Coding Track

Blind 75 Arrays, Intervals, Heaps, And Matrices

A advanced practice chapter for the high-frequency implementation rounds: state the invariant, handle edge cases, then write compact Python that survives follow-up questions.

Interview Method

Talk Like A Builder, Code Like A Reviewer

These problems look smaller than ML system design, but the same discipline applies: define the contract, protect invariants, test failure modes, and explain tradeoffs under constraints.

  1. Restate: inputs, output, mutation rules, sortedness, duplicates, and whether one valid answer is guaranteed.
  2. Choose a pattern: hash map, prefix/suffix scan, two pointers, monotonic stack, heap, matrix boundary walk, or pointer rewiring.
  3. Declare the invariant: say what remains true after each loop, heap operation, or pointer move.
  4. Test before running: empty input, single item, duplicates, all equal values, negative values, overflow-like products, and disconnected links.
  5. Close with complexity: include hidden costs from sorting, heap operations, recursion stack, slicing, and copied arrays.
Question: What separates an advanced solution from a memorized one?

A strong solution makes assumptions explicit, names the invariant, handles edge cases without drama, and can adapt when the interviewer changes one constraint. The code is short because the reasoning is clean, not because the candidate skipped explanation.

Arrays And Hashing

Frequency, Complement, Prefix, And Monotonic Patterns

These are the warm-up problems that become production skills: feature aggregation, deduplication, telemetry windows, ranking, and invariant checks for streaming data.

Problem: Contains Duplicate

Return true if any value appears at least twice in the array.

Hidden answer: strategy, invariant, mistakes, tests

Use a set. Invariant: before reading nums[i], the set contains exactly the values seen at earlier indices. Mistake to avoid: sorting changes the cost to O(n log n) and can obscure the simpler expected answer. Test empty, one element, duplicate adjacent, duplicate far apart, and negative values.

Problem: Valid Anagram

Return true when two strings contain the same character multiset.

Hidden answer: strategy, invariant, mistakes, tests

Count characters in both strings or add for one string and subtract for the other. Invariant: after processing aligned positions, the counter equals the frequency difference for the prefixes. Mistake to avoid: assuming ASCII only without asking. Test unequal lengths, repeated characters, mixed case if allowed, and Unicode if the interviewer leaves character set open.

Problem: Top K Frequent Elements

Return the k values that appear most frequently.

Hidden answer: strategy, invariant, mistakes, tests

Count with a hash map, then use bucket sort for O(n) expected time or a heap for O(n log k). Invariant for the heap version: the heap contains the best k elements among processed frequency pairs. Mistake to avoid: sorting all counts when the follow-up asks for better than O(n log n). Test k = 1, k equals distinct count, ties, and all values equal.

Problem: Maximum Product Subarray

Return the largest product of a contiguous non-empty subarray.

Hidden answer: strategy, invariant, mistakes, tests

Track both max and min products ending at the current index because a negative value can swap them. Invariant: after processing x, hi and lo are the largest and smallest products of subarrays ending at x. Mistake to avoid: only tracking the max, which fails on two negatives. Test zeros, all negatives, one element, and alternating signs.

Worked Python: Maximum Product Subarray

Implement the min/max ending-state approach.

Hidden answer: Python solution
def max_product(nums):
    best = hi = lo = nums[0]
    for x in nums[1:]:
        if x < 0:
            hi, lo = lo, hi
        hi = max(x, hi * x)
        lo = min(x, lo * x)
        best = max(best, hi)
    return best

Problem: Container With Most Water

Choose two vertical lines that hold the most water.

Hidden answer: strategy, invariant, mistakes, tests

Use two pointers. Invariant: after evaluating a pair, moving the shorter side is the only move that can possibly improve area because width always shrinks. Mistake to avoid: moving the taller side and skipping candidates with a higher limiting height. Test strictly increasing heights, strictly decreasing heights, equal heights, and two-element input.

Intervals

Sort Once, Preserve The Meaning Of The Active Range

Problem: Insert Interval

Insert a new interval into a sorted non-overlapping interval list.

Hidden answer: strategy, invariant, mistakes, tests

Append intervals before the new interval, merge all overlaps, then append the rest. Invariant: output is sorted and non-overlapping for everything already consumed. Mistake to avoid: treating touching endpoints incorrectly; ask whether [1, 2] and [2, 3] overlap. Test insert before all, after all, merging one, merging many, and exact endpoint contact.

Problem: Merge Intervals

Merge all overlapping intervals.

Hidden answer: strategy, invariant, mistakes, tests

Sort by start, then maintain the last merged interval. Invariant: the merged list covers exactly the processed intervals and has no overlaps. Mistake to avoid: forgetting to update the end with max when a later interval is contained by the active one. Test nested intervals, unsorted input, endpoint contact, and a single interval.

Problem: Non-Overlapping Intervals

Return the minimum number of intervals to remove so the rest do not overlap.

Hidden answer: strategy, invariant, mistakes, tests

Greedily keep intervals with the earliest end time. Invariant: among processed intervals, the kept set has maximum size and the smallest possible last end for that size. Mistake to avoid: sorting by start and removing the next interval without comparing ends. Test identical intervals, nested intervals, endpoint contact, and no overlaps.

Worked Python: Meeting Rooms II Variant

Given intervals, return the minimum number of rooms needed.

