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).

13 Core Algorithmic Patterns & 225 Practice Problems

  • 1. Two Pointers (16 Paradigms, 43 Problems): Opposite ends, sorted pair sums, palindrome verification, trapping rain water, 3Sum, container with most water — includes the Sliding Window and Fast & Slow Pointers paradigms (contiguous subarray invariants, longest substrings, Floyd's cycle detection, linked list middle).
  • 2. Binary Search (9 Paradigms, 14 Problems): Monotonic predicate partitioning (feasible(x)), boundary search, rotated sorted arrays, square roots, minimum ship capacity, median of two sorted arrays, matrix median on value range.
  • 3. Bit Manipulation (5 Paradigms, 11 Problems): Counting set bits, XOR cancellation, bit reversal, bitmask pairing, maximum XOR with a bitwise trie.
  • 4. Math & Geometry (8 Paradigms, 14 Problems): Sieve of Eratosthenes, integer/roman conversions, modular arithmetic, geometric simulation.
  • 5. Tree/Graph Depth-First Search (15 Paradigms, 24 Problems): Path sums, lowest common ancestor, tree diameter, validating BSTs, tree DP (House Robber III, Binary Tree Cameras).
  • 6. Tree/Graph Breadth-First Search (5 Paradigms, 12 Problems): Level-order traversals, shortest path in unweighted graphs, zig-zag traversals, rotting oranges, word ladders.
  • 7. Graphs (12 Paradigms, 22 Problems): Topological sort, cycle detection, Dijkstra's algorithm, bipartite graph validation, network delay.
  • 8. Backtracking (6 Paradigms, 14 Problems): Subsets, permutations, combinations, constraint satisfaction, pruning, N-Queens, Sudoku solver.
  • 9. Dynamic Programming (13 Paradigms, 28 Problems): Memoization vs tabulation, 0/1 knapsack, unbounded knapsack, coin change, edit distance, longest common subsequence.
  • 10. Heap / Priority Queue (9 Paradigms, 11 Problems): Running medians, top-k elements, interval scheduling, IPO, k-way merges.
  • 11. Advanced Data Structures (7 Paradigms, 17 Problems): Trie (prefix tree), Union-Find (Disjoint Set Union), LRU Cache, LFU Cache, range-sum queries with updates.
  • 12. Stack (5 Paradigms, 9 Problems): Next greater element, largest rectangle in histogram, remove k digits, decode string, min stack.
  • 13. Intervals & Greedy (2 Paradigms, 6 Problems): Merge intervals, interval scheduling, meeting rooms by sweep line, jump game.

4-Stage Deliberate Practice Framework

  1. Stage 1 (Compare & Learn): Read the pattern's mental model, loop invariant and Big-O proof, compare the pattern's template with the problem's solution side by side, and use the step-by-step debugger. The solution can also be shown in C#, Java, TypeScript, C++, Go or Rust for almost every problem.
  2. Stage 2 (Active Recall): Rebuild the solution from memory in a code editor, with an invariant checklist and optional progressive hints, and check it against a judged test suite.
  3. Stage 3 (AI Interview Coach, coming soon): A mock-interview stage still in development; for now, students go straight from Stage 2 to Stage 4.
  4. Stage 4 (Solve on Your Own): Solve a new problem on your own against a 15-minute timer; your code is graded against a test suite. Python and TypeScript run in your browser and C# runs on our server (design problems grade in Python and TypeScript).

Equipped with a spaced-repetition review hub on a fixed 7-step schedule (1 day up to 90 days), a two-pane Studio workspace, and study notes.

Pricing, Access & Commercial Terms

  • Core Curriculum: 100% Free. No credit card required.
  • Coins: New accounts get 40 free coins once, the daily claim adds +20 coins once a day, and inviting a friend earns you +25 coins when they complete their first practice step. These are the only ways to earn coins.
  • AI Coach: Each AI coach question costs 1-5 coins, priced by the server according to its size.
  • BYOK (Bring Your Own Key): AI coaching is free with your own Google Gemini, OpenAI or OpenRouter API key (BYOK).
  • Extras: Coins also unlock extras for 24 hours: a Recall hint level (1 coin), a Solve solution reveal (2), a LeetCode problem card's solutions (1) and a pattern's extra canonical problems (1).
  • Payments & Refunds: Nothing on the site is sold for money: coins can only be earned, never bought. There are no subscriptions or charges, so there is nothing to refund.
  • Platform Operator: Hi👋WebEnterprise. Support & policies at hispeedalgo.com.
Skip to main content
Hi👋SpeedAlgo

Invariant-First Algorithmic Mastery

Arena
238Items
Theory Context•Two Pointers & Sliding Window
MediumLC 287

Find the Duplicate Number (LeetCode 287)

Target Frequency:AmazonGoogleMeta

You have an array nums holding n + 1 integers, every one of them in the range [1, n].

Exactly one value repeats somewhere in the array (possibly more than twice) — find and return that value.

You're required to do this without mutating nums and using only O(1) extra space.

Worked Examples

Example 1
Input:nums = [1,3,4,2,2]
Output:2
Explanation: The number 2 appears twice.
Example 2
Input:nums = [3,1,3,4,2]
Output:3
Explanation: The number 3 appears twice.
Example 3
Input:nums = [3,3,3,3,3]
Output:3
Explanation: The number 3 appears multiple times.

⚖️Formal Constraints & Bounds

  • 1 <= n <= 105

  • nums.length == n + 1

  • 1 <= nums[i] <= n

  • All the integers in nums appear only once except for precisely one integer which appears two or more times

Deep-Dive & Conceptual Insights

Core Insight

Treating array indices as nodes and values as directed next pointers transforms the duplicate search into finding the entry point of a directed cycle (in-degree >= 2).

Real-World Scenario & Production Applications

Finding duplicate records or hash collisions in read-only immutable storage streams under strict O(1) memory limits.

Subproblems & Recurrence Decomposition3 Phases

🧩Subproblem 1: Implicit Functional Graph Mapping

Interpret array indices as graph nodes and array values nums[i] as directed next pointers. Since values are in [1, n], index 0 is a clean root with in-degree 0.

Mathematical Recurrence / Code Invariant
slow = nums[0]
fast = nums[0]

Step-by-Step Execution Trace Table

PhaseStepSlow (s = nums[s])Fast (f = nums[nums[f]])ExplanationStatus
Phase 1: FloydInit00Virtual pointer: index -> nums[index]Start at index 0
Phase 1: Floyd1nums[0] = 1nums[nums[0]] = nums[1] = 3Slow advances 1 hop, fast advances 2 hops1 != 3
Phase 1: Floyd2nums[1] = 3nums[nums[3]] = nums[2] = 4Slow at index 3, fast at index 43 != 4
Phase 1: Floyd3nums[3] = 2nums[nums[4]] = nums[2] = 4Slow at index 2, fast at index 42 != 4
Phase 1: Floyd4nums[2] = 4nums[nums[4]] = nums[2] = 4Slow at index 4, fast at index 4Rendezvous at index 4!
Phase 2: EntryInitp1 = 0p2 = 4Reset p1 to 0, keep p2 at 4Both advance 1 step
Phase 2: Entry1nums[0] = 1nums[4] = 2p1 = 1, p2 = 21 != 2
Phase 2: Entry2nums[1] = 3nums[2] = 4p1 = 3, p2 = 43 != 4
Phase 2: Entry3nums[3] = 2nums[4] = 2p1 = 2, p2 = 2Match found! Duplicate is 2
Code Shape
Archetype Code Shape
Python
1slow = nums[0]
2fast = nums[0]
3while True:
4 slow = nums[slow]
5 fast = nums[nums[fast]]
6 if slow == fast:
7 break
8p1 = nums[0]
9p2 = slow
10while p1 != p2:
11 p1 = nums[p1]
12 p2 = nums[p2]
13return p1

Conceptual Narrative

The ultimate test of Fast & Slow pointers: converting a static read-only array into an implicit directed graph where duplicate values manifest as cycle entry points.

🧭 Conceptual Foundation & Pattern Intuition

LC 287 gives you n+1n+1n+1 integers in the range [1,n][1, n][1,n]. By Dirichlet's Pigeonhole Principle, at least one duplicate must exist. However, the problem enforces brutal constraints: you cannot modify the array (no sorting, no in-place sign negation) and you must use O(1)O(1)O(1) extra space (no hash sets, no frequency arrays).

How can we solve this in O(N)O(N)O(N) time without modifying anything? The breakthrough is recognizing an implicit functional graph:

  • Every index i∈[0,n]i \in [0, n]i∈[0,n] is a node.
  • The directed edge from node iii points to node nums[i]\text{nums}[i]nums[i] (analogous to node.next).
  • Because all values nums[i]∈[1,n]\text{nums}[i] \in [1, n]nums[i]∈[1,n], index 000 is never pointed to (in-degree 0) — making it the ideal unambiguous root.
  • Because a duplicate value exists, at least two distinct indices point to the exact same index. In graph theory, a node with multiple incoming edges in a functional graph creates the entrance to a directed cycle!
🏟️ The Analogy: The Scavenger Hunt Clue Cards

Imagine n+1n+1n+1 envelopes numbered 000 to nnn. Inside each envelope is a slip of paper telling you which envelope to open next (nums[i]). Since all slips point to envelopes between 111 and nnn, envelope 000 is the start of the hunt and nobody will ever send you back to envelope 000. If every clue pointed to a unique envelope, you would visit every envelope in a single path. But if two different envelopes contain the exact same clue (the duplicate number), two different paths lead to that envelope. Once you enter that room, following subsequent clues traps you in an endless loop! The envelope that started the loop is the duplicate clue card.

🔑 The Key Idea in the Code

Because nums[i] acts as the next pointer, the cycle's entrance has in-degree ≥2\ge 2≥2. That entrance node is precisely the duplicate value.

  • Mutating the input array: Modifying the array (e.g., negating values nums[abs(x)] = -nums[abs(x)] or sorting) violates the problem constraint of keeping array read-only.

  • Using O(N) extra space: Allocating a hash set or boolean visited array violates the O(1) auxiliary space constraint.

  • Starting search at an arbitrary index: Index 0 is guaranteed never to be part of a cycle because values are in range [1, n]. You must initialize slow = nums[0] and fast = nums[nums[0]] to guarantee entry into the cycle.

  • Implicit graph mapping array boundary. In LC 287 (Find the Duplicate Number), values are in range [1, n] while indices are 0..n. Index 0 has in-degree 0 (no value is 0), which guarantees that index 0 is never part of the cycle. Starting at index 0 guarantees you traverse the access road into the cycle entrance rather than starting trapped inside the cycle or cycling indefinitely.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

Array of n+1 integers in [1, n] + find duplicate + no array modification + O(1) space.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: since values are in [1, n], index 0 is a guaranteed entry root; duplicates have in-degree >= 2, forming a cycle origin.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

This problem's traps are in Common Pitfalls above.

The 60-Second Interview Pitch

Say this out loud before you type a single line

"I treat the array as an implicit functional graph where index i has a directed edge to nums[i]. Since values are in [1, n], 0 is a clean starting node with in-degree 0. The duplicate value has multiple incoming edges, forming the entrance of a directed cycle. I use Floyd's cycle detection to find this entrance in O(N) time and O(1) space."

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N)

