Skip to content
Skilled.dev

Interactive tools

Coding interview pattern quiz with answer explanations

Practice choosing algorithms from constraints in 12 questions, compare alternatives, retry missed prompts, and study worked pattern guides.

Published · 4 min read

Question 1 of 12

Choose the approach that satisfies every stated constraint. Several alternatives can solve a related problem.

Count every contiguous subarray whose sum is K. Values may be positive, negative, or zero. Which approach gives expected O(n) time with a hash map?
Read all 12 questions and answer explanations

Open this reference after trying the questions, or use it to study the reasoning directly.

1. Count every contiguous subarray whose sum is K. Values may be positive, negative, or zero. Which approach gives expected O(n) time with a hash map?

Prefix sums plus a frequency map of earlier prefixes. If the current prefix is S, each earlier prefix S − K identifies one valid start. Count matches before inserting S so an empty interval is not counted. Seed the map with prefix zero once.

Follow-up: Trace [0, 0] with K = 0. Why must a prefix map store frequencies rather than a set?

Read prefix sums.

2. Find two distinct positions in an already sorted numeric array that sum to a target. Return any pair, use O(1) auxiliary space, and aim for O(n) time.

Move inward from the left and right endpoints. If the sum is too small, the current left value cannot pair successfully with any remaining value at or below the current right endpoint. Discard it. Use the symmetric argument when the sum is too large.

Follow-up: Explain why a sum that is too small lets you discard the current left value.

Read two pointers.

3. A predicate over indexes 0 through n − 1 is false for a prefix and true thereafter. One predicate call costs O(1). Find the first true index, returning n if none is true.

Binary-search the false/true boundary. A true midpoint keeps the first true index at or to its left; a false midpoint rules out everything through that midpoint. A half-open interval shrinks until its endpoints meet, including at the n sentinel.

Follow-up: Trace n = 0, an all-false input, and a first true value at index zero.

Read binary-search boundaries.

4. A directed graph may contain cycles. Every edge counts as one hop. Find a path with the fewest hops from a start vertex to a target.

BFS with a visited set and parent links. BFS discovers vertices in increasing hop distance. Mark a vertex when enqueuing it, record its parent, and reconstruct the route after reaching the target. The guarantee relies on equal edge costs.

Follow-up: Give a graph where DFS first discovers a longer route than BFS. What changes if edge weights differ?

Read bfs versus dfs.

5. For each temperature in an array, report how many positions until the next strictly warmer temperature, or zero if none exists. Aim for O(n) total time.

Keep unresolved indexes in a decreasing-temperature stack. When a warmer value arrives, resolve and pop every smaller temperature at the top. Those indexes have found their first warmer value. Each index is pushed once and popped at most once, giving linear total stack work.

Follow-up: For [70, 70, 71], which indexes should be resolved by the second 70?

Read monotonic stacks.

6. Values arrive in a stream of unknown length. After each value, retain the K largest values seen, including duplicates. K is much smaller than the stream. Use O(K) storage and O(log K) heap comparison work per update for K ≥ 2.

A min-heap containing at most K values. The root is the weakest retained candidate. Fill the heap, then replace the root only when an incoming value is larger. Sifting repairs the heap in logarithmic time; the retained array need not be sorted.

Follow-up: Why is the root of this heap the smallest retained value rather than the largest?

Read heaps and priority queues.

7. Generate every subset of n distinct values. Each output must be an independent array. Which method directly models the include-or-skip decisions?

Explore include/skip branches and copy the path at each leaf. Every sequence of n binary decisions maps to one subset. Undo a chosen value after returning from its branch, and copy completed paths so later mutations do not alter earlier outputs. Copying all subsets costs Θ(n·2ⁿ) total output work for n ≥ 1.

Follow-up: Why does saving the same mutable path object break the result? What is the output-size lower bound?

Read backtracking.

8. Choose values from a line to maximize their sum, with no two chosen positions adjacent. Choosing nothing is allowed, and values may be negative. Return only the best sum.

Track the best sum through the previous one and two positions. For the current value, compare skipping it with taking it plus the best answer ending before its neighbor. Two running states suffice. Initial zero states allow an empty selection and keep an all-negative answer at zero.

Follow-up: Test [4, 5, 4] against choosing the largest available value greedily. What should an all-negative array return?

Read dynamic programming.

9. Find the longest contiguous substring with no repeated Unicode code point. Aim for expected O(n) time, where n is the number of code points.

A window with a set or frequency map, advancing the left edge until valid. Each rightward extension introduces at most one repeated code point. Removing leftmost code points can restore uniqueness. Both pointers move forward at most n times. In JavaScript, iterate code points deliberately; user-perceived grapheme clusters need a separate definition.

Follow-up: Trace abba. Can removing a leftmost character introduce a repeated character into a valid window?

Read sliding windows.

10. An array never changes after construction. Answer many sum queries over half-open index ranges [left, right). Spend O(n) preprocessing to make each query O(1).

Store a leading-zero prefix array and subtract prefix[right] − prefix[left]. The two prefixes contain the same contribution before left; subtraction removes it. A leading zero also handles ranges starting at zero and empty ranges. The static-input assumption avoids costly prefix repairs after updates.

Follow-up: What should a query for [3, 3) return? How does a point update affect later prefix values?

Read prefix sums.

