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•Priority Queue / Heap
MediumLC 347

Top K Frequent Elements (LeetCode 347)

Target Frequency:MetaAppleAmazon

You're given an integer array nums and an integer k. Report the k values that appear most often in nums — ties in return order don't matter, so any ordering of the k values is accepted.

Follow-up: a full O(n log n) sort is accepted, but can you do better? Aim for a time complexity below O(n log n), where n is the length of nums.

Worked Examples

Example 1
Input:nums = [1,1,1,2,2,3], k = 2
Output:[1,2]
Explanation: 1 appears 3 times and 2 twice, more often than 3.
Example 2
Input:nums = [1], k = 1
Output:[1]
Explanation: There is only one value.
Example 3
Input:nums = [1,2,1,2,1,2,3,1,3,2], k = 2
Output:[1,2]
Explanation: 1 and 2 appear 4 times each; 3 appears only twice.

⚖️Formal Constraints & Bounds

  • 1 <= nums.length <= 105

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

  • k is in the range [1, the number of unique elements in the array].

  • It is guaranteed that the answer is unique.

Deep-Dive & Conceptual Insights

Core Insight

Bounding the heap to size K ensures all push/pop heap operations take O(log K) rather than O(log N) time.

Real-World Scenario & Production Applications

Real-time analytics trending topics (Twitter/X hashtag rankings) and cache eviction telemetry.

Subproblems & Recurrence Decomposition3 Phases

🧩Subproblem 1: Frequency Hash Map Tallying

Count element frequencies in O(N) time using a hash map count = Counter(nums).

Mathematical Recurrence / Code Invariant
count = Counter(nums)

Step-by-Step Execution Trace Table

StepItem Pushed (freq, val)Min-Heap State After PushSizeOver k = 2?Evicted RootHeap State After Step
1(3, 1)[(3, 1)]1No—[(3, 1)]
2(2, 2)[(2, 2), (3, 1)]2No—[(2, 2), (3, 1)]
3(1, 3)[(1, 3), (3, 1), (2, 2)]3Yes(1, 3) (lowest freq)[(2, 2), (3, 1)]
Code Shape
Archetype Code Shape
Python
1counts = Counter(nums)
2min_heap = []
3for value, count in counts.items():
4 heappush(min_heap, (count, value))
5 if len(min_heap) > k:
6 heappop(min_heap)
7return [value for count, value in min_heap]

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition
Code / Blueprint
Identifying the $K$ most frequent elements requires counting occurrences with a hash map and then extracting the $K$ highest frequencies. Maintaining a min-heap of capacity $K$ keyed by frequency ensures that the smallest frequency among the current top $K$ sits at the root. Evicting the root whenever size exceeds $K$ bounds runtime to $O(N \log K)$ and space to $O(N + K)$.
 
🏆 The Analogy: A Leaderboard With Only k Seats

Imagine a leaderboard with exactly k seats, currently occupied by whoever has qualified so far. A new contender only earns a seat by beating the weakest person currently on the board — and the moment they do, the weakest person gets bumped off. You never need to compare a new contender against everyone in the whole competition, only against the single weakest name currently on the board, which a min-heap hands you instantly.

🔑 The Key Idea in the Code

A min-heap (not a max-heap) is the right tool specifically because the operation you need repeatedly is "find and remove the smallest" — the weakest current qualifier — not the largest.

  • Sorting full dictionary O(Ulog⁡U)O(U \log U)O(UlogU): Sorting all unique elements by frequency is O(Ulog⁡U)O(U \log U)O(UlogU). A min-heap of size KKK keyed on frequency maintains the top KKK in O(Ulog⁡K)O(U \log K)O(UlogK), and bucket sort achieves O(N)O(N)O(N).

  • Inverting heap key ordering: Storing (key, freq) in Python's min-heap sorts primarily by key. Always store (freq, key) so the heap prioritizes frequency.

  • Popping from min-heap leaves root as smallest: In a min-heap of size kkk, the elements left in the heap at the end are the kkk most frequent, but popped in ascending order. Reverse if descending order is requested.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

Find top / most frequent K elements from unsorted data.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Decision rule: push every (count, value), and pop the root whenever len(min_heap) > k. The root is the least frequent of the k + 1 kept, so it can never be in the answer.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • Heap direction: the k most frequent need a min-heap, because heappop removes the root; a max-heap of size k would evict the most frequent value.

  • Heap ordering: push tuple (freq, num) so heap orders by frequency, not number value.

