Core Interview & Competitive Patterns
Interval merging and insertion, Top-K elements with min-heaps, fast & slow pointers for linked lists, and bitwise manipulation tricks.
Competitive programming and technical interviews center on a core suite of canonical archetype patterns that recur across domains. By mastering interval consolidation, heap selection, prefix-sum hash table invariants, and single-cycle ALU bit manipulation, developers can rapidly classify unstructured problem statements and implement optimal solutions under strict time constraints.
1. Executive Summary & Learning Objectives
#This module synthesizes essential problem-solving patterns frequently encountered in systems design and algorithmic interviews, focusing on invariant preservation and asymptotic efficiency.
By the end of this chapter, you will be able to:
- Consolidate Disjoint & Overlapping Intervals: Sort time boundaries to merge intervals and allocate minimum resource pools via min-heaps in time.
- Track Dynamic Order Statistics: Maintain the -th largest element in time and maintain running medians from real-time streams in insertion time using dual heaps.
- Exploit Hash Table Invariants: Formulate prefix sum frequency mappings to count continuous subarrays summing to in time across negative numbers.
- Leverage Single-Cycle Bit Manipulation: Apply hardware-level bitwise primitives (
n & (n - 1),n & -n, XOR cancellation) to solve parity, power-of-two, and frequency queries in time.
2. Topic 141: Interval Patterns
#1. Merge Overlapping Intervals
#Given an array of intervals , combine all overlapping segments into non-overlapping contiguous ranges:
- Sort by Start Time: Order intervals such that .
- Linear Merge Sweep:
- If the current interval starts after the active merged interval ends (), append it as a new disjoint interval.
- Otherwise, an overlap exists: update .
export function mergeIntervals(intervals: number[][]): number[][] {
if (intervals.length <= 1) return intervals;
// Sort ascending by start boundary
intervals.sort((a, b) => a[0] - b[0]);
const merged: number[][] = [intervals[0]];
for (let i = 1; i < intervals.length; i++) {
const current = intervals[i];
const lastMerged = merged[merged.length - 1];
if (current[0] <= lastMerged[1]) {
// Overlap detected: expand ending boundary
lastMerged[1] = Math.max(lastMerged[1], current[1]);
} else {
// Disjoint: start new interval block
merged.push(current);
}
}
return merged;
}2. Meeting Rooms II (Minimum Resource Allocation)
#Given meeting schedule intervals, calculate the minimum number of rooms required so that no two meetings overlap in the same room.
- Min-Heap Strategy: Sort meetings by start time. Maintain a min-heap storing the end times of ongoing meetings.
- When evaluating meeting :
- If , the earliest ending meeting has completed reuse the room by popping the root.
- Push into the min-heap.
- Result: The peak heap size reflects the minimum rooms needed. Overall time complexity: .
3. Topic 143: Heap Patterns (Top-K & Streaming Median)
#1. Top-K Frequent / Extreme Elements in Time
#To extract the largest elements from an unsorted stream of elements:
- Sorting the full array requires time.
- By maintaining a Min-Heap of size , we process each element in time:
- Push incoming element into the min-heap.
- If the heap size exceeds , remove the minimum element ().
- After processing all items, the heap contains strictly the largest elements, with the root representing the -th largest element.
2. Median from a Dynamic Data Stream (Dual-Heap Pattern)
#To maintain the exact running median of numbers arriving sequentially in insertion and query time:
- Partition the dataset into two balanced halves:
- Max-Heap (
low): Holds the smaller half of elements (root is the maximum of the lower partition). - Min-Heap (
high): Holds the larger half of elements (root is the minimum of the upper partition).
- Max-Heap (
| Invariant | Specification | Action on Violation |
|---|---|---|
| Order Invariant | If , swap the root elements. | |
| Size Invariant | or | If , move . |
Median Query:
- If total elements is odd: return .
- If total elements is even: return .
4. Topic 144: Hash Map Prefix Sum Invariant Pattern
#Subarray Sum Equals in Linear Time
#Given an unsorted array containing positive and negative integers, count the total number of continuous subarrays whose sum equals .
Mathematical Invariant
Let denote the prefix sum up to index . A subarray evaluates to sum if and only if:
By recording the frequencies of prefix sums in a hash table as we iterate, we can query in time how many prior prefixes satisfy .
export function subarraySumEqualsK(nums: number[], k: number): number {
const prefixFrequency = new Map<number, number>();
// Base case: prefix sum of 0 occurs once initially
prefixFrequency.set(0, 1);
let runningSum = 0;
let totalSubarrays = 0;
for (let i = 0; i < nums.length; i++) {
runningSum += nums[i];
const targetComplement = runningSum - k;
if (prefixFrequency.has(targetComplement)) {
totalSubarrays += prefixFrequency.get(targetComplement)!;
}
prefixFrequency.set(
runningSum,
(prefixFrequency.get(runningSum) || 0) + 1
);
}
return totalSubarrays;
}5. Topic 147: Bit Manipulation Hacks & Masking
#Bitwise operations execute directly in CPU Arithmetic Logic Units (ALUs) in a single clock cycle ().
1. Fundamental Bitwise Operators
#| Operator | Syntax | Name | Logic Condition | Arithmetic Equivalence |
|---|---|---|---|---|
| AND | a & b | Conjunction | 1 only if both operand bits are 1 | Set intersection of active bits |
| OR | a | b | Disjunction | 1 if at least one operand bit is 1 | Set union of active bits |
| XOR | a ^ b | Exclusive OR | 1 if operand bits differ | Addition modulo 2 without carry |
| NOT | ~a | Inversion | Flips all bits () | Two's complement negation |
| Left Shift | a << k | Left Shift | Shifts bits left, fills with zeros | Multiply by |
| Right Shift | a >> k | Sign-Extending Shift | Shifts bits right, preserves sign bit | Integer division |
2. The 5 Essential Bit Manipulation Primitives
#Primitive 1: Brian Kernighan's Bit-Counting Algorithm
Clears the lowest set bit in an integer in :
Proof: Subtracting 1 flips the lowest set bit to 0 and turns all subsequent trailing zeros into ones. Performing a bitwise AND between and clears exactly that lowest set bit while keeping all higher bits unchanged.
Primitive 2: Power-of-Two Detection
A positive integer is a power of 2 if and only if its binary expansion contains exactly one set bit:
Primitive 3: XOR Cancellation (Single Unique Element)
Exploiting algebraic properties and : When all elements in an array appear twice except for one unique element, XORing every value collapses duplicate pairs to 0, isolating the unique value in time and space.
Primitive 4: Isolate Lowest Set Bit
Primitive 5: Bitmask Manipulation Primitives
- Test bit :
(n >> k) & 1 - Set bit :
n | (1 << k) - Clear bit :
n & ~(1 << k) - Toggle bit :
n ^ (1 << k)
6. Pattern Selection Matrix
#| Pattern Archetype | Input Precondition | Key Invariant / Property | Asymptotic Complexity |
|---|---|---|---|
| Interval Merging | Collection of start/end pairs | Sort by start boundary; merge overlapping tails | time, space |
| Min-Heap Top-K | Stream or large unsorted array | Bounded heap of size retains top elements | time, space |
| Dual Heap Median | Continuous dynamic numerical stream | Balanced sizes with | insertion, query |
| Prefix Hash Map | Linear sequence with negative values | captures target subarrays | time, space |
| Bit Manipulation | Integer attributes, boolean flags, sets | ALU single-cycle execution of bitwise algebra | time, space |
References & Academic Attribution
#- Halim, S., Halim, F., & Skiena, S. S. (2020). Competitive Programming 4: The Lower Bound of Programming Contests. CP4 Pte Ltd.
- Laaksonen, A. (2020). Guide to Competitive Programming: Learning and Improving Algorithms Through Contests (2nd ed.). Springer.
- Skiena, S. S. (2020). The Algorithm Design Manual (3rd ed.). Springer.
- Warren, H. S. (2012). Hacker's Delight (2nd ed.). Addison-Wesley Professional.