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•Binary Search Boundary
EasyLC 35

Search Insert Position (LC 35)

Target Frequency:GoogleMetaApple

You have an array of distinct integers in sorted order and a target value. If target is already in the array, return its index; otherwise, return the index it would land at if you inserted it while keeping the array sorted.

Solve it in O(log n) time.

Worked Examples

Example 1
Input:nums = [1,3,5,6], target = 5
Output:2
Explanation: Target 5 exists at index 2.
Example 2
Input:nums = [1,3,5,6], target = 2
Output:1
Explanation: Target 2 is not found; inserting at index 1 preserves ascending order.
Example 3
Input:nums = [1,3,5,6], target = 7
Output:4
Explanation: Target 7 exceeds all elements; inserting at index 4 (end of array) preserves sorted order.

⚖️Formal Constraints & Bounds

  • 1 <= nums.length <= 104

  • -104 <= nums[i] <= 104

  • nums contains distinct values sorted in ascending order.

  • -104 <= target <= 104

Deep-Dive & Conceptual Insights

Core Insight

The predicate arr[mid] >= target transforms the sorted array into a boolean sequence [False, ..., False, True, ..., True]. Binary search finds the transition boundary.

Real-World Scenario & Production Applications

Database range index scans (e.g. WHERE timestamp >= '2026-08-01') use lower-bound binary search to locate the exact starting leaf page in logarithmic time.

Subproblems & Recurrence Decomposition3 Phases

🧩Subproblem 1: Monotonic Predicate Mapping

Map the sorted array to a monotonic boolean sequence via predicate P(i) = (nums[i] >= target). Produces [False, False, ..., True, True] where the first True is our exact answer.

Mathematical Recurrence / Code Invariant
# Monotonic Predicate Partition:
# [False, False, ..., True, True]
P(mid) = (nums[mid] >= target)

Step-by-Step Execution Trace Table

StepSearch Window [lo, hi]midnums[mid]Predicate nums[mid] >= 8?Action & State UpdateRecorded first_true
1[0, 6]37False (7 < 8)Infeasible →\to→ push right: lo = mid + 1 = 4—
2[4, 6]513True (13 >= 8)Feasible →\to→ record 5, push left: hi = mid - 1 = 45
3[4, 4]411True (11 >= 8)Feasible →\to→ record 4, push left: hi = mid - 1 = 34
4[4, 3]——lo > hi (Window empty)Loop terminates →\to→ Return first_true = 44
Code Shape
Archetype Code Shape
Python
1def is_feasible(i):
2 <the yes/no question about slot i>
3lo, hi = 0, len(nums)
4while lo < hi:
5 mid = lo + (hi - lo) // 2
6 if is_feasible(mid):
7 hi = mid
8 else:
9 lo = mid + 1
10return lo

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

Keeping a qualifying answer in play and deliberately continuing to search feels backwards the first time you see it — most searches stop the moment they find something. Here's why this one doesn't.

🎢 The Analogy: The Amusement Park Height Line

Imagine a line of kids sorted shortest to tallest, and a ride requires "at least 4 feet tall." You want the first kid in line who's tall enough — not just a tall-enough kid. If you jump into the middle of the line and find a kid who qualifies, you can't stop there: there might be a shorter (but still qualifying) kid standing earlier in line. So you keep that kid in the running (the stretch of line you still consider now ends at them) and keep checking further to the left. If a kid is too short, everyone before them is too short as well, so the stretch you consider now starts just after them. When that stretch shrinks to a single spot, it is the first qualifier (or the end of the line, if nobody qualifies).

🔑 The Key Idea in the Code

The predicate nums[mid] >= target is just "is this kid tall enough?" — a [False, False, ..., True, True] line by construction, because nums is sorted. Keeping mid with hi = mid instead of returning immediately is what separates "found a match" from "found the boundary."

  • Writing lo = mid instead of lo = mid + 1

  • Writing hi = mid - 1 in the half-open template

  • Setting hi to the last index, not one past it

  • Reading nums[i] without checking i < len(nums)

  • Using a check that is not monotonic

  • Adding 1 to what bisect_left returns

  • Forgetting + lo on the bisect form

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

