Hi👋SpeedAlgo • Deliberate Practice & Cognitive Ergonomics for Software Engineers

An interactive algorithm mastery and technical interview preparation platform published by Hi👋WebEnterprise. Built for senior and staff software engineers preparing for rigorous coding screens at top tech companies (FAANG/MAMAA).

12 Core Algorithmic Patterns & 168 Practice Problems

  • 1. Two Pointers (9 Paradigms, 32 Problems): Converging pointers, sorted pair sums, container with most water, trapping rain water, 3Sum, plus the Sliding Window and Fast & Slow Pointers paradigms (Floyd cycle detection, monotonic window invariants, longest substrings, minimum window).
  • 2. Binary Search (8 Paradigms, 12 Problems): Monotonic predicate partitioning, boundary searching, rotated arrays, median of two sorted arrays, matrix median on value range.
  • 3. Bit Manipulation (5 Paradigms, 8 Problems): Bitmasking, XOR tricks, counting set bits, subset enumeration via bitmasks.
  • 4. Math & Geometry (5 Paradigms, 10 Problems): Sieve of Eratosthenes, integer/roman conversions, modular arithmetic, geometric simulation.
  • 5. Tree/Graph Depth-First Search (8 Paradigms, 17 Problems): Path sums, lowest common ancestor, tree diameter, subtree serialization, validating BSTs.
  • 6. Tree/Graph Breadth-First Search (4 Paradigms, 11 Problems): Level-order traversals, shortest path, rotting oranges, word ladders.
  • 7. Graphs (6 Paradigms, 14 Problems): Topological sort, cycle detection, Dijkstra, bipartite validation, network delay.
  • 8. Backtracking (5 Paradigms, 13 Problems): Subsets, permutations, combinations, constraint satisfaction, pruning, N-Queens.
  • 9. Dynamic Programming (7 Paradigms, 14 Problems): Memoization vs tabulation, knapsack, coin change, edit distance, longest common subsequence.
  • 10. Heap / Priority Queue (8 Paradigms, 10 Problems): Running medians, top-k elements, interval scheduling, IPO, k-way merges.
  • 11. Advanced Data Structures (5 Paradigms, 13 Problems): Trie, Union-Find, LRU Cache, LFU Cache, Monotonic Stacks.
  • 12. Intervals & Stack / Miscellaneous (7 Paradigms, 14 Problems): Merge intervals, daily temperatures, largest rectangle in histogram, trapping rain water via stack.

4-Stage Deliberate Practice Framework

  1. Stage 1 (Compare & Learn): Multi-language Rosetta Stone contrasting abstract invariants with concrete solutions across Python, C#, Java, TypeScript, C++, Go, and Rust.
  2. Stage 2 (Active Recall): Reconstruct algorithmic template invariants from memory with real-time feedback before looking at solutions.
  3. Stage 3 (Senior SWE AI Mock Coach): Simulated senior mock interview evaluating Big-O space/time tradeoffs, edge cases, and code reviews in Monaco Editor.
  4. Stage 4 (Solve on Your Own): Timed sandbox challenges verified against automated test suites in Python, C#, Java, and TypeScript.

Equipped with SM-2 Spaced Repetition Review Hub, Studio Cockpit workspace layout, and interactive study notes.

Pricing, Access & Commercial Terms

  • Core Curriculum: 100% Free. No credit card required.
  • Compute Coins: 40 free coins upon signup, +20 daily login bonus, +25 referral bonus.
  • 24-Hour AI Coaching Pass: 5 compute coins unlocks unlimited senior SWE AI coaching for a full 24 hours.
  • BYOK (Bring Your Own Key): Completely free unlimited AI coaching if using your own Gemini/OpenAI API key.
  • Refund & Subscription Policy: No recurring charges, no subscription traps, and no paid paywalls. Free tier provides full learning path.
  • Platform Operator: Hi👋WebEnterprise Inc. Support & policies at hispeedalgo.com.
Skip to main content
Hi👋SpeedAlgo

Invariant-First Algorithmic Mastery

180Items
Theory Context•Two Pointers & Sliding Window
MediumLC 189

Rotate Array (LeetCode 189)

Algebraic Group Reflection: (Aᴿ Bᴿ)ᴿ = BA

Target Frequency:AmazonGoogleAppleMicrosoft

Given an array of nnn elements, rotate the sequence to the right by kkk steps in-place with strict O(1)O(1)O(1) auxiliary space.