Look at the execution steps: Phase 1 meets within at most N hops along the implicit functional graph. Phase 2 walks to the cycle entrance in at most N hops. Total operations <= 2N = O(N).

SPACE COMPLEXITY

O(1) Auxiliary

Look at memory allocations: Call stack uses O(1) Iterative. Uses two integer index variables with zero array mutations.

Formal Recurrence Relation

T(N) = Phase1 + Phase2 = O(N)

Derivation Progression

Phase 1: Graph Cycle Collision

T1≤NT1 \le NT1≤N

Traversing indices via nums[i] closes gap by 1 each step inside cycle.

Phase 2: Duplicate In-Degree Origin

T2≤NT2 \le NT2≤N

Linear traverse from root 0 and collision index meets at cycle entrance.

Total Operations

O(N) operations

Linear scan without allocating memory or modifying input array.

Variable Definitions

NNN

Number of elements (array length is N + 1)

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative

🔵 Auxiliary Heap

O(1) Integer pointers only

🟢 Output Space

O(1) Integer duplicate value

Boundary Best / Worst Cases

Best Case

O(N)O(N)O(N)

Average Case

O(N)O(N)O(N)

Worst Case

O(N)O(N)O(N)

Pointer Invariant Transition Progression

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

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Triggers: "array of n+1 integers where each integer is in range [1, n]", "only one repeated number", "do not modify the array and use only constant extra space". Implicit functional directed graph: mapping index i→nums[i]i \to nums[i]i→nums[i].