"If target is already in the array, return its index; otherwise, return the index it would land at if you inserted it", on a sorted array: the insert position is the first index with nums[i] >= target (Lower Bound).

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: for Search Insert Position (LC 35), every index below lo has nums[i] < target and every index from hi on has nums[i] >= target (or is len(nums)), with lo, hi = 0, len(nums); the answer is lo when lo == hi.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • lo = mid in the False branch: with the floor midpoint, mid == lo when two candidates are left, so the loop never ends (nums = [1,3,5,6], target = 5 stops at lo = 1, hi = 2).

  • Starting hi at len(nums) - 1: a target larger than every value must return len(nums) (LeetCode Example 3, target = 7 on [1,3,5,6] gives 4), which that window can never produce.

The 60-Second Interview Pitch

Say this out loud before you type a single line

"I'd use Lower Bound. nums[i] >= target is False, then True, so the insert position is the first True. I start hi at len(nums) so 'insert at the end' is a possible answer. If mid passes the check it might be the answer, so I keep it with hi = mid; if it fails, the answer is strictly to its right, so lo = mid + 1. The loop stops when lo == hi, and that is the answer. The trap is lo = mid: with two candidates left, mid equals lo and the loop never moves. It's O(log n) time and O(1) space."

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(log N)

Look at the while loop: while lo < hi:. In each step, we evaluate the monotonic boolean predicate nums[mid] >= target. If True, mid may be the first True, so we keep it with hi = mid; if False, we move right with lo = mid + 1. Either way the window [lo, hi) loses at least half of its size (rounded down), so from N candidates the loop runs at most ⌊log2 N⌋ + 1 times with O(1) work per step, yielding O(log N) time.

SPACE COMPLEXITY

O(1)

Look at memory allocation: The loop is iterative with O(1) call stack. We store only three scalar integer variables (lo, hi, mid). Zero heap objects or arrays are allocated. Auxiliary space is O(1).

Formal Recurrence Relation

T(N)=T(N/2)+O(1)⟹O(log⁡N)T(N) = T(N/2) + O(1) ⟹ O(\log N)T(N)=T(N/2)+O(1)⟹O(logN)

Derivation Progression

Monotonic Boolean Mapping

P(i) = (nums[i] ≥ target)

Sorted order guarantees P(i) is monotonically non-decreasing [False...False, True...True]. Binary search locates the exact boundary transition.

Keep-Left Contraction

hi = mid, O(1)

When P(mid) is True, mid stays in the window as a possible answer and everything right of it is dropped.

Convergence

at most ⌊log2 N⌋ + 1 steps ⟹ O(log N)

The window closes at lo == hi, which is the boundary.

Variable Definitions

NNN

Total number of elements in the sorted array

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative while loop with zero recursion stack frames

🔵 Auxiliary Heap

O(1) Only scalar variables (lo, hi, mid)

🟢 Output Space

O(1) Returns a single integer insertion index

Boundary Best / Worst Cases

Best Case

O(1)O(1)O(1) when the array has 1 element; otherwise between ⌊log⁡2N⌋⌊ \log_2 N ⌋⌊log2​N⌋ and ⌊log⁡2N⌋+1⌊ \log_2 N ⌋ + 1⌊log2​N⌋+1 iterations, depending on the target.

Average Case

O(log⁡N)O(\log N)O(logN).

Worst Case

O(log⁡N)O(\log N)O(logN) — at most ⌊log⁡2N⌋+1⌊ \log_2 N ⌋ + 1⌊log2​N⌋+1 iterations until lo == hi.

Recurrence Tree Topology

Recurrence Tree Topology
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

The structural trigger that catches my eye is: "insertion point if the target is missing" — a target that's found returns its index, but one that's absent returns where it would slot in. Notice how this diverges from LC 704: we are no longer searching for an isolated value that permits early exit—we are searching for a transition frontier. The boolean predicate nums[i] >= target partitions the sorted array into two contiguous zones: [False, ..., False, True, ..., True]. This maps directly to Monotonic Predicate Boundary Search (lower bound / bisect_left).

CONSTRAINTS & BOUNDS

The array length is N≤104N \le 10^4N≤104 with an O(log⁡N)O(\log N)O(logN) requirement, demanding logarithmic bisection. The values are distinct and fit within standard integers (−104≤nums[i],target≤104-10^4 \le \text{nums}[i], \text{target} \le 10^4−104≤nums[i],target≤104). The search runs on lo = 0 and hi = len(nums): hi starts one past the last index because a target greater than every element is inserted at index NNN, so NNN must stay a possible answer.

FAANG PRODUCTION TRAPS & EDGE CASES

A target smaller than nums[0] needs no special case: every check is True, hi walks down to 0, and the loop returns 0.

