Hash maps for O(1) lookup, sets for uniqueness, counters for frequency — these primitives unlock a huge class of interview problems.
Problems: 9
Easy: 3
Medium: 6
Hard: 0
Learning approach: Read the problem. Try the test cases yourself first.
Click Hint if stuck — it guides without spoiling.
Use Show Solution only after a genuine attempt.
Then hit Let's Code to run your solution live.
Key idea: Two strings are anagrams iff they have exactly the same character frequencies. Counter builds a frequency dict in O(n); comparing two dicts is O(k) where k is the alphabet size.
For each number, what value would pair with it to reach the target? Have you seen that value before?
Python Solution
def twoSum(nums, target):
seen = {} # value → index
for i, n in enumerate(nums):
complement = target - n
if complement in seen:
return [seen[complement], i]
seen[n] = i
Key idea: For each element, compute complement = target - n. If the complement is already in the hash map, we found the pair. Store indices as we go.
Two strings are anagrams iff their sorted versions are identical. Use the sorted string as a dictionary key.
Python Solution
from collections import defaultdict
def groupAnagrams(strs):
groups = defaultdict(list)
for s in strs:
key = tuple(sorted(s))
groups[key].append(s)
return list(groups.values())
Key idea: Sort each string — anagrams produce the same sorted tuple. Use that as a hash map key to bucket strings into groups.
Time: O(n·k log k) — n strings, each of length k sorted. Space: O(n·k).
Design an algorithm to encode a list of strings to a single string, and decode it back. The encoded string is sent over the network and decoded on the other side.
Delimiters like commas won't work if strings contain them. What if you prefix each string with its length?
Python Solution
class Codec:
def encode(self, strs):
# Format: '{length}#{string}' for each string
return ''.join(f'{len(s)}#{s}' for s in strs)
def decode(self, s):
result = []
i = 0
while i < len(s):
j = s.index('#', i) # find delimiter
length = int(s[i:j]) # extract length
result.append(s[j+1:j+1+length])
i = j + 1 + length # advance past this string
return result
Key idea: Prefix each string with its length and a # delimiter. During decode, read the length first, then slice exactly that many characters — no ambiguity even if strings contain special characters.
Time: O(n·k) for both encode and decode. Space: O(n·k).
For each index, you need (product of everything to the left) × (product of everything to the right). Can you compute both in two separate passes?
Python Solution
def productExceptSelf(nums):
n = len(nums)
output = [1] * n
# Forward pass: output[i] = product of nums[0..i-1]
prefix = 1
for i in range(n):
output[i] = prefix
prefix *= nums[i]
# Backward pass: multiply in suffix products
suffix = 1
for i in range(n - 1, -1, -1):
output[i] *= suffix
suffix *= nums[i]
return output
Key idea: Two passes. Forward pass fills output[i] with the product of everything to the left. Backward pass multiplies in the product of everything to the right.
Time: O(n). Space: O(1) extra (output array doesn't count).
Determine if a 9×9 Sudoku board is valid. Only filled cells need to be validated: each row, column, and 3×3 box must contain unique digits 1–9.
Test Cases
# board = 9x9 grid with '.' for empty cells
isValidSudoku(board) → True or False
set per row/col/boxfloor division for box indexO(81)
Use 9 sets for rows, 9 for columns, and 9 for 3×3 boxes. How do you map (row, col) to a box index?
Python Solution
def isValidSudoku(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):
val = board[r][c]
if val == '.':
continue
box_idx = (r // 3) * 3 + (c // 3)
if (val in rows[r] or val in cols[c]
or val in boxes[box_idx]):
return False
rows[r].add(val)
cols[c].add(val)
boxes[box_idx].add(val)
return True
Key idea: Maintain 27 sets (9 rows + 9 cols + 9 boxes). Map (r, c) to box index via (r//3)*3 + c//3. If any digit appears twice in the same set, the board is invalid.
Put all numbers in a set. For each number, check if it's the START of a chain (i.e., n-1 is NOT in the set). Only then count forward.
Python Solution
def longestConsecutive(nums):
num_set = set(nums)
best = 0
for n in num_set:
# Only start a chain from the smallest number in it
if n - 1 not in num_set:
length = 1
while n + length in num_set:
length += 1
best = max(best, length)
return best
Key idea: For each number that is the start of a chain (no predecessor in the set), count how long the chain extends. Each number is visited at most twice total, giving O(n).