โ 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
EasyLeetCode โ
Best Time to Buy and Sell Stock
EasyLeetCode โ
Maximum Subarray
MediumLeetCode โ
Product of Array Except Self
MediumLeetCode โ