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
MediumLC 658

Find K Closest Elements (LC 658)

Target Frequency:MetaGoogleAmazon

You're given a sorted integer array arr plus integers k and x; find the k values in arr that sit closest to x, and return them sorted in ascending order.

When comparing two candidates a and b for closeness to x: a wins if |a - x| < |b - x|, or if the distances tie and a < b.

Worked Examples

Example 1
Input:arr = [1,2,3,4,5], k = 4, x = 3
Output:[1,2,3,4]
Explanation: 2, 3 and 4 are within 1 of x = 3. Both 1 and 5 are 2 away, and the tie goes to the smaller value, 1.
Example 2
Input:arr = [1,1,2,3,4,5], k = 4, x = -1
Output:[1,1,2,3]
Explanation: x is below every value, so the four smallest values are the closest. The two 1s count as separate values.

⚖️Formal Constraints & Bounds

  • 1 <= k <= arr.length

  • 1 <= arr.length <= 104

  • arr is sorted in ascending order.

  • -104 <= arr[i], x <= 104

Deep-Dive & Conceptual Insights

Core Insight

Binary search the window's LEFT EDGE over [0, len(arr) - k - 1]. Comparing the departing element (x - arr[mid]) against the entering element (arr[mid + k] - x) is the monotonic feasibility question.

Real-World Scenario & Production Applications

Recommendation systems retrieving the k nearest neighbors to a query score from a pre-sorted index, and time-series systems fetching the k readings closest to a given timestamp.

Subproblems & Recurrence Decomposition3 Phases

🧩Subproblem 1: Window Left-Edge Domain

The answer is always a single contiguous window of size k. Its left edge lo ranges over [0, len(arr) - k] -- that entire range is the binary search domain, not the array's values.

Mathematical Recurrence / Code Invariant
lo, hi = 0, len(arr) - k

Step-by-Step Execution Trace Table

StepSearch Domain [lo, hi]midx - arr[mid] vs arr[mid+k] - xActionNew Search Domain
1[0, 0] (arr=[1,2,3,4,5], k=4, x=3)03-1=2 vs 5-3=2 → 2 > 2 is Falsehi = mid - 1 = -1[0, -1]
2[0, -1]—lo <= hi (0 <= -1) is FalseConvergedReturn arr[0:4] = [1,2,3,4]
Code Shape
Archetype Code Shape
Python
1lo, hi = 0, len(arr) - k - 1
2while lo <= hi:
3 mid = lo + (hi - lo) // 2
4 if x - arr[mid] > arr[mid + k] - x:
5 lo = mid + 1
6 else:
7 hi = mid - 1
8return arr[lo:lo + k]

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

There's no target index to find here — the thing being binary searched is the left edge of a sliding window of size k.

🥈 The Analogy: Sliding a Fixed-Size Frame Along a Number Line

Imagine a picture frame that can hold exactly k numbers, sliding along the sorted array. You want to park the frame so the k numbers inside are collectively closest to x. At any candidate position mid, sliding the frame one step right would drop arr[mid] (the leftmost element leaving) and pick up arr[mid + k] (the next element entering). Comparing "how far is the element about to leave" versus "how far is the element about to enter" tells you, with certainty, whether sliding right helps or hurts — and that yes/no question is monotonic across all valid left edges.

🔑 The Key Idea in the Code

Because arr is sorted, x - arr[mid] and arr[mid + k] - x shrink and grow predictably as the window slides, which is exactly the monotonic structure binary search needs — just measured between two elements a window-width apart, not between one element and x directly. When len(arr) == k (e.g. arr = [1], k = 1, x = 5), hi = len(arr) - k - 1 = -1, so the loop while lo <= hi never executes and returns arr[0:k] directly!

  • Binary searching closest element then expanding outward: Finding the single closest element and expanding two pointers outward takes O(log⁡N+K)O(\log N + K)O(logN+K) and has complex edge-case bounds. Binary searching the sliding window starting index directly takes O(log⁡(N−K))O(\log(N - K))O(log(N−K)) and is much cleaner.

  • Window comparator condition: When comparing window boundaries mid and mid + k, the transition condition is x - arr[mid] > arr[mid + k] - x. If the element at mid + k is closer to x than arr[mid], lo must move to mid + 1.

  • Tie-breaking preference for smaller values: When distances are equal (|a - x| == |b - x|), the problem requires picking the smaller value. The strict inequality > ensures that ties prefer the left element.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

