Member-only story

Using an Array as a built in index for LeetCode problems

Algorithms in Swift

Steven Curtis
4 min readJun 26, 2019
An example array with index places shown

Before We Start

Why?

O(n) solutions are often required in Interviews, and for some LeetCode problems. Rather than using extra space, we can use the property of arrays that they are ordered and have an intrinsic index in order to (often) find a missing Integer in an unsorted list

Prerequisites

To follow along you should be able to use Arrays, and understand the fact that they are zero-indexed. Some experience of using inout parameters could be beneficial (or you can just go with it).

Keywords and Terminology

  • Array: An ordered, random-access collection

Setting elements to their correct position

Let us make the example as simple as possible, and use only positive integers in an array. The challenge is to put them into a the correct order in an array

The sort solution:

This won’t get you far in an interview, but you might choose to use a simple in-built sort in Swift:

arr.sort()

A real in-place solution:

--

--

No responses yet