DevPrep

All topics › Algorithms & data structures

Array complexity

Junior PRO

The gist

Array is a dynamic array: a contiguous buffer with count and capacity, a value type with copy-on-write. All the complexities follow from that.

var a = [1, 2, 3]
a.append(4)               // amortized O(1)
a.insert(0, at: 0)        // O(n)
a.removeLast()            // O(1)
a.removeFirst()           // O(n)
_ = a.contains(3)         // O(n)
_ = a[1]                  // O(1)
var b = a                 // O(1): shared buffer
b.append(5)               // O(n): first mutation copies the buffer (CoW)
a.reserveCapacity(1_000)  // so append doesn't reallocate

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store