Sorted array + fixed window size k + 'k closest elements to x' -- the answer is always a single CONTIGUOUS window, so its left edge is a search space of size n - k + 1.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: the optimal left edge candidate space is [lo, hi] = [0, len(arr) - k - 1]. Comparing x - arr[mid] (the element that would leave on a right shift) against arr[mid + k] - x (the element that would enter) tells you whether shifting right strictly helps, which is monotonic because arr is sorted.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • Comparing arr[mid] directly to x instead of comparing the two elements a window-shift would trade (arr[mid] leaving vs arr[mid + k] entering).

  • Using >= instead of > in the comparison silently breaks the tie-breaking rule (prefer the smaller of two equally-close values).

  • Comparing abs(arr[mid] - x) with abs(arr[mid + k] - x) instead of the signed x - arr[mid] with arr[mid + k] - x: two equal values below x tie, the search stops too early, and arr = [0,2,2,2,3,3,5], k = 1, x = 6 returns [2] instead of [5].

The 60-Second Interview Pitch

Say this out loud before you type a single line

"Since the answer is always one contiguous window of size k, I binary search its left edge candidate space over [0, len(arr) - k - 1] using while lo <= hi. At each mid I compare x - arr[mid] (departing) against arr[mid + k] - x (entering): if departing is strictly farther, shifting right helps, so lo = mid + 1; otherwise hi = mid - 1. This converges on the optimal window left edge lo in O(log(n - k)) time, then an O(k) slice returns the answer."

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(log(n - k) + k)

Look at the while loop: while lo <= hi: searches over the candidate window boundaries with hi = len(arr) - k - 1. Each iteration performs O(1) comparisons (x - arr[mid] vs arr[mid + k] - x) and halves the range, terminating in O(log(n - k)) iterations. Slicing arr[lo:lo + k] afterward costs O(k).

SPACE COMPLEXITY

O(k) Output

Look at memory allocations: Call stack uses O(1) Iterative. The only allocation is the O(k) output slice returned to the caller -- no auxiliary heaps are used during the search itself.

Formal Recurrence Relation

T(N,K)=O(log⁡(N−K))+O(K)T(N, K) = O(\log(N - K)) + O(K)T(N,K)=O(log(N−K))+O(K)

Derivation Progression

Window Left-Edge Domain

left∈[0,N−K−1]left \in [0, N - K - 1]left∈[0,N−K−1]

Every valid window candidate is tested by its left edge, searching over N - K positions with while lo <= hi.

Trade Comparison

abs(arr[mid]−x) vs abs(arr[mid+K]−x)\text{abs}(arr[mid] - x) \text{ vs } \text{abs}(arr[mid+K] - x)abs(arr[mid]−x) vs abs(arr[mid+K]−x)

Comparing the departing and entering elements of a one-step shift is a monotonic O(1) feasibility test.

Convergence + Slice

O(log⁡(N−K))+O(K)O(\log(N-K)) + O(K)O(log(N−K))+O(K)

Binary search converges on the optimal left edge, then a single O(K) slice materializes the answer.

Variable Definitions

NNN

Total number of elements in the sorted array

KKK

Fixed size of the closest-elements window

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative while loop with zero recursion frames

🔵 Auxiliary Heap

O(1) Only scalar pointers during the search

🟢 Output Space

O(K) Result slice of K closest elements

Boundary Best / Worst Cases

Best Case

O(K)O(K)O(K) when K == N (the whole array is the answer, no search needed).

Average Case

O(log⁡(N−K)+K)O(\log(N - K) + K)O(log(N−K)+K).

Worst Case

O(log⁡(N−K)+K)O(\log(N - K) + K)O(log(N−K)+K) for K ≪ N.

Recurrence Tree Topology

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

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

The statement specifies a "sorted integer array arr, two integers k and x" and asks for the "k closest integers to x" Because the input array is already sorted, any kkk closest elements must form a contiguous window of length kkk! Finding kkk closest elements therefore reduces to finding the optimal left index of that window, denoted by left_index ∈[0,N−k]\in [0, N - k]∈[0,N−k]. This triggers a binary search directly over the window's starting index.

CONSTRAINTS & BOUNDS

With 1≤k≤N≤1041 \le k \le N \le 10^41≤k≤N≤104, the search space for the left boundary of a length-kkk window is strictly [0,N−k][0, N - k][0,N−k]. Thus, lo = 0 and hi = len(arr) - k.

FAANG PRODUCTION TRAPS & EDGE CASES

A common naive attempt is binary searching for xxx and then using two pointers to expand outward. While correct, that approach takes O(log⁡N+k)O(\log N + k)O(logN+k) and involves intricate boundary checks when pointers reach array ends. Binary searching the window left edge eliminates all pointer expansion logic. A subtle trap is comparing arr[mid] to xxx directly instead of comparing the delta x−arr[mid]x - \text{arr}[mid]x−arr[mid] vs arr[mid+k]−x\text{arr}[mid + k] - xarr[mid+k]−x, which destroys monotonicity across window shifts.