11. In a sorted numeric array with duplicates, find the first position whose value is at least target. Return the length if every value is smaller.

Find the first true index of values[index] ≥ target. The predicate is false for smaller values and true from the lower bound onward. On equality, retain the midpoint as a possible boundary and search to its left. The length sentinel handles a missing boundary.

Follow-up: For [2, 2, 2, 5] and target 2, what is the answer? Why can equality not return the midpoint immediately?

Read binary-search boundaries.

12. Count subarrays summing to 3 in [4, −1]. A proposed algorithm discards the leftmost value as soon as its running sum exceeds 3. Which observation invalidates that algorithm?

A later negative value can lower the sum to the target after a valid start was discarded. The whole interval [4, −1] sums to 3. Dropping 4 immediately loses it. A shrinking rule needs a monotone argument; signed values break this one. Prefix differences with frequencies preserve the earlier start.

Follow-up: Write a tiny exhaustive subarray counter and use it to test a prefix-frequency solution.

Read prefix sums and signed values.

Answers stay in this page and reset when you reload. No account is required.

Choose an algorithm from the constraints in a problem statement, then check the explanation and compare alternatives. This quiz covers two pointers, sliding windows, prefix sums, binary-search boundaries, graph traversal, backtracking, dynamic programming, monotonic stacks, and heap-based selection.

Each prompt states the output, relevant input properties, and a time or space target when those affect the choice. Several options can solve a related task. Select the one that meets the complete contract given here. After answering, use the follow-up to test whether you can explain the choice beyond recognizing its name.

Read constraints before matching a pattern

A sorted pair-sum problem with constant auxiliary space suggests two pointers. Remove the sorted-input guarantee and that elimination proof disappears. A hash map can handle unsorted values in expected linear time, but uses additional space. Choosing between them requires reading both the input and memory requirements.

A contiguous sum target does not automatically imply a sliding window. Negative values can reduce an oversized sum after a start has been discarded. Prefix sums with a frequency map can count matching signed subarrays because the method tracks earlier cumulative totals rather than assuming sums move in one direction.

Likewise, “shortest path” needs an edge-cost qualification. BFS gives fewest-hop paths in an unweighted graph. If edges have different nonnegative weights, counting queue layers is insufficient to minimize total weight. The quiz's graph prompt deliberately says every edge counts as one hop.

Check what an answer must return

Finding any matching value differs from finding its first position. When duplicate values exist, returning immediately on an equal binary-search midpoint can produce a valid match without producing the requested boundary. A lower-bound search keeps equality as a possible upper boundary and continues left.

Generating every subset differs from returning a count or an existence answer. Materializing the outputs has exponential cost, and each saved path needs an independent array. A method that quickly identifies one large-sum subset cannot satisfy a request for every subset.

For the K largest arrivals in a stream, the heap must expose the weakest retained candidate. A min-heap does that even though the desired output contains large values. The result can be the right multiset without being sorted. State whether output order is part of the contract before adding a final sort.

Use the explanations after an attempt

Check answer reveals the selected approach and its reasoning. If your choice differs, read the explanation of why it violates a stated constraint. Compare every alternative for the remaining explanations. Some alternatives are correct algorithms with a slower bound or a larger memory requirement; others change the problem by sorting away original positions.

Before advancing, answer the follow-up aloud or write a small trace. The question about signed subarrays asks why a frequency map needs counts instead of membership alone. The warmer-temperature question asks what equal temperatures resolve. These checks target state meaning and comparison rules that a pattern label can hide.

The complete question bank and correct explanations are also available in the expandable reference. Use it for direct study or a keyboard-readable review after a round. The reference includes the same prompts and follow-ups, so there is no need to retain a separate answer key.

Treat the score as a practice record

The result reports correct answers in the current round. Retry missed questions starts a new round containing those prompts, with fresh answers. Start all questions again returns to the full set. Neither action claims to estimate interview performance, and repeated exposure can make answer recognition easier than independent problem solving.

Answers remain in this page and reset on reload. There is no account requirement, saved profile, or ranking among learners. If you want a lasting record, write down the prompt, your wrong assumption, and a counterexample that invalidates it. That note is more useful for later practice than preserving a percentage without its mistakes.

A perfect round is a reason to attempt implementation. Choose one approach, close its guide, and build it from the contract. Compare against an independent slower baseline on small inputs. Then change one assumption, such as allowing negative values, requesting the first occurrence, or imposing a smaller space budget, and determine whether your proof survives.

Turn missed questions into focused exercises

After a prefix-sum miss, trace [0, 0] with target zero. Distinguish the three nonempty intervals and identify which earlier zero boundary supplies each one. After a stack miss, trace [70, 70, 71] and explain why equality must remain unresolved for a strictly warmer answer.

After a DP miss, compare taking the largest value in [4, 5, 4] with taking both outside values. Write the recurrence in terms of skipping or taking the current position, then test an all-negative input when an empty selection is allowed. After a backtracking miss, mutate one returned subset and check whether another result changes.

Use the pattern guides for the worked implementations and the study-plan builder to reserve time for a fresh attempt. For a complete problem discussion, finish by explaining your invariant, complexity, and smallest useful counterexample using the solution walkthrough guide.

Practice in the course

Open a lesson to work through its explanation and examples. Coding exercises include an editor; available code languages are shown in each lesson.

Continue learning