2025 Coding Interview Prep
Overall principles.
All data structures are variants of arrays and linkedlists.
What kind of problem is this? Basically all coding problems can be boiled down to enumeration. To write a efficient enumeration algorithm, we need to make sure the code enumerates in a fashion where there is no leftovers and redundancies.
- No leftovers: Chose the right algorithms.
- No redundancies: Utilize all the information.
When encounters a problem, use the following thinking paradigm:
- How do we enumerate by brute-forcing?
- DFS, BFS
- Backtracing, Dynamic program
- Is it possible to enumerate or traverse more efficiently?
- Sliding window
- Greedy
- Union Find
Linked List / Arrays
- Two pointers: fast/slow, left/right.
- Use DummyNode to simplify the edge cases.
- Make sure the tail is None and the constructed LinkedList has no cycles.
Sliding window
Problems related to Continuous sub-string, sub sequence.
def solution(array):
l = r = 0
# initialize window here using different data structures
window = ...
while r < len(array):
item = array[r]
r += 1
# Update window status.
window.add(item)
while l < r and needs shrink:
item = array[l]
window.remove(item)
l += 1
# Check if result update is needed.
Binary Tree
Pre-order, in-order, post-order.
- Can we solve the problem by traversing the tree once? -> Use a
void traverse()
function and aexternal variable
. - Can we solve the problem by * breaking down* the problem into smaller ones? -> Define a
recursive function
and utilize thereturn value
well.
搜索问题
本质上是图的遍历问题,每个state
如何遍历以找到target state
的问题。如何高效遍历:
- DFS/Backtracking
- BFS
BFS
本质是在一个图中求从start
到end
的最短距离。
from collections import deque
def bfs(start, end):
q = deque([start])
# Use set to achieve O(1) time complexity.
# Sometimes the state need to be convert to data structures
# that can be hashed and are immutable.
visited = set([start])
steps = 0
while q:
steps += 1
# The following line can be substitute by appending depth to the element.
for _ in range(len(q)):
cur = q.popleft()
if cur == end:
return cur
for next_node in get_next_steps(node):
if next_node not in visited:
q.append(next_node)
visited.add(cur)
# No path from start to end.
return None