Most interview problems are dressed-up array or string questions, and most efficient solutions lean on a hash map. This chapter covers those two structures plus the two patterns — two-pointer and sliding window — that turn brute-force O(n²) solutions into clean O(n) ones.
Arrays
An array stores elements contiguously, so indexing is O(1). But inserting/removing in the middle shifts everything after it:
| Operation | Cost |
|---|---|
| Index / update by position | O(1) |
| Append at end | O(1) |
| Insert / delete in the middle | O(n) |
| Search (unsorted) | O(n) |
Hash maps
A hash map (dict in Python, object/Map in JS) stores key→value pairs with O(1) average lookup, insert and delete. Whenever a brute-force solution scans the array again and again, ask: "could a hash map remember what I've seen?"
def two_sum(nums, target):seen = {} # value → indexfor i, n in enumerate(nums):need = target - nif need in seen: # O(1) lookupreturn [seen[need], i]seen[n] = ireturn None# Brute force is O(n^2); the hash map makes it O(n).
Two-pointer
On a sorted array, two indices moving toward each other (or in the same direction) solve many problems in one pass with O(1) extra space:
def pair_sums_to(nums, target): # nums is sortedlo, hi = 0, len(nums) - 1while lo < hi:s = nums[lo] + nums[hi]if s == target: return (lo, hi)if s < target: lo += 1 # need a bigger sumelse: hi -= 1 # need a smaller sumreturn None
Sliding window
For "longest/shortest subarray with property X", grow a window from the right and shrink from the left instead of re-checking every subarray:
def longest_unique(s):seen = set()left = best = 0for right, ch in enumerate(s):while ch in seen: # shrink until validseen.remove(s[left]); left += 1seen.add(ch)best = max(best, right - left + 1)return best
Practice
Solve: (1) Does an array contain any duplicate? (use a set) (2) Given a sorted array, find a pair summing to a target (two-pointer). (3) Find the length of the longest substring without repeating characters (sliding window).
Key takeaways
- 01Arrays index in O(1) but insert/delete in the middle is O(n).
- 02Hash maps give O(1) average lookup — the go-to for "have I seen this before?".
- 03Two-pointer solves many sorted-array problems in one pass with O(1) space.
- 04Sliding window handles longest/shortest-subarray problems in O(n).
- 05When you reach for a nested loop, check whether a map/pointer/window makes it linear.