Theory Context•Binary Search Boundary
MediumLC 658

Find K Closest Elements (LC 658)

Target Frequency:MetaGoogleAmazon

You're given a sorted integer array arr plus integers k and x; find the k values in arr that sit closest to x, and return them sorted in ascending order.

When comparing two candidates a and b for closeness to x: a wins if |a - x| < |b - x|, or if the distances tie and a < b.

Worked Examples

Example 1
Input:arr = [1,2,3,4,5], k = 4, x = 3
Output:[1,2,3,4]
Explanation: 2, 3 and 4 are within 1 of x = 3. Both 1 and 5 are 2 away, and the tie goes to the smaller value, 1.
Example 2
Input:arr = [1,1,2,3,4,5], k = 4, x = -1
Output:[1,1,2,3]
Explanation: x is below every value, so the four smallest values are the closest. The two 1s count as separate values.

⚖️Formal Constraints & Bounds

  • 1 <= k <= arr.length

  • 1 <= arr.length <= 104

  • arr is sorted in ascending order.

  • -104 <= arr[i], x <= 104

Deep-Dive & Conceptual Insights

Core Insight

Binary search the window's LEFT EDGE over [0, len(arr) - k - 1]. Comparing the departing element (x - arr[mid]) against the entering element (arr[mid + k] - x) is the monotonic feasibility question.

Real-World Scenario & Production Applications

Recommendation systems retrieving the k nearest neighbors to a query score from a pre-sorted index, and time-series systems fetching the k readings closest to a given timestamp.

Subproblems & Recurrence Decomposition3 Phases

🧩Subproblem 1: Window Left-Edge Domain

The answer is always a single contiguous window of size k. Its left edge lo ranges over [0, len(arr) - k] -- that entire range is the binary search domain, not the array's values.

Mathematical Recurrence / Code Invariant
lo, hi = 0, len(arr) - k

Step-by-Step Execution Trace Table

StepSearch Domain [lo, hi]midx - arr[mid] vs arr[mid+k] - xActionNew Search Domain
1[0, 0] (arr=[1,2,3,4,5], k=4, x=3)03-1=2 vs 5-3=2 → 2 > 2 is Falsehi = mid - 1 = -1[0, -1]
2[0, -1]—lo <= hi (0 <= -1) is FalseConvergedReturn arr[0:4] = [1,2,3,4]
Code Shape
Archetype Code Shape
Python
1lo, hi = 0, len(arr) - k - 1
2while lo <= hi:
3 mid = lo + (hi - lo) // 2
4 if x - arr[mid] > arr[mid + k] - x:
5 lo = mid + 1
6 else:
7 hi = mid - 1
8return arr[lo:lo + k]

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

There's no target index to find here — the thing being binary searched is the left edge of a sliding window of size k.

🥈 The Analogy: Sliding a Fixed-Size Frame Along a Number Line

Imagine a picture frame that can hold exactly k numbers, sliding along the sorted array. You want to park the frame so the k numbers inside are collectively closest to x. At any candidate position mid, sliding the frame one step right would drop arr[mid] (the leftmost element leaving) and pick up arr[mid + k] (the next element entering). Comparing "how far is the element about to leave" versus "how far is the element about to enter" tells you, with certainty, whether sliding right helps or hurts — and that yes/no question is monotonic across all valid left edges.

🔑 The Key Idea in the Code

Because arr is sorted, x - arr[mid] and arr[mid + k] - x shrink and grow predictably as the window slides, which is exactly the monotonic structure binary search needs — just measured between two elements a window-width apart, not between one element and x directly. When len(arr) == k (e.g. arr = [1], k = 1, x = 5), hi = len(arr) - k - 1 = -1, so the loop while lo <= hi never executes and returns arr[0:k] directly!

  • Binary searching closest element then expanding outward: Finding the single closest element and expanding two pointers outward takes O(log⁡N+K)O(\log N + K)O(logN+K) and has complex edge-case bounds. Binary searching the sliding window starting index directly takes O(log⁡(N−K))O(\log(N - K))O(log(N−K)) and is much cleaner.

  • Window comparator condition: When comparing window boundaries mid and mid + k, the transition condition is x - arr[mid] > arr[mid + k] - x. If the element at mid + k is closer to x than arr[mid], lo must move to mid + 1.

  • Tie-breaking preference for smaller values: When distances are equal (|a - x| == |b - x|), the problem requires picking the smaller value. The strict inequality > ensures that ties prefer the left element.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