Theory Context•Binary Search Boundary
EasyLC 35

Search Insert Position (LC 35)

Target Frequency:GoogleMetaApple

You have an array of distinct integers in sorted order and a target value. If target is already in the array, return its index; otherwise, return the index it would land at if you inserted it while keeping the array sorted.

Solve it in O(log n) time.

Worked Examples

Example 1
Input:nums = [1,3,5,6], target = 5
Output:2
Explanation: Target 5 exists at index 2.
Example 2
Input:nums = [1,3,5,6], target = 2
Output:1
Explanation: Target 2 is not found; inserting at index 1 preserves ascending order.
Example 3
Input:nums = [1,3,5,6], target = 7
Output:4
Explanation: Target 7 exceeds all elements; inserting at index 4 (end of array) preserves sorted order.

⚖️Formal Constraints & Bounds

  • 1 <= nums.length <= 104

  • -104 <= nums[i] <= 104

  • nums contains distinct values sorted in ascending order.

  • -104 <= target <= 104

Deep-Dive & Conceptual Insights

Core Insight

The predicate arr[mid] >= target transforms the sorted array into a boolean sequence [False, ..., False, True, ..., True]. Binary search finds the transition boundary.

Real-World Scenario & Production Applications

Database range index scans (e.g. WHERE timestamp >= '2026-08-01') use lower-bound binary search to locate the exact starting leaf page in logarithmic time.

Subproblems & Recurrence Decomposition3 Phases

🧩Subproblem 1: Monotonic Predicate Mapping

Map the sorted array to a monotonic boolean sequence via predicate P(i) = (nums[i] >= target). Produces [False, False, ..., True, True] where the first True is our exact answer.

Mathematical Recurrence / Code Invariant
# Monotonic Predicate Partition:
# [False, False, ..., True, True]
P(mid) = (nums[mid] >= target)

Step-by-Step Execution Trace Table

StepSearch Window [lo, hi]midnums[mid]Predicate nums[mid] >= 8?Action & State UpdateRecorded first_true
1[0, 6]37False (7 < 8)Infeasible →\to→ push right: lo = mid + 1 = 4—
2[4, 6]513True (13 >= 8)Feasible →\to→ record 5, push left: hi = mid - 1 = 45
3[4, 4]411True (11 >= 8)Feasible →\to→ record 4, push left: hi = mid - 1 = 34
4[4, 3]——lo > hi (Window empty)Loop terminates →\to→ Return first_true = 44
Code Shape
Archetype Code Shape
Python
1def is_feasible(i):
2 <the yes/no question about slot i>
3lo, hi = 0, len(nums)
4while lo < hi:
5 mid = lo + (hi - lo) // 2
6 if is_feasible(mid):
7 hi = mid
8 else:
9 lo = mid + 1
10return lo

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

Keeping a qualifying answer in play and deliberately continuing to search feels backwards the first time you see it — most searches stop the moment they find something. Here's why this one doesn't.

🎢 The Analogy: The Amusement Park Height Line

Imagine a line of kids sorted shortest to tallest, and a ride requires "at least 4 feet tall." You want the first kid in line who's tall enough — not just a tall-enough kid. If you jump into the middle of the line and find a kid who qualifies, you can't stop there: there might be a shorter (but still qualifying) kid standing earlier in line. So you keep that kid in the running (the stretch of line you still consider now ends at them) and keep checking further to the left. If a kid is too short, everyone before them is too short as well, so the stretch you consider now starts just after them. When that stretch shrinks to a single spot, it is the first qualifier (or the end of the line, if nobody qualifies).

🔑 The Key Idea in the Code

The predicate nums[mid] >= target is just "is this kid tall enough?" — a [False, False, ..., True, True] line by construction, because nums is sorted. Keeping mid with hi = mid instead of returning immediately is what separates "found a match" from "found the boundary."

  • Writing lo = mid instead of lo = mid + 1

  • Writing hi = mid - 1 in the half-open template

  • Setting hi to the last index, not one past it

  • Reading nums[i] without checking i < len(nums)

  • Using a check that is not monotonic

  • Adding 1 to what bisect_left returns

  • Forgetting + lo on the bisect form

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

