โ† Back to DSA
๐Ÿ“ฆ

Data Structures

Array

A contiguous block of memory storing elements of the same type, accessible by index in O(1) time.

Complexity

Time (Best)

O(1)

Time (Avg)

O(n)

Time (Worst)

O(n)

Space

O(n)

Key Points

  • โ€บRandom access in O(1) โ€” any element by index instantly
  • โ€บCache-friendly: elements stored contiguously in memory
  • โ€บInsertion/deletion at the front is O(n) โ€” all elements must shift
  • โ€บDynamic arrays (ArrayList, Vec) double capacity when full โ€” O(1) amortized append
  • โ€บBest choice when index-based access is the primary operation

Code Examples

Swift
var arr = [1, 2, 3, 4, 5]

// Access โ€” O(1)
let val = arr[2]           // 3

// Append โ€” O(1) amortized
arr.append(6)

// Insert at index โ€” O(n)
arr.insert(0, at: 0)

// Remove at index โ€” O(n)
arr.remove(at: 0)

// Search โ€” O(n)
if let idx = arr.firstIndex(of: 3) {
    print("Found at index \(idx)")
}

// Slice
let sub = arr[1...3]       // [2, 3, 4]

// Iterate โ€” O(n)
for num in arr { print(num) }

Practice Problems

Two Sum
Best Time to Buy and Sell Stock
Maximum Subarray
Product of Array Except Self