Mixed interview practice
Solve each problem before you open its hint or solution. The titles describe the required result, so you must choose the method yourself. For each attempt, write the input contract, a direct solution, an invariant, and the time and auxiliary space costs. Keep your first implementation so that you can compare it with the solution on small inputs.
These exercises use invented data. Download the complete solutions after your attempt.
A balanced activity segment
Section titled “A balanced activity segment”An activity log records signed integer changes to a resource count. Find the length of the longest contiguous segment whose changes sum to zero. The log can contain positive values, negative values, and zero. Return zero for an empty log or when no nonempty segment qualifies. Do not change the input.
Implement longest_balanced_segment(changes: list[int]) -> int.
For [3, -1, -2, 5, -5, 4], the answer is five because the first five changes sum to zero.
Before you run your code, explain the answers for [0, 0], [1, 2], and [2, -2, 2, -2].
Open the hint after your first attempt.
Let a prefix total describe the sum before one position. If two positions have the same prefix total, what is the sum between them? Decide whether you need the first or most recent occurrence to maximize the length.
Open the solution and checks.
The dictionary stores the earliest position for each prefix total. A repeated total identifies a zero sum segment, and the earliest occurrence makes that segment longest.
The initial total belongs before the first element, at position -1. This also handles segments that start at index zero.
The invariant is that every stored position is the earliest occurrence seen so far.
def longest_balanced_segment(changes: list[int]) -> int: """Return the longest contiguous segment with total change zero.
Args: changes: Signed integer changes, including an empty list.
Returns: The longest qualifying length, or zero when none exists. """ first_position = {0: -1} total = 0 longest = 0 for index, change in enumerate(changes): total += change if total in first_position: longest = max(longest, index - first_position[total]) else: first_position[total] = index return longest
for changes in ([3, -1, -2, 5, -5, 4], [], [0, 0], [1, 2], [2, -2, 2, -2]): print(changes, longest_balanced_segment(changes))[3, -1, -2, 5, -5, 4] 5[] 0[0, 0] 2[1, 2] 0[2, -2, 2, -2] 4The expected time is O(n) with expected constant time dictionary access. Auxiliary space is O(n).
This cost treats integer arithmetic as constant time; arbitrarily large integers add a cost that depends on their bit lengths.
A window rule that shrinks when a sum is too large fails here because a negative value can reduce the sum later.
For an independent check, enumerate every start and end position and sum each slice. Compare the largest qualifying length with your result. The hash map lesson explains how the required answer determines the information stored with each key.
Enough instruments for every run
Section titled “Enough instruments for every run”Each instrument can execute one run at a time. All runs have fixed integer start and end times, and every run must execute.
Return the minimum number of instruments needed. A run occupies [start, end), so an instrument becomes available at its end time.
Reject a run whose end is no greater than its start. Accept unsorted runs and repeated intervals, preserve the input, and return zero for no runs.
Implement required_instruments(runs: list[tuple[int, int]]) -> int.
For [(0, 4), (1, 3), (3, 6), (6, 7)], the answer is two.
Explain why the two runs that meet at time three can use the same instrument.
Open the hint after your first attempt.
Process runs by start time. Which end time must you inspect first to find a free instrument? Count the runs still active when the next run starts.
Open the solution and checks.
The min-heap contains the end times of all active runs. Before a new run starts, remove every end time that is no greater than its start. After you insert the new end, the heap size is the simultaneous demand at that start time. The maximum demand is a lower bound because overlapping runs need distinct instruments. It is also sufficient: whenever demand rises, allocate another instrument; otherwise, reuse one whose run has ended.
import heapq
def required_instruments(runs: list[tuple[int, int]]) -> int: """Return the minimum instruments needed for fixed run intervals.
Args: runs: Integer half-open intervals in any order.
Returns: The maximum number of simultaneously active runs.
Raises: ValueError: If an interval has nonpositive duration. """ if any(end <= start for start, end in runs): raise ValueError("Every run must have positive duration.") active_ends = [] peak = 0 for start, end in sorted(runs): while active_ends and active_ends[0] <= start: heapq.heappop(active_ends) heapq.heappush(active_ends, end) peak = max(peak, len(active_ends)) return peak
for runs in ([(0, 4), (1, 3), (3, 6), (6, 7)], [], [(0, 2), (2, 4)], [(0, 2), (0, 2), (0, 2)]): print(runs, required_instruments(runs))[(0, 4), (1, 3), (3, 6), (6, 7)] 2[] 0[(0, 2), (2, 4)] 1[(0, 2), (0, 2), (0, 2)] 3Sorting and heap operations take O(n log n) time. The sorted copy and heap require O(n) auxiliary space.
Removing only runs with end < start would incorrectly count touching runs as overlapping.
For an independent check, count active intervals directly at every start time and take the maximum.
The heap lesson explains why the root exposes the earliest end without sorting the whole heap.
A shared contiguous signal
Section titled “A shared contiguous signal”Two sensors record integer states. Find the length of their longest identical contiguous block. The block can start at different positions in the two lists, but it cannot skip a state. Return zero when either list is empty or no state matches, and preserve both inputs.
Implement shared_signal_length(first: list[int], second: list[int]) -> int.
For [4, 1, 2, 3, 8] and [9, 1, 2, 3, 7], the answer is three.
For [1, 2, 3] and [1, 9, 3], it is one because the matching states are separated.
Open the hint after your first attempt.
Define the length of a matching block that ends at one position in each list. What happens to that length when the two current states differ?
Open the solution and checks.
Let current[j] be the length of a shared block that ends at the current first-list value and at second[j - 1].
Matching values extend the previous diagonal by one. Different values reset the length to zero because a contiguous block cannot cross the mismatch.
Keep the largest cell encountered; the best block need not end at the last position.
def shared_signal_length(first: list[int], second: list[int]) -> int: """Return the longest identical contiguous block length.
Args: first: First sequence of integer sensor states. second: Second sequence of integer sensor states.
Returns: The longest shared block length, or zero when no block exists. """ if not first or not second: return 0 previous = [0] * (len(second) + 1) longest = 0 for first_value in first: current = [0] * (len(second) + 1) for column, second_value in enumerate(second, start=1): if first_value == second_value: current[column] = previous[column - 1] + 1 longest = max(longest, current[column]) previous = current return longest
for first, second in (([4, 1, 2, 3, 8], [9, 1, 2, 3, 7]), ([1, 2, 3], [1, 9, 3]), ([], [1]), ([2, 2, 2], [2, 2])): print(first, second, shared_signal_length(first, second))[4, 1, 2, 3, 8] [9, 1, 2, 3, 7] 3[1, 2, 3] [1, 9, 3] 1[] [1] 0[2, 2, 2] [2, 2] 2For nonempty lengths n and m, the time is O(nm) and auxiliary space is O(m).
Empty inputs return in constant time.
An independent check tries each pair of starting positions and extends the match until the first mismatch.
The two-dimensional dynamic programming lesson teaches a subsequence recurrence.
Its rule allows skipped positions, so it would solve a different problem here.
Assess your attempt
Section titled “Assess your attempt”Record whether you selected a correct method before opening the hint. Check your explanation separately from your implementation: a passing example does not prove an invariant. For each incorrect attempt, keep a small counterexample and explain which assumption it breaks. The practice plan provides a record format.
Further reading
Section titled “Further reading”The Python dictionary documentation describes key lookup and insertion. Use it to distinguish the first stored prefix position from a later replacement.
The Python heapq documentation defines the min-heap invariant and its push and pop operations. It explains the operation that makes the earliest active end available at the root.