The 60-Second Interview Pitch

Say this out loud before you type a single line

"I'd use a Top-K Heap. First I count each value with a Counter. Then I walk the counts and push each (count, value) pair onto a min-heap, and whenever the heap grows past k, I pop its root. The root is the least frequent of the k + 1 items kept, and k others already beat it, so it can never be in the answer. After the last push, the heap holds exactly the k most frequent values. The trap is the direction: to keep the k largest I need a min-heap, because its root is the item I evict next; a max-heap would throw away the winner. Counting is O(N) and each push or pop is O(log K), so the time is O(N log K), with O(N) space for the counts plus O(K) for the heap."

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N log K)

Look at the execution steps: Frequency hash map takes O(N) to build. Iterates through unique elements and maintains min-heap of size K: each push/pop costs O(log K). Total O(N log K) time (or O(N) via bucket sort).

SPACE COMPLEXITY

O(N) counts + O(K) heap

Look at memory allocations: Call stack uses O(1) Iterative. Hash map of size N and min-heap of size K.

Formal Recurrence Relation

T(N, K) = O(N) + N · O(log K) = O(N log K)

Derivation Progression

Frequency Map Build

O(N) linear hash map tally

Counts occurrences of each number in array.

Bounded Heap Sifting

U unique keys × O(log K) min-heap push/pop

Maintains the top K highest frequency elements.

Compound Time Bound

O(N log K) ≤ O(N log N)

Optimal when K << N.

Variable Definitions

NNN

Total number of elements in the array

KKK

Number of top frequent elements requested (min-heap capacity)

UUU

Number of unique elements in the array (U ≤ N)

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative

🔵 Auxiliary Heap

O(N) counts + O(K) heap

🟢 Output Space

O(K) List of top K frequent elements

Boundary Best / Worst Cases

Best Case

O(N)O(N)O(N) if K=1 or all elements identical.

Average Case

O(Nlog⁡K)O(N \log K)O(NlogK).

Worst Case

O(Nlog⁡K)O(N \log K)O(NlogK) with all unique elements.

Binary Heap Priority Queue Tree

Binary Heap Priority Queue Tree
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Key triggers: "the k values that appear most often", "any order", and the follow-up to beat a full sort. Only the top k of many counted keys matter, so a Top-K Heap keeps k of them and throws the rest away as it goes.

CONSTRAINTS & BOUNDS

1≤nums.length≤1051 \le nums.length \le 10^51≤nums.length≤105 and −104≤nums[i]≤104-10^4 \le nums[i] \le 10^4−104≤nums[i]≤104, so there are at most U≤2⋅104+1U \le 2 \cdot 10^4 + 1U≤2⋅104+1 distinct values, and kkk can be as large as UUU. After the O(N)O(N)O(N) count the heap does at most UUU pushes and pops of O(log⁡k)O(\log k)O(logk) each: O(N+Ulog⁡k)O(N + U \log k)O(N+Ulogk), inside the O(Nlog⁡K)O(N \log K)O(NlogK) bound.

FAANG PRODUCTION TRAPS & EDGE CASES

Heap direction: keeping the k largest needs a min-heap, because its root is the item evicted next; a max-heap pops the winner. When k is close to U, the heap saves little and sorting the counts (or bucketing by count, O(N)O(N)O(N)) is simpler.

Core Algorithmic State Invariants

  1. One Push per Distinct Value

The loop runs over counts.items(), so the heap sees each distinct value once, not each element: with -10^4 <= nums[i] <= 10^4 there are at most 2 * 10^4 + 1 pushes, even when nums holds 10^5 numbers.

  1. Why the Unique-Answer Promise Matters

LeetCode promises the answer is unique, so the k-th and (k+1)-th counts are never tied at the cut. Without that promise, two values with the same count could compete for the last seat, and which one heappop evicts would depend only on the value used as the tie-breaker.

  1. Any Order Is Accepted

The answer is read straight out of min_heap with [value for count, value in min_heap], in heap order rather than sorted order. That is enough because the problem accepts the k values in any order, so no final sort is needed.