"If target is already in the array, return its index; otherwise, return the index it would land at if you inserted it", on a sorted array: the insert position is the first index with nums[i] >= target (Lower Bound).

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: for Search Insert Position (LC 35), every index below lo has nums[i] < target and every index from hi on has nums[i] >= target (or is len(nums)), with lo, hi = 0, len(nums); the answer is lo when lo == hi.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • lo = mid in the False branch: with the floor midpoint, mid == lo when two candidates are left, so the loop never ends (nums = [1,3,5,6], target = 5 stops at lo = 1, hi = 2).

  • Starting hi at len(nums) - 1: a target larger than every value must return len(nums) (LeetCode Example 3, target = 7 on [1,3,5,6] gives 4), which that window can never produce.

The 60-Second Interview Pitch

Say this out loud before you type a single line

"I'd use Lower Bound. nums[i] >= target is False, then True, so the insert position is the first True. I start hi at len(nums) so 'insert at the end' is a possible answer. If mid passes the check it might be the answer, so I keep it with hi = mid; if it fails, the answer is strictly to its right, so lo = mid + 1. The loop stops when lo == hi, and that is the answer. The trap is lo = mid: with two candidates left, mid equals lo and the loop never moves. It's O(log n) time and O(1) space."

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(log N)

Look at the while loop: while lo < hi:. In each step, we evaluate the monotonic boolean predicate nums[mid] >= target. If True, mid may be the first True, so we keep it with hi = mid; if False, we move right with lo = mid + 1. Either way the window [lo, hi) loses at least half of its size (rounded down), so from N candidates the loop runs at most ⌊log2 N⌋ + 1 times with O(1) work per step, yielding O(log N) time.

SPACE COMPLEXITY

O(1)

Look at memory allocation: The loop is iterative with O(1) call stack. We store only three scalar integer variables (lo, hi, mid). Zero heap objects or arrays are allocated. Auxiliary space is O(1).

Formal Recurrence Relation

T(N)=T(N/2)+O(1)⟹O(log⁡N)T(N) = T(N/2) + O(1) ⟹ O(\log N)T(N)=T(N/2)+O(1)⟹O(logN)

Derivation Progression

Monotonic Boolean Mapping

P(i) = (nums[i] ≥ target)

Sorted order guarantees P(i) is monotonically non-decreasing [False...False, True...True]. Binary search locates the exact boundary transition.

Keep-Left Contraction

hi = mid, O(1)

When P(mid) is True, mid stays in the window as a possible answer and everything right of it is dropped.

Convergence

at most ⌊log2 N⌋ + 1 steps ⟹ O(log N)

The window closes at lo == hi, which is the boundary.

Variable Definitions

NNN

Total number of elements in the sorted array

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative while loop with zero recursion stack frames

🔵 Auxiliary Heap

O(1) Only scalar variables (lo, hi, mid)

🟢 Output Space

O(1) Returns a single integer insertion index

Boundary Best / Worst Cases

Best Case

O(1)O(1)O(1) when the array has 1 element; otherwise between ⌊log⁡2N⌋⌊ \log_2 N ⌋⌊log2​N⌋ and ⌊log⁡2N⌋+1⌊ \log_2 N ⌋ + 1⌊log2​N⌋+1 iterations, depending on the target.

Average Case

O(log⁡N)O(\log N)O(logN).

Worst Case

O(log⁡N)O(\log N)O(logN) — at most ⌊log⁡2N⌋+1⌊ \log_2 N ⌋ + 1⌊log2​N⌋+1 iterations until lo == hi.

Recurrence Tree Topology

Recurrence Tree Topology
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

The structural trigger that catches my eye is: "insertion point if the target is missing" — a target that's found returns its index, but one that's absent returns where it would slot in. Notice how this diverges from LC 704: we are no longer searching for an isolated value that permits early exit—we are searching for a transition frontier. The boolean predicate nums[i] >= target partitions the sorted array into two contiguous zones: [False, ..., False, True, ..., True]. This maps directly to Monotonic Predicate Boundary Search (lower bound / bisect_left).

CONSTRAINTS & BOUNDS

The array length is N≤104N \le 10^4N≤104 with an O(log⁡N)O(\log N)O(logN) requirement, demanding logarithmic bisection. The values are distinct and fit within standard integers (−104≤nums[i],target≤104-10^4 \le \text{nums}[i], \text{target} \le 10^4−104≤nums[i],target≤104). The search runs on lo = 0 and hi = len(nums): hi starts one past the last index because a target greater than every element is inserted at index NNN, so NNN must stay a possible answer.

FAANG PRODUCTION TRAPS & EDGE CASES

A target smaller than nums[0] needs no special case: every check is True, hi walks down to 0, and the loop returns 0.

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