The Technique Invariant: Instead of using a secondary buffer (O(n)O(n)O(n) space) or performing kkk single shifts (O(n⋅k)O(n \cdot k)O(n⋅k) time), apply the Three-Reversal Reflection Invariant:

  1. Normalize the rotation magnitude: k=k(modn)k = k \pmod nk=k(modn).
  2. Reverse the entire array (0…n−1)(0 \dots n - 1)(0…n−1), which swaps the two partitioned blocks (A,B)→(BR,AR)(A, B) \to (B^R, A^R)(A,B)→(BR,AR) but leaves their internal ordering mirrored.
  3. Reverse the first kkk elements (0…k−1)(0 \dots k - 1)(0…k−1) to restore BR→BB^R \to BBR→B.
  4. Reverse the remaining n−kn - kn−k elements (k…n−1)(k \dots n - 1)(k…n−1) to restore AR→AA^R \to AAR→A. This achieves the rotated sequence (B,A)(B, A)(B,A) in two linear passes (O(n)O(n)O(n) time) and zero extra allocations (O(1)O(1)O(1) space).

Worked Examples

Example 1
Input:nums = [1,2,3,4,5,6,7], k = 3
Output:[5,6,7,1,2,3,4]
Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6]; rotate 2 steps: [6,7,1,2,3,4,5]; rotate 3 steps: [5,6,7,1,2,3,4]
Example 2
Input:nums = [-1,-100,3,99], k = 2
Output:[3,99,-1,-100]
Explanation: rotate 1 steps to the right: [99,-1,-100,3]; rotate 2 steps: [3,99,-1,-100]

⚖️Formal Constraints & Bounds

  • 1 <= nums.length <= 10^5

  • -2^31 <= nums[i] <= 2^31 - 1

  • 0 <= k <= 10^5

Deep-Dive & Conceptual Insights

Why It Works & Core Invariant

(A B)^R = B^R A^R ⟹ (B^R)^R (A^R)^R = B A — two block reversals cancel mirror orientation while swapping partition positions.

Real-World Scenario & Production Applications

Linux kernel ring buffers and high-frequency trading (HFT) circular queues use memory reversals for zero-allocation cache-line permutations without allocating secondary buffers.

Core Invariant Specification & Code Shape
Archetype Code Shape
Python
1Normalize k: k = k % n
2Reverse the entire array: reverse(0, n - 1)
3Reverse the first k elements: reverse(0, k - 1)
4Reverse the remaining n - k elements: reverse(k, n - 1)

Target: Rotate Array (LeetCode 189). Normalizes rotations exceeding the array length to eliminate redundant full 360-degree cyclical revolutions.

Boundary Model: Closed In-Place Swap Interval [left, right]

Each reversal reverses the subarray nums[left..right] by converging two pointers inward, swapping nums[left] and nums[right] until left >= right.

Loop Invariant Termination

def reverse(l, r): while l < r: nums[l], nums[r] = nums[r], nums[l]; l += 1; r -= 1

Conceptual Narrative

The Flash of Genius: Rotating an array by K positions is an algebraic word reversal: (Aᴿ Bᴿ)ᴿ = BA. By reversing the prefix, reversing the suffix, and then reversing the entire array, cyclic rotation is achieved in O(N) time with strictly O(1) auxiliary space.

The Mental Model Analogy: The Two-Carriage Train Shunting Switch

Imagine a train composed of two coupled carriages, A (engine section) and B (passenger section), coupled together as [A | B]. A railway turntable needs to move carriage B to the front and carriage A to the back, forming [B | A], but the siding track is so narrow that you cannot decouple and move carriages around each other. The ingenious mechanical shunting trick: First, flip carriage A completely backwards on its own axis to get A^R. Second, flip carriage B backwards on its own axis to get B^R. You now have [A^R | B^R]. Finally, couple the entire train together and flip the whole train end-to-end: (A^R B^R)^R. Like magic, reversing an inverted sequence un-inverts both parts in reversed order: (B^R)^R (A^R)^R = [B | A]! The carriages have swapped positions without needing a second track.

  • Pitfall: Recall the algebraic reflection identity: (Aᴿ Bᴿ)ᴿ = BA.

  • Pitfall: Reversing the entire array places the target suffix at the front, but mirrored.

  • Pitfall: Two local reversals restore the correct intra-block order without extra memory.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Senior SWE thought process architecture for Three-Reversal Array Rotation.

Pattern Recognition Signals

The 10-second spot

