Data Structures & Algorithms Interview Questions
At the four‑to‑eight‑year band, coding rounds stop being "can you invert a binary tree?" and start being "can you pick a pattern under pressure, explain trade‑offs, and write code another engineer would maintain?" Interviewers already assume you can loop; they want to see judgment—when to use a heap, when a monotonic deque is overkill, and how you recover when your first idea is wrong.
The STAR method is not a magic template for LeetCode. It is a way to attach your solutions to reality: the on‑call issue that felt like two pointers, the log parser that was secretly a sliding window, the pricing rule that mapped to interval merging. When you can name the situation and result in plain English, you sound senior even before you finish typing.
Use the hubs below as themed drills. For each topic, aim for three layers: recognize the pattern in under a minute, implement without IDE autopilot, and defend time and space complexity as if you were reviewing a junior's PR.
Trending Sub-topics
- Sliding Window — Fixed and variable windows on arrays and strings—think "longest substring without repeat" and throughput-style limits you have seen in APIs.
- Dynamic Programming — Counting paths, knapsack variants, and string DP where the real test is defining state cleanly and avoiding redundant recursion.
- Blind 75 — A high-signal list people still use because it overlaps with what shows up in real loops—not because the number 75 is sacred.
- Tree Traversals — BFS vs DFS, parent pointers, and the moment the interviewer turns a tree into a graph—usually without warning.
What interviewers quietly score
Clarity beats speed. Most "no hires" on coding come from fuzzy requirements, silent coding, or an inability to state invariants ("my window always contains at most k distinct characters"). Strong candidates narrate assumptions, write small helper functions, and test edge cases out loud—empty input, single element, duplicates, overflow-ish values.
A weekly rhythm that actually sticks
- Three timed blocks (45–60 min): one new pattern, one repeat from last week, one random "weak area" draw from your mistake log.
- One review-only day: no new problems—re-solve two older ones on a whiteboard or plain text editor with syntax highlighting off.
- One STAR pass: pick a solved problem and write five sentences that tie it to work: team, constraint, deadline, metric.
When you are stuck, say this
"I am going to try brute force first to learn the bounds, then look for redundant work." That sentence buys trust. Interviewers are humans; they want to see how you think when the optimal approach is not obvious. If you have shipped production code, mention how you would add logging or property tests—without derailing the problem—because it signals engineering maturity.
Code snapshots and problems that actually happen
Interviewers like it when you connect LeetCode patterns to telemetry, queues, or APIs you have touched. Here are two compact examples you can narrate—not copy-paste from prod, but honest shapes.
Sliding window: count distinct in the last N minutes of logs (Python shape)
# Rolling distinct users per minute-bucket (conceptual)
from collections import deque, defaultdict
def distinct_in_window(events, window_minutes):
# events: list of (timestamp_minute, user_id) sorted by time
q = deque()
counts = defaultdict(int)
out = []
for t, user in events:
q.append((t, user))
counts[user] += 1
while q and q[0][0] < t - window_minutes:
_, old = q.popleft()
counts[old] -= 1
if counts[old] == 0:
del counts[old]
out.append(len(counts))
return outPicture requests landing in Azure Application Insights or a Kusto query where support asks, "How many unique tenants hit this API during the outage window?" The interview version is the same muscle: evict the left edge when time moves forward, keep counts in a map, and say what breaks if events arrive out of order (you buffer or sort first).
Tree as org chart: BFS to notify managers (TypeScript shape)
type Node = { id: string; reports: Node[] };
function collectSubtreeIds(root: Node): string[] {
const q = [root];
const ids: string[] = [];
while (q.length) {
const n = q.shift()!;
ids.push(n.id);
for (const r of n.reports) q.push(r);
}
return ids;
}Same traversal shows up when a policy change in Azure AD or your HR graph needs to fan out: "everyone under this director receives an email" or "disable access for this subtree." In the room, mention cycle detection if someone accidentally made their manager their report—real directories are messy, and saying that aloud shows you have shipped org tools, not only textbook trees.
Questions with sample answers
These are interview-ready outlines—sound human by swapping in your own metrics, team names, and war stories. The examples are generic on purpose so you can map them to what you actually shipped.
Primary prompt
Given an array of integers, find the length of the longest contiguous subarray whose sum equals k. Walk through your invariant before you code.
Prefix sum + hash map:
sum[i]= cumulative sum; need j withprefix[j] = prefix[i] - k. Invariant: map stores earliest index for each prefix sum. O(n) time. If all non-negative, two-pointer also works.Negative numbers: two-pointer breaks; stick with prefix map.
Primary prompt
You have a string s and a set of forbidden substrings of length m. How do you detect the first valid window of length n in better than naive time?
Rolling hash (Rabin-Karp) over length-n window O(n) per shift amortized, compare only when hash matches; verify collision. Or Aho-Corasick if many forbidden patterns—scan once.
Primary prompt
Design a test strategy for a sliding-window solution: what edge cases must pass before you call it done?
Empty, window larger than array, all valid, never valid, ties on max/min, duplicates, boundary windows at start/end, stress random vs brute force for small n.
Primary prompt
Compare two candidate approaches for "minimum window substring"—what trade-offs do you expect in time, space, and implementation risk?
Expand-shrink two-pointer O(n) with char map vs brute force O(n³)—implementation risk is counting "formed" characters; space O(alphabet). Mention sliding window as lower bug risk once invariant clear vs generating all substrings.
Follow-ups interviewers often ask
Expect nested "why?" questions—brief answers here; expand with your production defaults.
Follow-up
What happens if elements can be negative? Does your approach still hold—why or why not?
Prefix-sum approaches for subarray sum k still hold. Non-negative-only tricks (shrinking while sum>k) fail with negatives—need full map of prefix sums.
Follow-up
How would you adapt this pattern to a streaming log where you cannot store the whole array?
Bounded deque for last W elements or aggregate stats; for sum=k with negatives, need window state or approximation— clarify requirements with interviewer.
Follow-up
Can you prove each index is visited a constant number of times?
Two pointers each move forward only; each index entered once as right and exited once as left—at most two visits.
Follow-up
How would you unit-test the window boundaries without relying on a massive golden file?
Property tests on small random arrays vs brute force O(n²); table-driven cases for boundaries; log window in debug builds only.
Follow-up
If the interviewer changes the objective from "longest" to "exactly k distinct," what breaks in your first draft?
Longest variable-window code often maximizes; for exact k you may need two passes (at most k vs at most k-1 trick) or different shrink condition—don't reuse without adjusting invariant.