Theory Context•Priority Queue / Heap
MediumLC 347

Top K Frequent Elements (LeetCode 347)

Target Frequency:MetaAppleAmazon

You're given an integer array nums and an integer k. Report the k values that appear most often in nums — ties in return order don't matter, so any ordering of the k values is accepted.

Follow-up: a full O(n log n) sort is accepted, but can you do better? Aim for a time complexity below O(n log n), where n is the length of nums.

Worked Examples

Example 1
Input:nums = [1,1,1,2,2,3], k = 2
Output:[1,2]
Explanation: 1 appears 3 times and 2 twice, more often than 3.
Example 2
Input:nums = [1], k = 1
Output:[1]
Explanation: There is only one value.
Example 3
Input:nums = [1,2,1,2,1,2,3,1,3,2], k = 2
Output:[1,2]
Explanation: 1 and 2 appear 4 times each; 3 appears only twice.

⚖️Formal Constraints & Bounds

  • 1 <= nums.length <= 105

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

  • k is in the range [1, the number of unique elements in the array].

  • It is guaranteed that the answer is unique.

Deep-Dive & Conceptual Insights

Core Insight

Bounding the heap to size K ensures all push/pop heap operations take O(log K) rather than O(log N) time.

Real-World Scenario & Production Applications

Real-time analytics trending topics (Twitter/X hashtag rankings) and cache eviction telemetry.

Subproblems & Recurrence Decomposition3 Phases

🧩Subproblem 1: Frequency Hash Map Tallying

Count element frequencies in O(N) time using a hash map count = Counter(nums).

Mathematical Recurrence / Code Invariant
count = Counter(nums)

Step-by-Step Execution Trace Table

StepItem Pushed (freq, val)Min-Heap State After PushSizeOver k = 2?Evicted RootHeap State After Step
1(3, 1)[(3, 1)]1No—[(3, 1)]
2(2, 2)[(2, 2), (3, 1)]2No—[(2, 2), (3, 1)]
3(1, 3)[(1, 3), (3, 1), (2, 2)]3Yes(1, 3) (lowest freq)[(2, 2), (3, 1)]
Code Shape
Archetype Code Shape
Python
1counts = Counter(nums)
2min_heap = []
3for value, count in counts.items():
4 heappush(min_heap, (count, value))
5 if len(min_heap) > k:
6 heappop(min_heap)
7return [value for count, value in min_heap]

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition
Code / Blueprint
Identifying the $K$ most frequent elements requires counting occurrences with a hash map and then extracting the $K$ highest frequencies. Maintaining a min-heap of capacity $K$ keyed by frequency ensures that the smallest frequency among the current top $K$ sits at the root. Evicting the root whenever size exceeds $K$ bounds runtime to $O(N \log K)$ and space to $O(N + K)$.
 
🏆 The Analogy: A Leaderboard With Only k Seats

Imagine a leaderboard with exactly k seats, currently occupied by whoever has qualified so far. A new contender only earns a seat by beating the weakest person currently on the board — and the moment they do, the weakest person gets bumped off. You never need to compare a new contender against everyone in the whole competition, only against the single weakest name currently on the board, which a min-heap hands you instantly.

🔑 The Key Idea in the Code

A min-heap (not a max-heap) is the right tool specifically because the operation you need repeatedly is "find and remove the smallest" — the weakest current qualifier — not the largest.

  • Sorting full dictionary O(Ulog⁡U)O(U \log U)O(UlogU): Sorting all unique elements by frequency is O(Ulog⁡U)O(U \log U)O(UlogU). A min-heap of size KKK keyed on frequency maintains the top KKK in O(Ulog⁡K)O(U \log K)O(UlogK), and bucket sort achieves O(N)O(N)O(N).

  • Inverting heap key ordering: Storing (key, freq) in Python's min-heap sorts primarily by key. Always store (freq, key) so the heap prioritizes frequency.

  • Popping from min-heap leaves root as smallest: In a min-heap of size kkk, the elements left in the heap at the end are the kkk most frequent, but popped in ascending order. Reverse if descending order is requested.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