The requirement specifies rotating an array of size NNN by KKK positions with O(1)O(1)O(1) extra memory. This immediately rules out auxiliary buffer slicing (nums[:] = nums[-k:] + nums[:-k]).

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Rather than managing complex cycle counts with gcd⁡(N,K)\gcd(N, K)gcd(N,K), recognize that three continuous two-pointer reversals decompose the transposition into mirror reflections.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • Guard: If K(modN)==0K \pmod N == 0K(modN)==0, return immediately (no-op).

  • Step 1: reverse(nums, 0, N - 1)

  • Step 2: reverse(nums, 0, K - 1)

  • Step 3: reverse(nums, K, N - 1)

The 60-Second Interview Pitch

Say this out loud before you type a single line

Test against boundary conditions: N=1,K=0,K=N,K>NN=1, K=0, K=N, K > NN=1,K=0,K=N,K>N. All converge in exactly 2N2N2N element reads and NNN swaps.

Rotating an array by K positions is an algebraic word reversal: (Aᴿ Bᴿ)ᴿ = BA. By reversing the prefix, reversing the suffix, and then reversing the entire array, cyclic rotation is achieved in O(N) time with strictly O(1) auxiliary space.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N)

Reversing a subarray of length L requires floor(L / 2) swaps. Step 1 reverses length N (N/2 swaps). Step 2 reverses length K (K/2 swaps). Step 3 reverses length N - K ((N - K)/2 swaps). Total swaps: N/2 + K/2 + (N - K)/2 = N swaps. Each swap executes in O(1) CPU instructions. Total time is strictly O(N), with exactly 2N memory reads and 2N memory writes.

SPACE COMPLEXITY

O(1)

Only two integer pointers (left, right) and one temporary swap register are allocated on the CPU thread stack. Auxiliary memory complexity is strictly O(1).

Formal Recurrence Relation

lim⁡k→∞N2k=1  ⟹  2k=N  ⟹  k=log⁡2N\lim_{k \to \infty} \frac{N}{2^k} = 1 \implies 2^k = N \implies k = \log_2 Nlimk→∞​2kN​=1⟹2k=N⟹k=log2​N

Reversing a subarray of length L requires floor(L / 2) swaps. Step 1 reverses length N (N/2 swaps). Step 2 reverses length K (K/2 swaps). Step 3 reverses length N - K ((N - K)/2 swaps). Total swaps: N/2 + K/2 + (N - K)/2 = N swaps. Each swap executes in O(1) CPU instructions. Total time is strictly O(N), with exactly 2N memory reads and 2N memory writes.

Pointer Invariant Transition Progression

Pointer Invariant Transition Progression
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Immediately normalizes K using modulo arithmetic: k %= len(nums) before any memory operation. • Demonstrates deep knowledge of the algebraic symmetry: writes down (A^R B^R)^R = BA during design. • Implements a reusable two-pointer reverse(left, right) helper with zero off-by-one errors. • Explains CPU cache locality benefits of sequential memory access over jumping cycle indices.

CONSTRAINTS & BOUNDS

1 <= nums.length <= 10^5. -2^31 <= nums[i] <= 2^31 - 1. 0 <= k <= 10^5

FAANG PRODUCTION TRAPS & EDGE CASES

In low-latency networking stacks (DPDK, Linux packet queues), rotating ring buffer packets in-place avoids socket memory reallocations. • Operating system kernel memory managers use block reversal to rotate virtual memory pages during memory compaction.

Core Algorithmic State Invariants

1. Monotonic Window Expansion

The right pointer advances forward, absorbing the incoming element into the running aggregation state (frequency map, sum, or set).

2. Window Validity & Contraction Invariant

When window constraints are violated (or while valid when seeking minimal length), the left pointer increments to evict elements and restore the required invariant.

3. Amortized Linear Termination

Because each element enters and exits the window at most once, total operations across both pointers are bounded by 2N, guaranteeing strictly linear O(N) execution.

Theory Context•Two Pointers & Sliding Window
MediumLC 189

Rotate Array (LeetCode 189)

Algebraic Group Reflection: (Aᴿ Bᴿ)ᴿ = BA

Target Frequency:AmazonGoogleAppleMicrosoft

Given an array of nnn elements, rotate the sequence to the right by kkk steps in-place with strict O(1)O(1)O(1) auxiliary space.