Hidden answer: heap invariant and Python solution

This common follow-up uses a min-heap of meeting end times. Invariant: the heap contains the end time of each room currently in use after processing meetings in start-time order.

import heapq

def min_meeting_rooms(intervals):
    rooms = []
    for start, end in sorted(intervals):
        if rooms and rooms[0] <= start:
            heapq.heappop(rooms)
        heapq.heappush(rooms, end)
    return len(rooms)

Heaps

Streaming Priority Under Memory Constraints

Problem: Find Median From Data Stream

Support adding numbers and returning the current median.

Hidden answer: strategy, invariant, mistakes, tests

Use a max-heap for the lower half and a min-heap for the upper half. Invariant: every value in the lower heap is less than or equal to every value in the upper heap, and heap sizes differ by at most one. Mistake to avoid: balancing sizes without preserving ordering. Test increasing input, decreasing input, duplicates, negatives, and even versus odd counts.

Problem: Merge K Sorted Lists

Merge k sorted linked lists into one sorted list.

Hidden answer: strategy, invariant, mistakes, tests

Push each non-empty list head into a heap, pop the smallest node, and push that node's successor. Invariant: the heap contains the smallest unmerged node from each active list. Mistake to avoid: pushing nodes directly in Python without a tie-breaker when values match. Test empty list array, all lists empty, duplicates across lists, and one very long list.

Matrices

Boundary Discipline And Coordinate Invariants

Problem: Set Matrix Zeroes

If a cell is zero, set its entire row and column to zero in place.

Hidden answer: strategy, invariant, mistakes, tests

Use the first row and first column as marker storage, plus flags for whether they originally contained zero. Invariant: after the marker pass, matrix[r][0] and matrix[0][c] encode whether row r or column c should be zeroed. Mistake to avoid: overwriting markers before the inner cells are processed. Test one row, one column, zero at [0][0], and multiple zeroes.

Problem: Spiral Matrix

Return all matrix values in spiral order.

Hidden answer: strategy, invariant, mistakes, tests

Maintain top, bottom, left, and right boundaries. Invariant: after each side traversal, the corresponding boundary moves inward and no visited cell remains inside the active rectangle. Mistake to avoid: traversing bottom or left after the boundaries have crossed. Test square, single row, single column, wide rectangle, and tall rectangle.

Problem: Rotate Image

Rotate an n x n matrix 90 degrees clockwise in place.

Hidden answer: strategy, invariant, mistakes, tests

Transpose across the main diagonal, then reverse each row. Invariant after transpose: matrix[r][c] has swapped with matrix[c][r] exactly once for c > r. Mistake to avoid: swapping each pair twice. Test 1 x 1, 2 x 2, odd size, and even size.

Worked Python: Spiral Matrix

Implement the boundary walk without duplicate visits.

Hidden answer: Python solution
def spiral_order(matrix):
    if not matrix or not matrix[0]:
        return []

    out = []
    top, bottom = 0, len(matrix) - 1
    left, right = 0, len(matrix[0]) - 1

    while top <= bottom and left <= right:
        for c in range(left, right + 1):
            out.append(matrix[top][c])
        top += 1

        for r in range(top, bottom + 1):
            out.append(matrix[r][right])
        right -= 1

        if top <= bottom:
            for c in range(right, left - 1, -1):
                out.append(matrix[bottom][c])
            bottom -= 1

        if left <= right:
            for r in range(bottom, top - 1, -1):
                out.append(matrix[r][left])
            left += 1

    return out

Linked Lists

Pointer Moves You Can Explain Without Hand-Waving

Problem: Reverse Linked List

Reverse a singly linked list.

Hidden answer: strategy, invariant, mistakes, tests

Iterate with prev and cur. Invariant: prev is the reversed prefix and cur is the head of the unreversed suffix. Mistake to avoid: losing cur.next before saving it. Test empty list, one node, two nodes, and longer list.

Problem: Linked List Cycle

Return true if the list contains a cycle.

Hidden answer: strategy, invariant, mistakes, tests

Use Floyd's slow and fast pointers. Invariant: if a cycle exists, the fast pointer gains one node per step on the slow pointer modulo the cycle length, so they eventually meet. Mistake to avoid: dereferencing fast.next without checking it. Test empty, no cycle, cycle at head, and cycle in the middle.

Problem: Remove Nth Node From End

Remove the nth node from the end of a singly linked list.

Hidden answer: strategy, invariant, mistakes, tests

Use a dummy node and move fast ahead by n steps, then move slow and fast together. Invariant: the gap between pointers is n, so when fast reaches the end, slow.next is the node to remove. Mistake to avoid: failing when removing the head. Test one node, remove head, remove tail, and middle removal.

Worked Python: Reverse Linked List

Implement iterative pointer rewiring.

Hidden answer: Python solution
def reverse_list(head):
    prev = None
    cur = head
    while cur:
        nxt = cur.next
        cur.next = prev
        prev = cur
        cur = nxt
    return prev

Production Connection

Why This Matters For Speech ML/AI Work

Question: How should you explain a coding problem in a ML interview?

Tie the algorithm to a real system only after solving the prompt correctly. Interviewers want reliable fundamentals first, then mature engineering judgment: constraints, correctness, complexity, tests, and how the pattern appears in production ML systems.