Sorted array + fixed window size k + 'k closest elements to x' -- the answer is always a single CONTIGUOUS window, so its left edge is a search space of size n - k + 1.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Invariant: the optimal left edge candidate space is [lo, hi] = [0, len(arr) - k - 1]. Comparing x - arr[mid] (the element that would leave on a right shift) against arr[mid + k] - x (the element that would enter) tells you whether shifting right strictly helps, which is monotonic because arr is sorted.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • Comparing arr[mid] directly to x instead of comparing the two elements a window-shift would trade (arr[mid] leaving vs arr[mid + k] entering).

  • Using >= instead of > in the comparison silently breaks the tie-breaking rule (prefer the smaller of two equally-close values).

  • Comparing abs(arr[mid] - x) with abs(arr[mid + k] - x) instead of the signed x - arr[mid] with arr[mid + k] - x: two equal values below x tie, the search stops too early, and arr = [0,2,2,2,3,3,5], k = 1, x = 6 returns [2] instead of [5].

The 60-Second Interview Pitch

Say this out loud before you type a single line

"Since the answer is always one contiguous window of size k, I binary search its left edge candidate space over [0, len(arr) - k - 1] using while lo <= hi. At each mid I compare x - arr[mid] (departing) against arr[mid + k] - x (entering): if departing is strictly farther, shifting right helps, so lo = mid + 1; otherwise hi = mid - 1. This converges on the optimal window left edge lo in O(log(n - k)) time, then an O(k) slice returns the answer."

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(log(n - k) + k)

Look at the while loop: while lo <= hi: searches over the candidate window boundaries with hi = len(arr) - k - 1. Each iteration performs O(1) comparisons (x - arr[mid] vs arr[mid + k] - x) and halves the range, terminating in O(log(n - k)) iterations. Slicing arr[lo:lo + k] afterward costs O(k).

SPACE COMPLEXITY

O(k) Output

Look at memory allocations: Call stack uses O(1) Iterative. The only allocation is the O(k) output slice returned to the caller -- no auxiliary heaps are used during the search itself.

Formal Recurrence Relation

T(N,K)=O(log⁡(N−K))+O(K)T(N, K) = O(\log(N - K)) + O(K)T(N,K)=O(log(N−K))+O(K)

Derivation Progression

Window Left-Edge Domain

left∈[0,N−K−1]left \in [0, N - K - 1]left∈[0,N−K−1]

Every valid window candidate is tested by its left edge, searching over N - K positions with while lo <= hi.

Trade Comparison

abs(arr[mid]−x) vs abs(arr[mid+K]−x)\text{abs}(arr[mid] - x) \text{ vs } \text{abs}(arr[mid+K] - x)abs(arr[mid]−x) vs abs(arr[mid+K]−x)

Comparing the departing and entering elements of a one-step shift is a monotonic O(1) feasibility test.

Convergence + Slice

O(log⁡(N−K))+O(K)O(\log(N-K)) + O(K)O(log(N−K))+O(K)

Binary search converges on the optimal left edge, then a single O(K) slice materializes the answer.

Variable Definitions

NNN

Total number of elements in the sorted array

KKK

Fixed size of the closest-elements window

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative while loop with zero recursion frames

🔵 Auxiliary Heap

O(1) Only scalar pointers during the search

🟢 Output Space

O(K) Result slice of K closest elements

Boundary Best / Worst Cases

Best Case

O(K)O(K)O(K) when K == N (the whole array is the answer, no search needed).

Average Case

O(log⁡(N−K)+K)O(\log(N - K) + K)O(log(N−K)+K).

Worst Case

O(log⁡(N−K)+K)O(\log(N - K) + K)O(log(N−K)+K) for K ≪ N.

Recurrence Tree Topology

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

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

The statement specifies a "sorted integer array arr, two integers k and x" and asks for the "k closest integers to x" Because the input array is already sorted, any kkk closest elements must form a contiguous window of length kkk! Finding kkk closest elements therefore reduces to finding the optimal left index of that window, denoted by left_index ∈[0,N−k]\in [0, N - k]∈[0,N−k]. This triggers a binary search directly over the window's starting index.

CONSTRAINTS & BOUNDS

With 1≤k≤N≤1041 \le k \le N \le 10^41≤k≤N≤104, the search space for the left boundary of a length-kkk window is strictly [0,N−k][0, N - k][0,N−k]. Thus, lo = 0 and hi = len(arr) - k.

FAANG PRODUCTION TRAPS & EDGE CASES

A common naive attempt is binary searching for xxx and then using two pointers to expand outward. While correct, that approach takes O(log⁡N+k)O(\log N + k)O(logN+k) and involves intricate boundary checks when pointers reach array ends. Binary searching the window left edge eliminates all pointer expansion logic. A subtle trap is comparing arr[mid] to xxx directly instead of comparing the delta x−arr[mid]x - \text{arr}[mid]x−arr[mid] vs arr[mid+k]−x\text{arr}[mid + k] - xarr[mid+k]−x, which destroys monotonicity across window shifts.

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