Coding Interview Patterns Flashcards: Signals, Invariants & Complexity
Practice coding interview patterns with 210 English flashcards on problem signals, invariants, complexity, edge cases, and choosing between approaches. Language-agnostic DSA review to pair with hands-on coding.
Over dit deck
Coding interview patterns become useful when you can explain why an approach fits. These 210 English flashcards practice recognizing problem signals, stating invariants, checking prerequisites, comparing approaches, and diagnosing a broken assumption.
The sequence starts with constraints and complexity, then moves through arrays, strings, hashing, two pointers, sliding windows, prefix sums, binary search, intervals, stacks, linked lists, trees, heaps, tries, graphs, union-find, topological sorting, backtracking, greedy choices, dynamic programming, and bit techniques. Each topic builds from its basic idea toward the conditions that make it work.
Cards map short scenarios to candidate patterns, named patterns to invariants and costs, and failed assumptions to explanations or alternatives. Selected contrast prompts distinguish neighboring ideas such as subarrays and subsequences, BFS and DFS, or greedy choice and dynamic programming. Mechanical reverse cards, problem-number recall, language-specific API memorization, and full solution listings are excluded because they add little to this reasoning-focused review. Answer each prompt before turning the card, then test the idea by coding a fresh example.
This is a language-agnostic companion to practical DSA exercises. It complements the Blind 75 Python solutions deck by teaching reusable reasoning across problems. It was authored independently in English, not translated or paraphrased from another catalog package.
The questions, answers, organization, metadata, and original generated cover are released under CC0 1.0 to the extent applicable rights exist. Algorithm facts are common knowledge; no commercial deck text or third-party media was copied. This is an independent study resource with no affiliation to an employer or interview platform.
Kaarten in dit deck
Kaart 1
Vraag
Which input constraints should you clarify before choosing an interview algorithm?
Antwoord
Input size, value range, ordering, duplicates, allowed mutations, and the exact output. These determine which operations are affordable and which assumptions are valid.
Kaart 2
Vraag
What does a loop invariant describe?
Antwoord
A property that holds at a defined point in every iteration. Show it holds initially, survives an iteration, and implies the result when the loop ends.
Kaart 3
Vraag
When analyzing nested loops, why can multiplying their written bounds overestimate runtime?
Antwoord
The loops may share progress. If an inner pointer only advances across the input once, its total work can be O(n), even inside an outer loop.
Kaart 4
Vraag
What is the difference between auxiliary space and total space?
Antwoord
Auxiliary space counts extra working storage. Total space also includes the input and, depending on the stated convention, the output. State which measure you report.
Kaart 5
Vraag
What does amortized O(1) mean for an operation sequence?
Antwoord
The total cost of m operations is O(m), even if some individual operations are expensive. It is a sequence-wide bound, not a probability claim.
Kaart 6
Vraag
How does a counterexample help evaluate a proposed greedy rule?
Antwoord
One valid input where the rule fails disproves it. Try small cases that force a locally attractive choice to block a better later choice.
Kaart 7
Vraag
Why should an algorithm's correctness argument address termination separately?
Antwoord
Preserving the right property is not enough if the loop never stops. Identify a bounded measure that moves strictly toward termination.
Kaart 8
Vraag
What runtime lower bound follows from returning k separate results?
Antwoord
At least Ω(k) time to emit them, or more if each result has multiple elements. Include output size when analyzing enumeration algorithms.
Kaart 9
Vraag
What should you say when quoting expected O(1) hash-table lookup?
Antwoord
It assumes a suitable hash distribution and controlled load factor. It is not a worst-case guarantee; hashing a long key can also cost time.
Kaart 10
Vraag
Which edge cases best expose index and boundary errors?
Antwoord
Empty input, one element, all equal elements, and answers at either end. Also check the smallest input that enters each branch.
Kaart 11
Vraag
Why can sorting be an invalid optimization even when it reduces later search work?
Antwoord
Sorting may destroy required order or original indices. Preserve the needed information or choose an approach that respects the input contract.
Kaart 12
Vraag
What does an exchange argument establish in a greedy proof?
Antwoord
That an optimal solution can be changed to include the greedy choice without making its objective worse. The remaining problem must still fit the same reasoning.
Kaart 13
Vraag
Why can recursion use O(n) space even without an explicit collection?
Antwoord
Each active call occupies a stack frame. A chain of n calls can therefore need O(n) auxiliary space.
Kaart 14
Vraag
What evidence should accompany a faster solution after presenting brute force?
Antwoord
Name the repeated work or discarded search space, explain why the shortcut is safe, and give the resulting time and space bounds.
Kaart 15
Vraag
What makes an array useful when a problem repeatedly accesses positions by index?
Antwoord
Constant-time indexed access in the usual RAM model. Inserting or removing near the front can still require shifting O(n) elements.
Kaart 16
Vraag
What should 'one character' mean before solving a string problem?
Antwoord
Clarify whether the unit is a byte, code unit, Unicode code point, or user-perceived character. Indexing and length depend on that choice.
Kaart 17
Vraag
An unsorted array needs a duplicate-existence check. Which structure fits?
Antwoord
A hash set of values seen so far. Stop when a value is already present; expected O(n) time and O(n) space.
Kaart 18
Vraag
For two-sum on an unsorted array, what should a hash map store?
Antwoord
Previously seen values mapped to their indices. For each value x, look for target − x before inserting x, so the same position is not reused.
Kaart 19
Vraag
When does a frequency array beat a hash map for counting?
Antwoord
When keys come from a small known integer or character range. Direct indexing gives predictable access with space proportional to that range.
Kaart 20
Vraag
Why is repeated concatenation risky when constructing a long immutable string?
Antwoord
Each append may copy the existing prefix, producing quadratic total work. Collect pieces and join them, or use an appropriate mutable builder.
Kaart 21
Vraag
How can you group anagrams without comparing every pair of words?
Antwoord
Map a canonical character signature to a group. Sorted characters work; a frequency tuple works when the alphabet and character rules are fixed.
Kaart 22
Vraag
What information does a set lose compared with a frequency map?
Antwoord
Multiplicity. A set can answer whether a value exists but cannot distinguish one occurrence from several.
Kaart 23
Vraag
How can a hash set support finding the longest consecutive integer run in expected O(n) time?
Antwoord
Start scanning a run only at values whose predecessor is absent. Each distinct value then belongs to one forward scan; iterate distinct values.
Kaart 24
Vraag
Why can a mutable object be a dangerous hash-map key?
Antwoord
Changing fields used by its hash or equality can make the stored entry unreachable by ordinary lookup. Use immutable keys or stable key values.
Kaart 25
Vraag
An array contains only integers from 0 through k. When is counting sort attractive?
Antwoord
When k is small enough: count each value and reconstruct the order in O(n + k) time with O(k) count storage. General arbitrary keys need another approach.
Kaart 26
Vraag
How can a single scan find both the minimum value and its earliest index?
Antwoord
Keep the current minimum and index; update only on a strictly smaller value. Updating on equality would select a later occurrence.
Kaart 27
Vraag
How do you compare two strings as multisets of characters?
Antwoord
Compare character counts under the same character interpretation. Order does not matter, but every character's multiplicity does.
Kaart 28
Vraag
Why does a hash collision not imply that two keys are equal?
Antwoord
A hash compresses many possible keys into fewer codes. A correct table also checks key equality when resolving collisions.
Kaart 29
Vraag
When is sorting a useful preprocessing step for detecting duplicate values?
Antwoord
When reordering is allowed and O(n log n) time is acceptable. Equal values become adjacent, so a scan finds duplicates without a separate hash set.
Kaart 30
Vraag
What is the key distinction between a subarray and a subsequence?
Antwoord
A subarray is contiguous. A subsequence preserves relative order but may skip positions. Sliding-window methods usually depend on contiguity.
Kaart 31
Vraag
For an unsorted two-sum query, how do hashing and sorting trade off?
Antwoord
Hashing gives expected O(n) time with O(n) extra storage. Sorting plus two pointers costs O(n log n) time and requires care with original indices and mutation.
Kaart 32
Vraag
How can a frequency map detect whether any permutation of a string can be a palindrome?
Antwoord
Count odd frequencies. At most one character may have an odd count; all other occurrences must form mirrored pairs.
Kaart 33
Vraag
Why must compound hash keys encode boundaries unambiguously?
Antwoord
Naive concatenation can merge different tuples into the same key, such as (1, 23) and (12, 3). Use tuples or a length-aware encoding.
Kaart 34
Vraag
What does coordinate compression preserve about numeric values?
Antwoord
Their relative order and equality, by replacing distinct sorted values with ranks. It does not preserve numeric distances or sums.
Kaart 35
Vraag
How can you compute products except self without division?
Antwoord
Combine the product strictly before each position with the product strictly after it. Prefix and suffix passes handle zeros; use a numeric type large enough for the products.
Kaart 36
Vraag
Why can a count of matching pairs overflow even when every input value fits in an integer?
Antwoord
The number of matching pairs can grow quadratically with the input length. Size the result type for the count, not just the input values.
Kaart 37
Vraag
A sorted array needs a pair with a target sum. Which search pattern fits?
Antwoord
Opposite-end two pointers. Compare the endpoint sum with the target and move the endpoint that can move the sum in the needed direction.
Kaart 38
Vraag
What invariant supports in-place removal of unwanted array values with read and write pointers?
Antwoord
The prefix before write contains exactly the retained values from the processed input, in order. Read scans every input position once.
Kaart 39
Vraag
How can two pointers check a palindrome without constructing a reversed string?
Antwoord
Compare matching elements from opposite ends and move inward. Any mismatch rejects it; the pointers meeting or crossing completes the check.
Kaart 40
Vraag
When does a fixed-size sliding window apply?
Antwoord
When every candidate is a contiguous block of the same length and its summary can be updated as one element enters and one leaves.
Kaart 41
Vraag
What invariant should a longest-window algorithm restore after adding a new rightmost element?
Antwoord
The current window satisfies the required constraint. Move the left boundary and update state until validity returns, then consider its length.
Kaart 42
Vraag
Why is moving the left pointer safe when a sorted-array endpoint sum is too small?
Antwoord
With that left value, every candidate at or before the current right endpoint gives an equally small or smaller sum. The left position cannot form a valid pair.
Kaart 43
Vraag
How does a three-way partition maintain separate regions?
Antwoord
Track a low region, a middle region, an unclassified region, and a high region. Each step shrinks the unclassified region by placing one element correctly.
Kaart 44
Vraag
How do you update the sum when a fixed-size window moves one position?
Antwoord
Subtract the outgoing value and add the incoming value. After initializing the first window, all moves together take O(n) time.
Kaart 45
Vraag
Why can a variable sliding window run in O(n) despite a nested shrink loop?
Antwoord
Each boundary advances at most n times. With constant-time state updates, the total number of additions and removals is linear.
Kaart 46
Vraag
For the longest substring without repeated characters, what window state is useful?
Antwoord
Character counts or last-seen positions. Move the left boundary past the conflicting occurrence while ensuring it never moves backward.
Kaart 47
Vraag
Why does opposite-end target-sum search fail on a generally unsorted array?
Antwoord
Moving an endpoint no longer changes the sum predictably. The algorithm can discard a valid pair because the order-based elimination proof is missing.
Kaart 48
Vraag
A positive-number array needs the shortest nonempty subarray with sum at least a positive T. When should the left boundary move?
Antwoord
While the current sum is at least T, record the length and remove the leftmost value. Positive values make further shrinking reduce the sum predictably.
Kaart 49
Vraag
For windows with at most k distinct values, what must happen when an outgoing count becomes zero?
Antwoord
Remove that value from the active distinct set or decrement the distinct counter. A zero count must not still count as present.
Kaart 50
Vraag
What changes when a fixed-window length exceeds the input length?
Antwoord
There is no complete window. Return the contract's empty or missing-result value instead of treating a partial block as a valid candidate.
Kaart 51
Vraag
How do you merge two sorted arrays with forward pointers?
Antwoord
Repeatedly take the smaller unconsumed element, then append the remaining suffix. Each element is consumed once, giving O(m + n) time.
Kaart 52
Vraag
Why must a minimum-cover substring track multiplicities of required characters?
Antwoord
A target can require the same character more than once. A set of required characters would mark an undersupplied window as complete.
Kaart 53
Vraag
How can counting subarrays with exactly k distinct values, for k ≥ 1, use an at-most helper?
Antwoord
Compute atMost(k) − atMost(k − 1). The helper counts all valid subarrays ending at each right boundary after restoring the distinct-value limit.
Kaart 54
Vraag
Why can a negative value break the usual shortest-sum sliding-window argument?
Antwoord
Removing it increases the sum, and adding one can decrease the sum. The monotonic relation between window size and sum no longer holds.
Kaart 55
Vraag
What does 'fast and slow pointers' mean when removing duplicates from a sorted array?
Antwoord
A read pointer scans candidates while a write pointer marks the next unique slot. Sorting makes equal values adjacent, so the retained prefix can stay compact.
Kaart 56
Vraag
What invariant prevents overwriting unread data during a backward merge into spare array capacity?
Antwoord
The suffix after the write pointer already contains the largest merged elements. Filling from the end leaves the remaining source elements unread and intact.
Kaart 57
Vraag
Why is 'find a contiguous range' alone insufficient to justify a variable sliding window?
Antwoord
You also need a safe boundary-movement rule. Check how adding and removing elements affect the condition; contiguity by itself gives no such guarantee.
Kaart 58
Vraag
After restoring an at-most window's validity, why are there right − left + 1 valid subarrays ending at right?
Antwoord
Every suffix starting between left and right is valid when removing elements cannot violate the constraint. Count those starts, including the one-element suffix.
Kaart 59
Vraag
How can you avoid duplicate value pairs in a sorted two-pointer enumeration?
Antwoord
After emitting a pair, skip equal values on both sides. First confirm the output wants unique value pairs, since index-pair counting needs different handling.
Kaart 60
Vraag
When does a character-frequency sliding window detect an anagram of a pattern?
Antwoord
When the window has the pattern's length and identical character counts. Maintain count differences or a mismatch counter as the window moves.
Kaart 61
Vraag
What does a prefix-sum array P mean when P[0] = 0?
Antwoord
P[i] is the sum of the first i input elements. The extra zero represents the empty prefix and makes ranges beginning at index 0 work uniformly.
Kaart 62
Vraag
When is binary search valid on a Boolean predicate over ordered candidates?
Antwoord
When the predicate changes at most once, such as false then true. The search uses that monotonic boundary to discard a whole interval.
Kaart 63
Vraag
Which workload favors a difference array?
Antwoord
Many range additions followed by final value reconstruction. Mark each range's start and end changes, then take one prefix sum.
Kaart 64
Vraag
In a lower-bound search over [lo, hi), what does hi initially equal for an n-element array?
Antwoord
n, an exclusive boundary. The result can equal n when no element is at least the target, so do not index the array without checking.
Kaart 65
Vraag
For a static array, how do prefix sums answer the half-open range [l, r)?
Antwoord
Return P[r] − P[l]. Building P takes O(n) time and space; each range-sum query then takes O(1).
Kaart 66
Vraag
How can prefix sums count subarrays whose sum equals k when negative values are allowed?
Antwoord
For each current prefix p, add the number of earlier prefixes equal to p − k, then record p. A frequency map gives expected O(n) time.
Kaart 67
Vraag
Why is binary-searching an answer different from binary-searching an input array?
Antwoord
The candidates are possible result values. A feasibility check tells which side contains the boundary, even if the original input is unsorted.
Kaart 68
Vraag
How does a difference array encode an addition of v to [l, r)?
Antwoord
Add v at l and subtract v at r, using a boundary slot when needed. The reconstructed prefix totals apply v only within that range.
Kaart 69
Vraag
For lower bound, how should equality with the target move the search boundary?
Antwoord
Move hi to mid. An equal element is a candidate, but an earlier equal or qualifying element may still exist.
Kaart 70
Vraag
Why initialize the prefix-frequency map with zero appearing once?
Antwoord
It represents the empty prefix before the array. This lets a subarray starting at index 0 contribute to the count.
Kaart 71
Vraag
Why are plain prefix sums inconvenient for many interleaved point updates and range-sum queries?
Antwoord
Changing one value can invalidate a long suffix of prefix sums. A Fenwick tree or segment tree can support both operations in O(log n).
Kaart 72
Vraag
How can you binary-search the minimum capacity needed to finish ordered work within a deadline?
Antwoord
Define whether a capacity suffices, prove larger capacities remain feasible, bracket a feasible answer, and search for the first feasible capacity.
Kaart 73
Vraag
What must every binary-search iteration do to guarantee termination?
Antwoord
Strictly shrink the candidate interval while preserving the boundary invariant. Mixing inclusive and exclusive update rules can leave the same interval unchanged.
Kaart 74
Vraag
For the longest subarray with a specified sum, which occurrence of each prefix sum should you retain?
Antwoord
The earliest index. For a later endpoint, it gives the longest matching span; overwriting it with a later occurrence can shorten the answer.
Kaart 75
Vraag
What runtime should you report for binary search with a nonconstant feasibility check?
Antwoord
O(C log R), where C is one check's cost and R is the number of discrete candidates. Include any preprocessing separately.
Kaart 76
Vraag
How can prefix sums turn a longest balanced binary subarray into an equal-prefix problem?
Antwoord
Map one symbol to +1 and the other to −1. Equal prefix sums enclose a zero-sum range with equal counts of the two symbols.
Kaart 77
Vraag
What is upper bound in a sorted array?
Antwoord
The first position whose value is strictly greater than the target, or n if none exists. Lower bound instead finds the first value at least the target.
Kaart 78
Vraag
Why must a prefix-sum counting algorithm query before recording the current prefix?
Antwoord
Recording first can count the empty subarray ending at the current boundary, especially for target zero. Query only earlier prefixes for nonempty ranges.
Kaart 79
Vraag
How do you safely compute a midpoint in a fixed-width integer search?
Antwoord
Use lo + (hi − lo) / 2 with integer division when the nonnegative difference fits the type. Choose bounds or a wider type that also keep the subtraction safe.
Kaart 80
Vraag
Why can duplicate values degrade searching a rotated sorted array to O(n)?
Antwoord
Equal endpoints and midpoint can hide which side is sorted. Some cases permit discarding only one boundary element at a time.
Kaart 81
Vraag
What preprocessing usually simplifies merging overlapping intervals?
Antwoord
Sort by start coordinate. Keep the current merged interval and either extend its end or emit it when the next interval starts beyond it.
Kaart 82
Vraag
Which data structure matches nested bracket validation?
Antwoord
A stack of unmatched opening brackets. Each closing bracket must match the most recent unmatched opener, and the stack must be empty at the end.
Kaart 83
Vraag
A problem asks for each element's next greater element. Which pattern is promising?
Antwoord
A monotonic stack of unresolved positions. A new larger value resolves the smaller pending values it overtakes.
Kaart 84
Vraag
Why must interval endpoint conventions be explicit?
Antwoord
Touching endpoints overlap for closed intervals, but adjacent half-open intervals do not. The convention changes merge tests and event ordering.
Kaart 85
Vraag
How can a sweep line find the maximum number of simultaneous intervals?
Antwoord
Turn starts and ends into signed events, sort by coordinate, and track the running active count. Handle same-coordinate ties according to the endpoint convention.
Kaart 86
Vraag
Why is one pass after sorting enough to merge intervals?
Antwoord
No later interval starts earlier than the next one being inspected. Once that start is beyond the current end, future intervals cannot bridge the gap.
Kaart 87
Vraag
What information should a stack store for next-greater distances?
Antwoord
Indices, so the distance is currentIndex − previousIndex. Values alone do not identify positions or distinguish repeated occurrences.
Kaart 88
Vraag
Why is counting opening and closing brackets insufficient to validate their sequence?
Antwoord
Counts ignore order and nesting. A closing bracket may appear before its opener, or bracket types may cross despite balanced totals.
Kaart 89
Vraag
For half-open intervals [start, end), how should equal-time starts and ends affect room counts?
Antwoord
Process ends before starts, or aggregate their net change before evaluating the active count for the next segment. A room freed at time t can be reused at t.
Kaart 90
Vraag
Why is a monotonic-stack algorithm often O(n) even though one step can pop many items?
Antwoord
Each item is pushed once and popped at most once. Summed across the scan, stack operations are linear.
Kaart 91
Vraag
How can a stack help simplify an absolute filesystem path lexically?
Antwoord
Process components: ignore empty components and '.', pop for '..' when possible, and push ordinary names. This lexical result does not resolve symbolic links.
Kaart 92
Vraag
How can a monotonic deque find each sliding-window maximum?
Antwoord
Keep candidate indices in decreasing value order. Remove expired indices from the front and dominated values from the back; the front gives the maximum.
Kaart 93
Vraag
What mistake can lose coverage when merging an interval contained inside the current one?
Antwoord
Replacing the current end with the new end. Use the larger end so a nested interval cannot shrink the merged coverage.
Kaart 94
Vraag
For a strictly next-greater query, what should happen to an equal-valued stack entry?
Antwoord
Do not resolve it with the equal value. With a decreasing stack of unresolved indices, pop only when the new value is strictly greater.
Kaart 95
Vraag
What event allows a monotonic stack to finalize a rectangle in a histogram?
Antwoord
A shorter bar supplies a right limit for taller bars being popped. A popped bar's candidate span starts after the new stack top, or at index 0 if the stack is empty. Handle equal heights consistently.
Kaart 96
Vraag
What comparison detects overlap between two nonempty half-open intervals?
Antwoord
max(start1, start2) < min(end1, end2). A strict comparison excludes intervals that only touch.
Kaart 97
Vraag
How does a stack support evaluating a postfix arithmetic expression?
Antwoord
Push operands; for an operator, pop its right operand and then its left operand, compute, and push the result. Preserve order for subtraction and division.
Kaart 98
Vraag
Why can a newer value dominate an older value in a sliding-window maximum deque?
Antwoord
If the newer value is at least as large, it expires no earlier and is never worse as a future maximum. The older candidate can be removed.
Kaart 99
Vraag
How can you merge two already sorted lists of disjoint intervals to find their intersections?
Antwoord
Compare one interval from each list, emit any overlap, then advance the one with the earlier end. Total time is O(m + n).
Kaart 100
Vraag
Why must a histogram stack algorithm handle bars still pending after the scan?
Antwoord
Those bars may extend to the array's end and contain the largest rectangle. Flush them using the end boundary or a suitable sentinel.
Kaart 101
Vraag
What must you save before reversing a singly linked list node's next pointer?
Antwoord
Its original next node. Otherwise rewiring can lose access to the remaining list.
Kaart 102
Vraag
Why does a dummy head simplify linked-list insertion and deletion?
Antwoord
It supplies a predecessor even when the real head changes. The same pointer update can handle both the first node and interior nodes.
Kaart 103
Vraag
How do fast and slow pointers detect a cycle in a singly linked list?
Antwoord
Advance one pointer one step and the other two. A meeting implies a cycle; reaching null with the fast pointer means the list terminates.
Kaart 104
Vraag
What does a recursive binary-tree traversal use for auxiliary space?
Antwoord
O(h) call-stack space, where h is tree height. This is O(log n) for a balanced tree but O(n) for a chain.
Kaart 105
Vraag
During iterative list reversal, what do prev and current represent?
Antwoord
prev heads the reversed processed prefix; current heads the unprocessed suffix. Rewire one node while preserving access to the suffix.
210 kaarten
Coding Interview Patterns Flashcards: Signals, Invariants & Complexity
Gratis leren met dit deckNibomo opent zodat je meteen kunt beginnen met leren.
Kaart 106
Vraag
How can you remove the nth node from the end of a list in one pass?
Antwoord
Start lead at the head and lag at a dummy head. Advance lead n nodes, then move both until lead is null; remove lag.next. Reject invalid n according to the input contract.
Kaart 107
Vraag
Which tree traversal naturally computes a value that depends on both children's results?
Antwoord
Postorder. Process left and right subtrees before combining their results at the parent.
Kaart 108
Vraag
How can you locate a cycle's entry after Floyd's two-speed pointers meet?
Antwoord
Reset one pointer to the head and move both one step at a time. Their next meeting is the entry; this follows from the distances modulo the cycle length.
Kaart 109
Vraag
What is the difference between tree depth and tree height?
Antwoord
Depth measures distance from the root to a node; height measures the longest downward distance to a leaf. State whether distances count edges or nodes.
Kaart 110
Vraag
How can you merge two sorted linked lists using O(1) auxiliary node storage?
Antwoord
Relink the smaller current node onto the result tail, advancing that list. Attach the remaining suffix when one list ends; existing nodes are reused.
Kaart 111
Vraag
When is breadth-first traversal more natural than depth-first traversal on a tree?
Antwoord
When results are grouped by depth or you need the nearest qualifying node by edge count. A queue processes one distance layer before the next.
Kaart 112
Vraag
Why must linked-list intersection compare node identity rather than node value?
Antwoord
Intersection means sharing the same node object and suffix. Separate nodes can hold equal values without the lists intersecting.
Kaart 113
Vraag
Why is checking only immediate children insufficient to validate a binary search tree?
Antwoord
A descendant can satisfy its parent yet violate an ancestor's constraint. Carry inherited lower and upper bounds, with an explicit duplicate policy.
Kaart 114
Vraag
What is the lowest common ancestor of two nodes in a rooted tree?
Antwoord
The deepest node that is an ancestor of both, allowing a node to be its own ancestor.
Kaart 115
Vraag
What property makes inorder traversal useful in a binary search tree?
Antwoord
It visits keys in sorted order under the tree's duplicate policy. In a strict BST, each visited key must be greater than the previous one.
Kaart 116
Vraag
Why must maximum tree-path sum separate its returned value from its global candidate?
Antwoord
The parent can extend only one downward branch. A complete path considered at the current node may join both children, but that fork cannot be extended upward.
Kaart 117
Vraag
How can two pointers find the intersection of two acyclic singly linked lists without measuring lengths?
Antwoord
After reaching a list's end, switch that pointer to the other head. Each traverses both lengths, so they meet at the shared node or at null.
Kaart 118
Vraag
What extra information makes preorder serialization unambiguous for an arbitrary binary tree?
Antwoord
Explicit null-child markers or another equivalent shape encoding. Values in preorder alone do not determine the structure.
Kaart 119
Vraag
Why can repeated subtree-height calculations make a tree-balance check O(n²)?
Antwoord
The same descendants may be scanned from many ancestors. Return height and balance together in one postorder traversal to visit each node once.
Kaart 120
Vraag
How does BST ordering guide a lowest-common-ancestor search for two existing distinct keys?
Antwoord
Move left if both keys are smaller and right if both are larger. The first split, or a node matching one key, is their lowest common ancestor.
Kaart 121
Vraag
What runtime does a search in an ordinary unbalanced BST guarantee?
Antwoord
O(h), where h is its height, and O(n) in the worst case. Logarithmic search requires a balance guarantee or a stated expected-shape assumption.
Kaart 122
Vraag
When computing a root-to-leaf path sum, why is reaching a null child insufficient for success?
Antwoord
A valid endpoint must be a leaf with no children. A missing child beside an existing child does not finish a root-to-leaf path.
Kaart 123
Vraag
What does a min-heap guarantee about its root and children?
Antwoord
The root is a minimum element, and each parent is no larger than its children. The whole array representation is not sorted.
Kaart 124
Vraag
A stream needs the k largest values seen so far. Which heap should you maintain?
Antwoord
A min-heap of at most k values. Its root is the smallest retained value, so a larger arrival can replace it.
Kaart 125
Vraag
What shared structure does a trie store?
Antwoord
Prefixes of keys. Following one edge per symbol reaches a key's prefix node, while a terminal marker distinguishes a complete stored key.
Kaart 126
Vraag
What are the usual binary-heap costs for peek, insertion, and root removal?
Antwoord
Peek is O(1); insertion and root removal are O(log n). Moving a changed element along one root-to-leaf path restores heap order.
Kaart 127
Vraag
How can a heap merge k sorted input streams?
Antwoord
Keep each nonempty stream's next element in a min-heap. Emit the minimum and replace it with that stream's next item. With k streams and N total elements, O(k + N log k) time includes initialization for k ≥ 2.
Kaart 128
Vraag
Why is bottom-up heap construction O(n), not O(n log n)?
Antwoord
Most nodes are near the leaves and can move only a short distance. Summing each node's possible sift-down work across all heights is linear.
Kaart 129
Vraag
How do two heaps support a running median?
Antwoord
Keep the lower half in a max-heap and the upper half in a min-heap, with sizes differing by at most one and every lower value no greater than every upper value.
Kaart 130
Vraag
What is a trie's lookup cost for a key of length L?
Antwoord
O(L) when each child transition is O(1). Child maps or ordered child containers can change that transition cost; space depends on stored prefixes and representation.
Kaart 131
Vraag
Why does a trie node need a terminal marker even if it has children?
Antwoord
A stored key can be a prefix of another key. The marker distinguishes a complete word from a prefix that merely leads to longer words.
Kaart 132
Vraag
When does sorting make more sense than a top-k heap?
Antwoord
When you need the entire sorted order or k is close to n and a full sort is acceptable. A heap's advantage is strongest when only a small retained subset is needed.
Kaart 133
Vraag
Why does a priority queue not by itself support efficient arbitrary deletion?
Antwoord
The heap efficiently exposes only its root. Removing another item needs its position, an indexed-heap design, or a lazy-deletion scheme with cleanup.
Kaart 134
Vraag
What output cost remains after a trie reaches a requested prefix?
Antwoord
Enumerating matching completions still costs time proportional to the visited subtree and emitted text. Prefix lookup does not make all autocomplete results free.
Kaart 135
Vraag
How can a priority queue break tied priorities without comparing the payloads?
Antwoord
Attach a unique increasing sequence number and compare priority first, then sequence number. Equal-priority items can then leave in insertion order without requiring an order on their payloads.
Kaart 136
Vraag
Why can a trie use more memory than a hash set of complete strings?
Antwoord
Nodes and child containers have overhead, especially for sparse branches. Shared prefixes save repeated symbols but do not guarantee a smaller representation.
Kaart 137
Vraag
What should graph modeling identify before choosing a traversal?
Antwoord
The states as vertices and legal transitions as edges, including direction and cost. A grid cell, word, or puzzle configuration can be a vertex.
Kaart 138
Vraag
When does ordinary BFS find a shortest path?
Antwoord
When every edge has the same nonnegative cost, including the unweighted case. Processing vertices by distance layer makes first discovery a shortest-edge-count path.
Kaart 139
Vraag
What is the space cost of an adjacency list compared with an adjacency matrix?
Antwoord
A list uses O(V + E) space; a matrix uses O(V²). A matrix gives constant-time edge lookup, while lists efficiently enumerate actual neighbors.
Kaart 140
Vraag
Which pattern finds all vertices reachable from a start vertex?
Antwoord
DFS or BFS with a visited set. Each reachable vertex and edge is processed a bounded number of times with adjacency lists.
Kaart 141
Vraag
What role does a parent map play in shortest-path traversal?
Antwoord
It records the predecessor used to reach each state. After reaching the target, follow parents backward and reverse the sequence to recover a path.
Kaart 142
Vraag
Why should BFS mark a vertex visited when enqueuing it?
Antwoord
To prevent several parents from adding it before its first removal. First enqueue already fixes its distance in an unweighted graph.
Kaart 143
Vraag
When is Dijkstra's algorithm appropriate?
Antwoord
For shortest paths with nonnegative edge weights. Its greedy finalization relies on no later path reducing a settled distance through a negative edge.
Kaart 144
Vraag
How can a grid traversal avoid confusing physical cells with full search states?
Antwoord
Include all information that changes future moves in the visited key, such as remaining obstacle removals or collected keys. Position alone may merge different states.
Kaart 145
Vraag
How do you detect a directed cycle with DFS?
Antwoord
Track unvisited, active, and finished vertices. An edge to an active vertex closes a cycle on the current recursion path.
Kaart 146
Vraag
Why can DFS with a visited set fail to find a shortest unweighted path?
Antwoord
Its first discovered route may follow a deep detour. DFS reachability order is not distance order; BFS provides that guarantee.
Kaart 147
Vraag
What does a topological ordering guarantee?
Antwoord
For every directed edge u → v, u appears before v. Such an ordering exists exactly when the directed graph is acyclic.
Kaart 148
Vraag
Why should stale priority-queue entries be skipped in a common Dijkstra implementation?
Antwoord
A vertex can receive a better distance after an older entry was pushed. Skip an entry whose stored distance differs from the current best distance.
Kaart 149
Vraag
For an undirected simple graph, why does DFS ignore the edge back to its parent when detecting cycles?
Antwoord
That edge is the same tree edge traversed in reverse, not a new cycle. A different already-visited neighbor indicates a cycle.
Kaart 150
Vraag
What does union-find answer efficiently?
Antwoord
Whether elements belong to the same connected component while components are merged. It does not store the actual connecting paths.
Kaart 151
Vraag
How does Kahn's algorithm build a topological ordering?
Antwoord
Enqueue all zero-indegree vertices, repeatedly remove one, and decrement its outgoing neighbors' indegrees. Enqueue each neighbor when its indegree becomes zero.
Kaart 152
Vraag
Which shortest-path algorithm handles edges weighted only 0 or 1 without a heap?
Antwoord
0–1 BFS with a deque. Push a relaxed zero-cost neighbor to the front and a one-cost neighbor to the back, preserving distance order.
Kaart 153
Vraag
Why is a boolean visited flag usually wrong for Dijkstra at first enqueue?
Antwoord
The first tentative distance need not be the shortest. Allow improvements; a vertex becomes settled when its smallest current distance is removed from the queue.
Kaart 154
Vraag
How do path compression and union by size or rank affect union-find complexity?
Antwoord
Together they give O(α(n)) amortized time per operation, where α is the inverse Ackermann function. The bound is effectively tiny for practical input sizes.
Kaart 155
Vraag
What does processing fewer than V vertices in Kahn's algorithm reveal?
Antwoord
A directed cycle remains. No vertex in the cyclic remainder can reach indegree zero after all removable dependencies are processed.
Kaart 156
Vraag
How can BFS compute distance from every grid cell to the nearest source?
Antwoord
Initialize the queue with all sources at distance zero. This multi-source BFS expands the nearest-source distance layers together.
Kaart 157
Vraag
Why can a topological ordering be nonunique?
Antwoord
Several vertices may currently have no remaining prerequisites. Choosing them in different orders can produce different valid orderings.
Kaart 158
Vraag
What happens when union-find receives an edge whose endpoints already share a representative?
Antwoord
The edge connects vertices already in one component. In incremental construction of an undirected forest, adding it creates a cycle.
Kaart 159
Vraag
Which algorithm can handle negative edge weights and detect a reachable negative cycle?
Antwoord
Bellman–Ford. Repeatedly relax all edges; an improvement after V − 1 full rounds indicates a negative cycle reachable from the source.
Kaart 160
Vraag
Why does traversal need an outer loop to count every connected component of an undirected graph?
Antwoord
One traversal reaches only one component. Start another traversal from each still-unvisited vertex and increment the component count.
Kaart 161
Vraag
How can topological order simplify shortest paths in a weighted DAG?
Antwoord
Relax each vertex's outgoing edges in topological order. Every predecessor is processed first, so negative weights are allowed and total time is O(V + E).
Kaart 162
Vraag
When should you use BFS or DFS instead of union-find for connectivity?
Antwoord
When the graph is static and you need traversal details such as paths or component members. Union-find is especially useful for repeated incremental edge additions and connectivity queries.
Kaart 163
Vraag
What is the difference between a minimum spanning tree and a shortest-path tree?
Antwoord
A minimum spanning tree minimizes total connecting edge weight. A shortest-path tree preserves shortest routes from a chosen source; neither objective implies the other.
Kaart 164
Vraag
Why can stopping at the first meeting be unsafe in bidirectional BFS with arbitrary node-by-node expansion?
Antwoord
A first meeting under an arbitrary expansion order may not minimize the combined distances. Use a layer-based stopping rule that accounts for both search depths.
Kaart 165
Vraag
Which signal suggests backtracking rather than a single greedy choice?
Antwoord
The task asks for all valid arrangements, or choices must be tried and undone because no safe local choice is known. Build a partial candidate and explore legal extensions.
Kaart 166
Vraag
What belongs in a backtracking state?
Antwoord
Enough information to determine legal next choices and recognize completion, such as the current position, chosen items, and remaining constraints.
Kaart 167
Vraag
What makes a pruning condition safe?
Antwoord
It proves that no completion of the current partial state can satisfy the goal or improve the required objective. A guess about likely failure is insufficient.
Kaart 168
Vraag
How do combinations differ from permutations during generation?
Antwoord
Combinations ignore order, so restrict future choices to later positions. Permutations care about order, so track which positions are already used.
Kaart 169
Vraag
What should be true after a backtracking recursive call returns?
Antwoord
The caller's mutable search state is restored exactly to its pre-choice state. Undo additions and constraint updates before trying a sibling choice.
Kaart 170
Vraag
When generating unique subsets from sorted values, how do you skip duplicates safely?
Antwoord
At one recursion depth, skip a value equal to the previous sibling candidate. Still allow equal values at deeper levels when the input provides multiple copies.
Kaart 171
Vraag
Why can backtracking output alone require exponential time?
Antwoord
A set with n distinct elements has 2^n subsets. Explicitly listing all subsets cannot be polynomial in n; copying their contents adds further cost.
Kaart 172
Vraag
Why should a completed mutable candidate usually be copied before saving it?
Antwoord
Later backtracking steps will modify the working candidate. Saving only a reference can make all recorded answers reflect subsequent changes.
Kaart 173
Vraag
What is the main risk of memoizing backtracking solely by the current index?
Antwoord
Different histories can leave different remaining choices or constraints. The memo key must include every part of the state that affects future results.
Kaart 174
Vraag
For selecting the most nonoverlapping intervals, which greedy choice is justified?
Antwoord
Choose the available interval with the earliest finishing time, then continue with compatible intervals. This leaves at least as much room for the remaining selections.
Kaart 175
Vraag
What is the difference between greedy choice and dynamic programming?
Antwoord
Greedy commits to a choice proven safe without exploring all alternatives. DP evaluates and combines subproblem alternatives when that local commitment is not justified.
Kaart 176
Vraag
Why does choosing the largest coin repeatedly fail for some coin systems?
Antwoord
The locally largest coin can leave an expensive remainder. With denominations 1, 3, 4 and amount 6, greedy uses 4 + 1 + 1, while 3 + 3 uses fewer coins.
Kaart 177
Vraag
How does a farthest-reachable frontier solve reachability in a nonnegative jump-length array?
Antwoord
Scan positions no farther than the current frontier and extend it with each reachable index plus its jump length. If the next position lies beyond the frontier, progress is impossible.
Kaart 178
Vraag
Why does choosing the shortest interval not always maximize the number of nonoverlapping intervals?
Antwoord
A short interval can cross the boundary between two compatible intervals and block both. Duration alone does not measure the future scheduling space it consumes.
Kaart 179
Vraag
What must be proved before pruning a combination-sum branch because its sum exceeds the target?
Antwoord
Remaining choices cannot reduce the sum. The pruning is safe for nonnegative additions under the stated goal, but negative numbers can make it invalid.
Kaart 180
Vraag
How does branch and bound differ from ordinary feasibility pruning?
Antwoord
It uses a bound on the best objective reachable from a partial state. Prune only when that bound cannot beat the best complete answer already found.
Kaart 181
Vraag
What question distinguishes a greedy proof from evidence that a heuristic often works?
Antwoord
Can every discarded alternative be ruled out for all valid inputs? Examples and benchmarks support a heuristic, but do not establish the safe-choice property.
Kaart 182
Vraag
Why is earliest-finish interval scheduling insufficient when intervals have different rewards?
Antwoord
Maximizing count and maximizing reward are different objectives. A single high-reward interval can beat several low-reward intervals, so weighted scheduling needs more information.
Kaart 183
Vraag
Which combination of properties makes dynamic programming promising?
Antwoord
Repeated subproblems and a recurrence that combines their results. Define a state whose answer is independent of the path used to reach it.
Kaart 184
Vraag
What should a DP state definition say before you write a recurrence?
Antwoord
Exactly what one table entry means, including its input boundary and any remaining resource or constraint. Ambiguous states lead to mismatched transitions.
Kaart 185
Vraag
How do top-down memoization and bottom-up tabulation differ?
Antwoord
Memoization computes states on demand through calls and caches them. Tabulation processes states in an explicit dependency order, often avoiding recursion overhead.
Kaart 186
Vraag
What determines the runtime of a DP with a finite state table?
Antwoord
The number of states actually evaluated times the work per state, plus preprocessing and output reconstruction. Count transitions rather than just table dimensions.
Kaart 187
Vraag
Why are base cases part of a DP's meaning rather than convenient initial values?
Antwoord
They encode valid empty or smallest subproblems. A wrong base value can invent impossible solutions or remove legitimate ones from every later transition.
Kaart 188
Vraag
For 0/1 knapsack compressed to one capacity array, why iterate capacities downward?
Antwoord
Each item must be used at most once. Descending order reads the previous item's state instead of reusing an update made for the current item.
Kaart 189
Vraag
When can a DP table be compressed to a few rows or variables?
Antwoord
When future states depend only on a bounded slice of earlier states. Keep those dependencies until their last use; reconstruction may need additional storage.
Kaart 190
Vraag
What recurrence models choosing nonadjacent values for maximum sum?
Antwoord
At each position, compare skipping it with taking it plus the best result before its neighbor. The base cases must specify whether choosing nothing is allowed.
Kaart 191
Vraag
What DP state counts paths through a blocked grid when moves are only right or down?
Antwoord
The number of ways to reach each cell from above or from the left. Blocked cells contribute zero; initialize an unblocked starting cell to one.
Kaart 192
Vraag
For unbounded knapsack, why can capacities run upward within an item's pass?
Antwoord
Reusing the current item's updated smaller-capacity result is allowed. Ascending order lets that item contribute more than once.
Kaart 193
Vraag
How can loop order change coin-change counting from combinations to ordered sequences?
Antwoord
Processing coin types outside amounts builds combinations without ordering them. Processing amounts outside all coin choices counts different last-coin sequences separately.
Kaart 194
Vraag
What is the key distinction between longest common subsequence and longest common substring?
Antwoord
A subsequence may skip characters; a substring must stay contiguous. Their DP transitions differ because a substring match cannot carry through a mismatch.
Kaart 195
Vraag
Why is O(nW) knapsack called pseudopolynomial?
Antwoord
It is polynomial in the numeric capacity W, but W can be exponential in the number of bits used to encode it. It is not polynomial in input bit length.
Kaart 196
Vraag
For longest increasing subsequence, what does tails[length − 1] represent in the O(n log n) method?
Antwoord
The smallest possible final value of an increasing subsequence of that length among processed values. The tails array itself need not be one actual subsequence.
Kaart 197
Vraag
Why do counting and minimization DPs use different unreachable-state values?
Antwoord
A count uses zero ways. A minimization state needs an explicit unreachable marker or infinity so an impossible predecessor cannot look like a cheap solution.
Kaart 198
Vraag
What state supports edit distance between two strings?
Antwoord
The minimum edits needed to transform one prefix into the other. Transitions account for insertion, deletion, and replacement or a matching final character.
Kaart 199
Vraag
How can a DP recover one chosen solution instead of only its score?
Antwoord
Store predecessor or choice information, or recompute choices from the full table. Walk backward from the final state to reconstruct the selected decisions.
Kaart 200
Vraag
Why must an LIS implementation choose its binary-search boundary according to strictness?
Antwoord
For a strictly increasing subsequence, replace the first tail at least equal to the value. A nondecreasing subsequence instead uses the first strictly greater tail.
Kaart 201
Vraag
What operation tests whether bit i of a nonnegative integer mask is set?
Antwoord
Check whether mask AND (1 shifted left by i) is nonzero. Ensure i is inside the integer representation's supported bit range.
Kaart 202
Vraag
Why does XOR recover a unique value when every other value occurs exactly twice?
Antwoord
Equal values cancel because x XOR x = 0, and XOR is associative and commutative. XORing all values leaves the single unpaired value.
Kaart 203
Vraag
What does x AND (x − 1) do for a positive integer x?
Antwoord
It clears x's lowest set bit. Repeating it counts set bits in time proportional to the number of set bits.
Kaart 204
Vraag
When does a bitmask make a useful DP state?
Antwoord
When a small set of items is either included or excluded and future choices depend on that subset. n items give 2^n possible masks, so n must be small.
Kaart 205
Vraag
How do you set a bit and clear a bit without changing the others?
Antwoord
Set bit i with mask OR (1 shifted left by i). Clear it with mask AND the bitwise complement of that single-bit mask, respecting the chosen word width.
Kaart 206
Vraag
What makes a memoized recurrence invalid when it depends on mutable global state omitted from the key?
Antwoord
The same key can have different answers under different global conditions. Include the relevant state in the key or remove that dependency.
Kaart 207
Vraag
What condition recognizes a power of two among integers?
Antwoord
x > 0 and x AND (x − 1) = 0. The positivity check excludes zero, which also makes the bitwise expression zero.
Kaart 208
Vraag
Why does bitwise complement need a width convention in language-agnostic reasoning?
Antwoord
Complement flips all bits in the representation. Fixed-width and arbitrary-precision signed integers can produce different-looking values; mask to the intended width when necessary.
Kaart 209
Vraag
How can two unique values be recovered when every other value occurs twice?
Antwoord
XOR all values, choose a set bit in that nonzero result, and partition by that bit. XOR within each group; the two unique values fall into different groups.
Kaart 210
Vraag
Why is memoization alone insufficient to handle cyclic state dependencies?
Antwoord
A call may revisit an unfinished state before any value is cached. Use cycle handling or a problem-specific iterative method; ordinary DAG-style DP assumes an acyclic dependency order.
210 kaarten
Coding Interview Patterns Flashcards: Signals, Invariants & Complexity
Nibomo opent zodat je meteen kunt beginnen met leren.