The Technique Invariant: Instead of using a secondary buffer (O(n)O(n)O(n) space) or performing kkk single shifts (O(n⋅k)O(n \cdot k)O(n⋅k) time), apply the Three-Reversal Reflection Invariant:

  1. Normalize the rotation magnitude: k=k(modn)k = k \pmod nk=k(modn).
  2. Reverse the entire array (0…n−1)(0 \dots n - 1)(0…n−1), which swaps the two partitioned blocks (A,B)→(BR,AR)(A, B) \to (B^R, A^R)(A,B)→(BR,AR) but leaves their internal ordering mirrored.
  3. Reverse the first kkk elements (0…k−1)(0 \dots k - 1)(0…k−1) to restore BR→BB^R \to BBR→B.
  4. Reverse the remaining n−kn - kn−k elements (k…n−1)(k \dots n - 1)(k…n−1) to restore AR→AA^R \to AAR→A. This achieves the rotated sequence (B,A)(B, A)(B,A) in two linear passes (O(n)O(n)O(n) time) and zero extra allocations (O(1)O(1)O(1) space).

Worked Examples

Example 1
Input:nums = [1,2,3,4,5,6,7], k = 3
Output:[5,6,7,1,2,3,4]
Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6]; rotate 2 steps: [6,7,1,2,3,4,5]; rotate 3 steps: [5,6,7,1,2,3,4]
Example 2
Input:nums = [-1,-100,3,99], k = 2
Output:[3,99,-1,-100]
Explanation: rotate 1 steps to the right: [99,-1,-100,3]; rotate 2 steps: [3,99,-1,-100]

⚖️Formal Constraints & Bounds

  • 1 <= nums.length <= 10^5

  • -2^31 <= nums[i] <= 2^31 - 1

  • 0 <= k <= 10^5

Deep-Dive & Conceptual Insights

Why It Works & Core Invariant

(A B)^R = B^R A^R ⟹ (B^R)^R (A^R)^R = B A — two block reversals cancel mirror orientation while swapping partition positions.

Real-World Scenario & Production Applications

Linux kernel ring buffers and high-frequency trading (HFT) circular queues use memory reversals for zero-allocation cache-line permutations without allocating secondary buffers.

Core Invariant Specification & Code Shape
Archetype Code Shape
Python
1Normalize k: k = k % n
2Reverse the entire array: reverse(0, n - 1)
3Reverse the first k elements: reverse(0, k - 1)
4Reverse the remaining n - k elements: reverse(k, n - 1)

Target: Rotate Array (LeetCode 189). Normalizes rotations exceeding the array length to eliminate redundant full 360-degree cyclical revolutions.

Boundary Model: Closed In-Place Swap Interval [left, right]

Each reversal reverses the subarray nums[left..right] by converging two pointers inward, swapping nums[left] and nums[right] until left >= right.

Loop Invariant Termination

def reverse(l, r): while l < r: nums[l], nums[r] = nums[r], nums[l]; l += 1; r -= 1

Conceptual Narrative

The Flash of Genius: Rotating an array by K positions is an algebraic word reversal: (Aᴿ Bᴿ)ᴿ = BA. By reversing the prefix, reversing the suffix, and then reversing the entire array, cyclic rotation is achieved in O(N) time with strictly O(1) auxiliary space.

The Mental Model Analogy: The Two-Carriage Train Shunting Switch

Imagine a train composed of two coupled carriages, A (engine section) and B (passenger section), coupled together as [A | B]. A railway turntable needs to move carriage B to the front and carriage A to the back, forming [B | A], but the siding track is so narrow that you cannot decouple and move carriages around each other. The ingenious mechanical shunting trick: First, flip carriage A completely backwards on its own axis to get A^R. Second, flip carriage B backwards on its own axis to get B^R. You now have [A^R | B^R]. Finally, couple the entire train together and flip the whole train end-to-end: (A^R B^R)^R. Like magic, reversing an inverted sequence un-inverts both parts in reversed order: (B^R)^R (A^R)^R = [B | A]! The carriages have swapped positions without needing a second track.

  • Pitfall: Recall the algebraic reflection identity: (Aᴿ Bᴿ)ᴿ = BA.

  • Pitfall: Reversing the entire array places the target suffix at the front, but mirrored.

  • Pitfall: Two local reversals restore the correct intra-block order without extra memory.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Senior SWE thought process architecture for Three-Reversal Array Rotation.

Pattern Recognition Signals

The 10-second spot

The requirement specifies rotating an array of size NNN by KKK positions with O(1)O(1)O(1) extra memory. This immediately rules out auxiliary buffer slicing (nums[:] = nums[-k:] + nums[:-k]).

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Rather than managing complex cycle counts with gcd⁡(N,K)\gcd(N, K)gcd(N,K), recognize that three continuous two-pointer reversals decompose the transposition into mirror reflections.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • Guard: If K(modN)==0K \pmod N == 0K(modN)==0, return immediately (no-op).

  • Step 1: reverse(nums, 0, N - 1)

  • Step 2: reverse(nums, 0, K - 1)

  • Step 3: reverse(nums, K, N - 1)