CONSTRAINTS & BOUNDS

1≤n≤1051 \le n \le 10^51≤n≤105. Must run in <O(N2)< O(N^2)<O(N2) time (O(N)O(N)O(N) optimal) and O(1)O(1)O(1) space without modifying array.

FAANG PRODUCTION TRAPS & EDGE CASES

Naive modifications like marking visited indices negative violates the "do not modify array" constraint. Binary search on value range takes O(Nlog⁡N)O(N \log N)O(NlogN); Floyd's cycle detection achieves optimal O(N)O(N)O(N) time and O(1)O(1)O(1) memory.

Theory Context•Two Pointers & Sliding Window
MediumLC 287

Find the Duplicate Number (LeetCode 287)

Target Frequency:AmazonGoogleMeta

You have an array nums holding n + 1 integers, every one of them in the range [1, n].

Exactly one value repeats somewhere in the array (possibly more than twice) — find and return that value.

You're required to do this without mutating nums and using only O(1) extra space.

Worked Examples

Example 1
Input:nums = [1,3,4,2,2]
Output:2
Explanation: The number 2 appears twice.
Example 2
Input:nums = [3,1,3,4,2]
Output:3
Explanation: The number 3 appears twice.
Example 3
Input:nums = [3,3,3,3,3]
Output:3
Explanation: The number 3 appears multiple times.