Find top / most frequent K elements from unsorted data.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Decision rule: push every (count, value), and pop the root whenever len(min_heap) > k. The root is the least frequent of the k + 1 kept, so it can never be in the answer.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • Heap direction: the k most frequent need a min-heap, because heappop removes the root; a max-heap of size k would evict the most frequent value.

  • Heap ordering: push tuple (freq, num) so heap orders by frequency, not number value.

The 60-Second Interview Pitch

Say this out loud before you type a single line

"I'd use a Top-K Heap. First I count each value with a Counter. Then I walk the counts and push each (count, value) pair onto a min-heap, and whenever the heap grows past k, I pop its root. The root is the least frequent of the k + 1 items kept, and k others already beat it, so it can never be in the answer. After the last push, the heap holds exactly the k most frequent values. The trap is the direction: to keep the k largest I need a min-heap, because its root is the item I evict next; a max-heap would throw away the winner. Counting is O(N) and each push or pop is O(log K), so the time is O(N log K), with O(N) space for the counts plus O(K) for the heap."

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N log K)

Look at the execution steps: Frequency hash map takes O(N) to build. Iterates through unique elements and maintains min-heap of size K: each push/pop costs O(log K). Total O(N log K) time (or O(N) via bucket sort).

SPACE COMPLEXITY

O(N) counts + O(K) heap

Look at memory allocations: Call stack uses O(1) Iterative. Hash map of size N and min-heap of size K.

Formal Recurrence Relation

T(N, K) = O(N) + N · O(log K) = O(N log K)

Derivation Progression

Frequency Map Build

O(N) linear hash map tally

Counts occurrences of each number in array.

Bounded Heap Sifting

U unique keys × O(log K) min-heap push/pop

Maintains the top K highest frequency elements.

Compound Time Bound

O(N log K) ≤ O(N log N)

Optimal when K << N.

Variable Definitions

NNN

Total number of elements in the array

KKK

Number of top frequent elements requested (min-heap capacity)

UUU

Number of unique elements in the array (U ≤ N)

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative

🔵 Auxiliary Heap

O(N) counts + O(K) heap

🟢 Output Space

O(K) List of top K frequent elements

Boundary Best / Worst Cases

Best Case

O(N)O(N)O(N) if K=1 or all elements identical.

Average Case

O(Nlog⁡K)O(N \log K)O(NlogK).

Worst Case

O(Nlog⁡K)O(N \log K)O(NlogK) with all unique elements.

Binary Heap Priority Queue Tree

Binary Heap Priority Queue Tree
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Key triggers: "the k values that appear most often", "any order", and the follow-up to beat a full sort. Only the top k of many counted keys matter, so a Top-K Heap keeps k of them and throws the rest away as it goes.

CONSTRAINTS & BOUNDS

1≤nums.length≤1051 \le nums.length \le 10^51≤nums.length≤105 and −104≤nums[i]≤104-10^4 \le nums[i] \le 10^4−104≤nums[i]≤104, so there are at most U≤2⋅104+1U \le 2 \cdot 10^4 + 1U≤2⋅104+1 distinct values, and kkk can be as large as UUU. After the O(N)O(N)O(N) count the heap does at most UUU pushes and pops of O(log⁡k)O(\log k)O(logk) each: O(N+Ulog⁡k)O(N + U \log k)O(N+Ulogk), inside the O(Nlog⁡K)O(N \log K)O(NlogK) bound.

FAANG PRODUCTION TRAPS & EDGE CASES

Heap direction: keeping the k largest needs a min-heap, because its root is the item evicted next; a max-heap pops the winner. When k is close to U, the heap saves little and sorting the counts (or bucketing by count, O(N)O(N)O(N)) is simpler.

Core Algorithmic State Invariants

  1. One Push per Distinct Value

The loop runs over counts.items(), so the heap sees each distinct value once, not each element: with -10^4 <= nums[i] <= 10^4 there are at most 2 * 10^4 + 1 pushes, even when nums holds 10^5 numbers.

  1. Why the Unique-Answer Promise Matters

LeetCode promises the answer is unique, so the k-th and (k+1)-th counts are never tied at the cut. Without that promise, two values with the same count could compete for the last seat, and which one heappop evicts would depend only on the value used as the tie-breaker.

  1. Any Order Is Accepted

The answer is read straight out of min_heap with [value for count, value in min_heap], in heap order rather than sorted order. That is enough because the problem accepts the k values in any order, so no final sort is needed.

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