The 60-Second Interview Pitch

Say this out loud before you type a single line

Test against boundary conditions: N=1,K=0,K=N,K>NN=1, K=0, K=N, K > NN=1,K=0,K=N,K>N. All converge in exactly 2N2N2N element reads and NNN swaps.

Rotating an array by K positions is an algebraic word reversal: (Aᴿ Bᴿ)ᴿ = BA. By reversing the prefix, reversing the suffix, and then reversing the entire array, cyclic rotation is achieved in O(N) time with strictly O(1) auxiliary space.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N)

Reversing a subarray of length L requires floor(L / 2) swaps. Step 1 reverses length N (N/2 swaps). Step 2 reverses length K (K/2 swaps). Step 3 reverses length N - K ((N - K)/2 swaps). Total swaps: N/2 + K/2 + (N - K)/2 = N swaps. Each swap executes in O(1) CPU instructions. Total time is strictly O(N), with exactly 2N memory reads and 2N memory writes.

SPACE COMPLEXITY

O(1)

Only two integer pointers (left, right) and one temporary swap register are allocated on the CPU thread stack. Auxiliary memory complexity is strictly O(1).

Formal Recurrence Relation

lim⁡k→∞N2k=1  ⟹  2k=N  ⟹  k=log⁡2N\lim_{k \to \infty} \frac{N}{2^k} = 1 \implies 2^k = N \implies k = \log_2 Nlimk→∞​2kN​=1⟹2k=N⟹k=log2​N

Reversing a subarray of length L requires floor(L / 2) swaps. Step 1 reverses length N (N/2 swaps). Step 2 reverses length K (K/2 swaps). Step 3 reverses length N - K ((N - K)/2 swaps). Total swaps: N/2 + K/2 + (N - K)/2 = N swaps. Each swap executes in O(1) CPU instructions. Total time is strictly O(N), with exactly 2N memory reads and 2N memory writes.

Pointer Invariant Transition Progression

Pointer Invariant Transition Progression
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Immediately normalizes K using modulo arithmetic: k %= len(nums) before any memory operation. • Demonstrates deep knowledge of the algebraic symmetry: writes down (A^R B^R)^R = BA during design. • Implements a reusable two-pointer reverse(left, right) helper with zero off-by-one errors. • Explains CPU cache locality benefits of sequential memory access over jumping cycle indices.

CONSTRAINTS & BOUNDS

1 <= nums.length <= 10^5. -2^31 <= nums[i] <= 2^31 - 1. 0 <= k <= 10^5

FAANG PRODUCTION TRAPS & EDGE CASES

In low-latency networking stacks (DPDK, Linux packet queues), rotating ring buffer packets in-place avoids socket memory reallocations. • Operating system kernel memory managers use block reversal to rotate virtual memory pages during memory compaction.

Core Algorithmic State Invariants

1. Monotonic Window Expansion

The right pointer advances forward, absorbing the incoming element into the running aggregation state (frequency map, sum, or set).

2. Window Validity & Contraction Invariant

When window constraints are violated (or while valid when seeking minimal length), the left pointer increments to evict elements and restore the required invariant.

3. Amortized Linear Termination

Because each element enters and exits the window at most once, total operations across both pointers are bounded by 2N, guaranteeing strictly linear O(N) execution.

Rosetta Dual-Monaco Comparison
Python 3
CANONICAL INVARIANT TEMPLATE
Loading...
CONCRETE: ROTATE ARRAY (LEETCODE 189)
T = O(N)S = O(1)
Loading...
Pattern Implementation Mapping TableCanonical Invariant ⟷ Concrete Code ⟷ Engineering Rationale
Canonical InvariantConcrete CodeEngineering Rationale
k %= nk %= nNormalizes rotations exceeding the array length to eliminate redundant full 360-degree cyclical revolutions.
reverse_slice(0, n - 1)reverse(0, n - 1)Global mirror operation: places the tail k elements at the front of the array, but in inverted order: (AB)^R = B^R A^R.
reverse_slice(0, k - 1)reverse(0, k - 1)Prefix inversion: restores the newly front-placed k elements from B^R back to their original relative ordering B: (B^R)^R = B.
reverse_slice(k, n - 1)reverse(k, n - 1)Suffix inversion: restores the displaced n - k elements from A^R back to their original relative ordering A: (A^R)^R = A.
© 2026 Hi👋WebEnterprise. All rights reserved.
Sitemap•llms.txt•