⚖️Formal Constraints & Bounds

  • 1 <= n <= 105

  • nums.length == n + 1

  • 1 <= nums[i] <= n

  • All the integers in nums appear only once except for precisely one integer which appears two or more times

Deep-Dive & Conceptual Insights

Core Insight

Treating array indices as nodes and values as directed next pointers transforms the duplicate search into finding the entry point of a directed cycle (in-degree >= 2).

Real-World Scenario & Production Applications

Finding duplicate records or hash collisions in read-only immutable storage streams under strict O(1) memory limits.

Subproblems & Recurrence Decomposition3 Phases

🧩Subproblem 1: Implicit Functional Graph Mapping

Interpret array indices as graph nodes and array values nums[i] as directed next pointers. Since values are in [1, n], index 0 is a clean root with in-degree 0.

Mathematical Recurrence / Code Invariant
slow = nums[0]
fast = nums[0]

Step-by-Step Execution Trace Table

PhaseStepSlow (s = nums[s])Fast (f = nums[nums[f]])ExplanationStatus
Phase 1: FloydInit00Virtual pointer: index -> nums[index]Start at index 0
Phase 1: Floyd1nums[0] = 1nums[nums[0]] = nums[1] = 3Slow advances 1 hop, fast advances 2 hops1 != 3
Phase 1: Floyd2nums[1] = 3nums[nums[3]] = nums[2] = 4Slow at index 3, fast at index 43 != 4
Phase 1: Floyd3nums[3] = 2nums[nums[4]] = nums[2] = 4Slow at index 2, fast at index 42 != 4
Phase 1: Floyd4nums[2] = 4nums[nums[4]] = nums[2] = 4Slow at index 4, fast at index 4Rendezvous at index 4!
Phase 2: EntryInitp1 = 0p2 = 4Reset p1 to 0, keep p2 at 4Both advance 1 step
Phase 2: Entry1nums[0] = 1nums[4] = 2p1 = 1, p2 = 21 != 2
Phase 2: Entry2nums[1] = 3nums[2] = 4p1 = 3, p2 = 43 != 4
Phase 2: Entry3nums[3] = 2nums[4] = 2p1 = 2, p2 = 2Match found! Duplicate is 2
Code Shape
Archetype Code Shape
Python
1slow = nums[0]
2fast = nums[0]
3while True:
4 slow = nums[slow]
5 fast = nums[nums[fast]]
6 if slow == fast:
7 break
8p1 = nums[0]
9p2 = slow
10while p1 != p2:
11 p1 = nums[p1]
12 p2 = nums[p2]
13return p1

Conceptual Narrative

The ultimate test of Fast & Slow pointers: converting a static read-only array into an implicit directed graph where duplicate values manifest as cycle entry points.

🧭 Conceptual Foundation & Pattern Intuition

LC 287 gives you n+1n+1n+1 integers in the range [1,n][1, n][1,n]. By Dirichlet's Pigeonhole Principle, at least one duplicate must exist. However, the problem enforces brutal constraints: you cannot modify the array (no sorting, no in-place sign negation) and you must use O(1)O(1)O(1) extra space (no hash sets, no frequency arrays).

How can we solve this in O(N)O(N)O(N) time without modifying anything? The breakthrough is recognizing an implicit functional graph:

  • Every index i∈[0,n]i \in [0, n]i∈[0,n] is a node.
  • The directed edge from node iii points to node nums[i]\text{nums}[i]nums[i] (analogous to node.next).
  • Because all values nums[i]∈[1,n]\text{nums}[i] \in [1, n]nums[i]∈[1,n], index 000 is never pointed to (in-degree 0) — making it the ideal unambiguous root.
  • Because a duplicate value exists, at least two distinct indices point to the exact same index. In graph theory, a node with multiple incoming edges in a functional graph creates the entrance to a directed cycle!
