Arrays and Hashing (LeetCode #1)
Most “easy” array problems are easy for one reason: a hash map or hash set turns a repeated search into a single lookup. The brute force compares every pair; the hashed solution remembers what it has already seen and answers in \(O(1)\). If you learn nothing else from this series, learn to ask “can I remember this instead of searching for it?”
This post covers the nine NeetCode 150 Arrays & Hashing problems. Each one is restated in plain words, worked by hand on a concrete example, and explained before the code.
The technique
A hash set answers “have I seen this before?” and a hash map answers “what did I store for this key?” Both take average \(O(1)\) — constant time — because a hash function points directly at a bucket instead of scanning.
\[ \text{brute force } O(n^2) \;\longrightarrow\; \text{hash map } O(n) \text{ time},\ O(n) \text{ space} \]
We trade memory for speed: an extra structure of size up to \(n\) buys instant lookups. The recurring shapes:
- Membership — a
set; “is this a repeat?” - Counting — a
dict/Counter; value → how many times. - Complement — store what you need, not just what you have.
- Canonical key — a normal form (sorted string, count tuple) to group by.
- Prefix/suffix aggregates — precompute running values to avoid nested scans.
Keys must be immutable (hashable): strings and tuples work, lists do not.
Contains Duplicate
The question. Return True if any value in nums appears at least twice.
Input: [1, 2, 3, 1] -> True
Input: [1, 2, 3] -> False
The idea. Walk once, keeping a set of everything seen. If a value is already in the set, it is a repeat.
Walk it through on [1,2,3,1]: add 1 → {1}; add 2 → {1,2}; add 3 → {1,2,3}; 1 is present → True.
def contains_duplicate(nums):
seen = set()
for x in nums:
if x in seen:
return True
seen.add(x)
return False
\(O(n)\) time, \(O(n)\) space.
Valid Anagram
The question. Return True if t is an anagram of s (same letters, same counts, any order).
Input: s = "anagram", t = "nagaram" -> True
Input: s = "rat", t = "car" -> False
The idea. Anagrams have identical character counts. Compare the count dictionaries.
from collections import Counter
def is_anagram(s, t):
return Counter(s) == Counter(t)
\(O(n)\) time; \(O(k)\) space for the alphabet. Counting beats sorting (\(O(n \log n)\)) because order is irrelevant.
Two Sum
The question. Return the indices of the two numbers adding to target. Exactly one solution exists.
Input: nums = [2,7,11,15], target = 9 -> [0, 1]
The idea. For each x, its partner must be target - x. Store each value’s index as you go and look up the complement.
Walk it through [2,7,11,15], target 9: x=2, need 7, not seen → store 2:0; x=7, need 2, seen → return [0,1].
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, minimum width=0.7cm, minimum height=0.6cm, font=\small\ttfamily}]
\foreach \v [count=\i from 0] in {2,7,11,15} { \node[c, fill=blue!8] at (\i*0.8,0) {\v}; }
\node[font=\scriptsize\ttfamily, text=orange!75!black] at (0,-0.55) {need 7};
\draw[->, thick, orange!80!black] (0,-0.4) to[bend right=35] (0.8,-0.12);
\node[font=\rmfamily\small, text=black!60, anchor=north] at (1.2,-0.9) {remember complements, not pairs};
\end{tikzpicture}
def two_sum(nums, target):
seen = {}
for i, x in enumerate(nums):
need = target - x
if need in seen: # check BEFORE storing (no self-pairing)
return [seen[need], i]
seen[x] = i
return []
\(O(n)\) time, \(O(n)\) space. See Two Sum.
Group Anagrams
The question. Group words that are anagrams of each other.
Input: ["eat","tea","tan","ate","nat","bat"]
Output: [["eat","tea","ate"], ["tan","nat"], ["bat"]]
The idea. Two words are anagrams exactly when they have the same multiset of letters. So we need a canonical key — a normal form that is identical for every anagram of a word — and then bucket words by that key. Sorting a word’s letters gives such a key: "eat", "tea", and "ate" all become "aet".
Walk it through on ["eat","tea","tan","ate","nat","bat"]:
| word | sorted key | buckets so far |
|---|---|---|
| eat | aet | {aet: [eat]} |
| tea | aet | {aet: [eat, tea]} |
| tan | ant | {aet: [...], ant: [tan]} |
| ate | aet | {aet: [eat, tea, ate], ant: [tan]} |
| nat | ant | {aet: [...], ant: [tan, nat]} |
| bat | abt | {... , abt: [bat]} |
The bucket values are the groups.
from collections import defaultdict
def group_anagrams(words):
groups = defaultdict(list)
for w in words:
groups[tuple(sorted(w))].append(w) # "eat" -> ('a','e','t')
return list(groups.values())
Why it works. The map word → sorted-letters is many-to-one: every anagram collides on the same key, and non-anagrams never share a key because different letter multisets sort to different strings. defaultdict(list) makes the append safe without checking whether the key exists first.
Complexity. Sorting each of \(n\) words costs \(O(k \log k)\) for length \(k\), giving \(O(n k \log k)\) time and \(O(nk)\) space. When the alphabet is small, a 26-length count tuple as the key skips the sort and runs in \(O(nk)\).
Edge cases. Empty input → []; a single word → one group. The empty string is a valid word (key ()). Characters other than lowercase letters still work because sorting is by code point.
Top K Frequent Elements
The question. Return the k most frequent values.
Input: nums = [1,1,1,2,2,3], k = 2 -> [1, 2]
The idea. Count, then pick the top k. A size-\(k\) heap is \(O(n \log k)\); bucket sort by frequency is \(O(n)\) because frequencies are bounded by \(n\).
Walk it through counts {1:3, 2:2, 3:1}; buckets: bucket[3]=[1], bucket[2]=[2], bucket[1]=[3]; read down until k.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, minimum width=0.8cm, minimum height=0.55cm, font=\small\ttfamily}]
\node[b, fill=blue!10] at (0,1.1) {1}; \node[font=\scriptsize\ttfamily, anchor=east] at (-0.55,1.1) {3};
\node[b, fill=blue!10] at (0,0.4) {2}; \node[font=\scriptsize\ttfamily, anchor=east] at (-0.55,0.4) {2};
\node[b, fill=blue!10] at (0,-0.3) {3}; \node[font=\scriptsize\ttfamily, anchor=east] at (-0.55,-0.3) {1};
\draw[->, very thick, green!55!black] (0.9,1.35) -- (0.9,-0.1);
\node[font=\scriptsize\ttfamily, text=green!45!black, anchor=west] at (1.0,0.6) {read down};
\end{tikzpicture}
def top_k(nums, k):
counts = Counter(nums)
buckets = [[] for _ in range(len(nums) + 1)]
for value, freq in counts.items():
buckets[freq].append(value)
out = []
for freq in range(len(nums), 0, -1):
out.extend(buckets[freq])
if len(out) >= k:
return out[:k]
\(O(n)\) time and space.
Product of Array Except Self
The question. Return an array where output[i] is the product of all other elements. No division, in \(O(n)\).
Input: nums = [1, 2, 3, 4]
Output: [24, 12, 8, 6] (24 = 2·3·4, 12 = 1·3·4, ...)
Why not division? Division breaks on zeros, and the problem forbids it.
The idea. The product except nums[i] is the product of everything to its left times everything to its right. Precompute a left pass and a right pass. left[i] = product of nums[0..i-1]; right[i] = product of nums[i+1..]. Then output[i] = left[i] × right[i].
We can do it with one output array: fill it with prefix products left-to-right, then sweep right-to-left multiplying by a running suffix product.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, minimum width=0.6cm, minimum height=0.55cm, font=\small\bfseries}]
\foreach \v [count=\i from 0] in {1,2,3,4} { \node[c, fill=blue!8] at (\i*0.66,0) {\v}; }
\draw[->, thick, green!55!black] (-0.33,0.45) -- (2.3,0.45);
\draw[->, thick, orange!80!black] (2.3,-0.45) -- (-0.33,-0.45);
\node[font=\scriptsize\ttfamily, text=green!45!black] at (1.0,0.72) {prefix};
\node[font=\scriptsize\ttfamily, text=orange!75!black] at (1.0,-0.72) {suffix};
\end{tikzpicture}
Walk it through on [1,2,3,4]:
| i | prefix (left) | run suffix | output |
|---|---|---|---|
| 0 | 1 | 24 | 24 |
| 1 | 1 | 12 | 12 |
| 2 | 2 | 4 | 8 |
| 3 | 6 | 1 | 6 |
def product_except_self(nums):
n = len(nums)
out = [1] * n
prefix = 1
for i in range(n): # out[i] = product of everything left of i
out[i] = prefix
prefix *= nums[i]
suffix = 1
for i in range(n - 1, -1, -1): # multiply by everything right of i
out[i] *= suffix
suffix *= nums[i]
return out
Why it works. At index i, out[i] holds the left product; multiplying by the running suffix completes it. No division and no extra arrays.
\(O(n)\) time, \(O(1)\) extra space (the output does not count).
Edge cases. Zeros are handled naturally (the prefix/suffix become 0 where appropriate). One element → [1].
Valid Sudoku
The question. Given a 9×9 board of digits and .s, decide whether it is a valid Sudoku (no repeated digit in any row, column, or 3×3 box). It need not be solved.
Input: a valid partially-filled board -> True
The idea. “No duplicates within a group” is a set-membership test. Make a set for each row, each column, and each box; scan every cell and check it is not already in its three sets. The only tricky part is mapping a cell (r, c) to its box index:
\[ \text{box} = (r \parallel 3) \times 3 + (c \parallel 3) \]
Walk it through. Cell (4, 7) is in row 4, column 7, and box (4//3)*3 + (7//3) = 1*3 + 2 = 5. If '5' were already in rows[4], cols[7], or boxes[5], the board is invalid.
def is_valid_sudoku(board):
rows = [set() for _ in range(9)]
cols = [set() for _ in range(9)]
boxes = [set() for _ in range(9)]
for r in range(9):
for c in range(9):
d = board[r][c]
if d == ".":
continue
b = (r // 3) * 3 + c // 3
if d in rows[r] or d in cols[c] or d in boxes[b]:
return False
rows[r].add(d); cols[c].add(d); boxes[b].add(d)
return True
\(O(81)\) time and space — effectively \(O(1)\) for a fixed board.
Edge cases. An empty board is valid. The board is always 9×9.
Encode and Decode Strings
The question. Design encode(list_of_strings) -> single string and decode(string) -> list_of_strings such that any list of strings survives a round trip, including strings containing your separator.
Input: ["lint", "code", "love", "you"]
encode -> "4#lint4#code4#love3#you"
decode -> ["lint", "code", "love", "you"]
The idea. A delimiter alone fails if a string contains it. Prefix each string with its length and a delimiter: len#string. The decoder reads the length, then takes exactly that many characters — so the delimiter inside the content is harmless.
Walk it through decoding "4#lint4#code": read 4 up to #, then take the next 4 characters lint; read 4, take code. Done.
def encode(strs):
return "".join(f"{len(s)}#{s}" for s in strs)
def decode(s):
out, i = [], 0
while i < len(s):
j = s.index("#", i) # end of the length prefix
length = int(s[i:j])
out.append(s[j+1:j+1+length]) # take exactly `length` characters
i = j + 1 + length
return out
Why it works. The length prefix makes the format unambiguous: the decoder never guesses where a string ends, so any characters (including #) are safe.
\(O(n)\) time and space.
Edge cases. Empty list → "" and back to []. Empty strings → "0#". Multi-digit lengths work.
Longest Consecutive Sequence
The question. Given an unsorted array, return the length of the longest run of consecutive integers (e.g. 1,2,3,4).
Input: [100, 4, 200, 1, 3, 2]
Output: 4 (1, 2, 3, 4)
The idea. Put every number in a set for \(O(1)\) membership. Then, for each number, only start counting if it is the beginning of a run — that is, if x - 1 is not in the set. From such a start, count upward while start + length is present. Each number is visited once, so the total is \(O(n)\).
Walk it through on the input. For 1: 0 not in the set, so it starts a run: 2 yes, 3 yes, 4 yes, 5 no → length 4. For 2, 3, 4: their predecessors are present, so we skip them (they are not starts). For 100, 200: runs of length 1.
def longest_consecutive(nums):
s = set(nums)
best = 0
for x in s:
if x - 1 not in s: # x is the start of a run
length = 1
while x + length in s:
length += 1
best = max(best, length)
return best
Why it works. Counting only from run starts means each run is walked once, so despite the inner while, the total work is \(O(n)\) (the same amortized argument as a monotonic stack).
\(O(n)\) time, \(O(n)\) space.
Edge cases. Empty → 0. Duplicates are removed by the set. All consecutive → n.
Pitfalls
- Assuming worst-case \(O(1)\). Hash lookups degrade with collisions; for adversarial input, sort or use a tree.
- Using a list as a key. Lists are unhashable; convert to a tuple.
- Check-before-store in Two Sum. Storing first lets an element pair with itself.
- Counting when a set would do. Membership is smaller and faster than a full counter.
- Starting a consecutive run in the middle. Only count from values whose predecessor is absent, or you break the \(O(n)\) bound.
Why does Two Sum store values rather than pairs? How does Longest Consecutive Sequence stay \(O(n)\) with an inner while?
ASolution
It stores each value’s index so a later x returns the earlier partner’s index in one lookup. Longest Consecutive Sequence only starts counting from values whose predecessor is absent, so each run is walked exactly once and the total work across all starts is \(O(n)\).
Next: Two Pointers (LeetCode #2) — converging and same-direction pointers.