Problem
FAANG · LeetCode #347

Top K Frequent Elements — three-stage drill

1The ProblemMedium

Top K Frequent Elements

Return the k elements that appear most often.

the k most frequent, k =21011122324351 appears 3×, 2 appears 2× → the two most frequentreturn[1, 2]
Examples
[1,1,1,2,2,3], k=2→ [1,2]

constraintThe answer is unique for the given k.

2The PatternTIME O(n) · SPACE O(n)

Arrays & Hashing

Trade space for time: a hash map turns 'have I seen this?' into an O(1) lookup.

remember what you've seen in a hash map → O(1) lookup4021722344scan›value → countseen = {4: 1}
Problems using this pattern
3The SolutionRESULT → [1, 2]

Step through it

phase 1 — count frequencies · k = 2101112232435x›↩ ANSWERtop k =?value → countfreq = {1: 1}
count: 1 → 1×
Step 1 / 7
Arrow keys to navigate · escape to reset

All problems by pattern

Backtracking

Recursive Descent