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