🏟️ The Analogy: The Scavenger Hunt Clue Cards

Imagine n+1n+1n+1 envelopes numbered 000 to nnn. Inside each envelope is a slip of paper telling you which envelope to open next (nums[i]). Since all slips point to envelopes between 111 and nnn, envelope 000 is the start of the hunt and nobody will ever send you back to envelope 000. If every clue pointed to a unique envelope, you would visit every envelope in a single path. But if two different envelopes contain the exact same clue (the duplicate number), two different paths lead to that envelope. Once you enter that room, following subsequent clues traps you in an endless loop! The envelope that started the loop is the duplicate clue card.

🔑 The Key Idea in the Code

Because nums[i] acts as the next pointer, the cycle's entrance has in-degree ≥2\ge 2≥2. That entrance node is precisely the duplicate value.

  • Mutating the input array: Modifying the array (e.g., negating values nums[abs(x)] = -nums[abs(x)] or sorting) violates the problem constraint of keeping array read-only.

  • Using O(N) extra space: Allocating a hash set or boolean visited array violates the O(1) auxiliary space constraint.

  • Starting search at an arbitrary index: Index 0 is guaranteed never to be part of a cycle because values are in range [1, n]. You must initialize slow = nums[0] and fast = nums[nums[0]] to guarantee entry into the cycle.

  • Implicit graph mapping array boundary. In LC 287 (Find the Duplicate Number), values are in range [1, n] while indices are 0..n. Index 0 has in-degree 0 (no value is 0), which guarantees that index 0 is never part of the cycle. Starting at index 0 guarantees you traverse the access road into the cycle entrance rather than starting trapped inside the cycle or cycling indefinitely.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

Array of n+1 integers in [1, n] + find duplicate + no array modification + O(1) space.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: since values are in [1, n], index 0 is a guaranteed entry root; duplicates have in-degree >= 2, forming a cycle origin.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

This problem's traps are in Common Pitfalls above.

The 60-Second Interview Pitch

Say this out loud before you type a single line

"I treat the array as an implicit functional graph where index i has a directed edge to nums[i]. Since values are in [1, n], 0 is a clean starting node with in-degree 0. The duplicate value has multiple incoming edges, forming the entrance of a directed cycle. I use Floyd's cycle detection to find this entrance in O(N) time and O(1) space."

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N)

Look at the execution steps: Phase 1 meets within at most N hops along the implicit functional graph. Phase 2 walks to the cycle entrance in at most N hops. Total operations <= 2N = O(N).

SPACE COMPLEXITY

O(1) Auxiliary

Look at memory allocations: Call stack uses O(1) Iterative. Uses two integer index variables with zero array mutations.

Formal Recurrence Relation

T(N) = Phase1 + Phase2 = O(N)

Derivation Progression

Phase 1: Graph Cycle Collision

T1≤NT1 \le NT1≤N

Traversing indices via nums[i] closes gap by 1 each step inside cycle.

Phase 2: Duplicate In-Degree Origin

T2≤NT2 \le NT2≤N

Linear traverse from root 0 and collision index meets at cycle entrance.

Total Operations

O(N) operations

Linear scan without allocating memory or modifying input array.

Variable Definitions

NNN

Number of elements (array length is N + 1)

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative

🔵 Auxiliary Heap

O(1) Integer pointers only

🟢 Output Space

O(1) Integer duplicate value

Boundary Best / Worst Cases

Best Case

O(N)O(N)O(N)

Average Case

O(N)O(N)O(N)

Worst Case

O(N)O(N)O(N)

Pointer Invariant Transition Progression

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

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Triggers: "array of n+1 integers where each integer is in range [1, n]", "only one repeated number", "do not modify the array and use only constant extra space". Implicit functional directed graph: mapping index i→nums[i]i \to nums[i]i→nums[i].

CONSTRAINTS & BOUNDS

1≤n≤1051 \le n \le 10^51≤n≤105. Must run in <O(N2)< O(N^2)<O(N2) time (O(N)O(N)O(N) optimal) and O(1)O(1)O(1) space without modifying array.

FAANG PRODUCTION TRAPS & EDGE CASES

Naive modifications like marking visited indices negative violates the "do not modify array" constraint. Binary search on value range takes O(Nlog⁡N)O(N \log N)O(NlogN); Floyd's cycle detection achieves optimal O(N)O(N)O(N) time and O(1)O(1)O(1) memory.

© 2026 Hi👋WebEnterprise. All rights reserved.
Sitemap•llms.txt•