Learn
Practice
Interview
Resources
Newsletter
F
Toggle theme
0
F
0
Toggle menu
Animations
← Back to All Animations
Top K Frequent Words
Bookmark
Input
Standard
Larger
Custom
words
=
[i, love, leetcode, i, love, coding]
,
k
=
2
INPUT WORDS
i
love
leetcode
i
love
coding
find the k most frequent words
INPUT WORDS
i
love
leetcode
i
love
coding
find the k most frequent words
INPUT WORDS
i
love
leetcode
i
love
coding
i
FREQUENCY MAP
i
:
1
count '
i
' →
1
INPUT WORDS
i
love
leetcode
i
love
coding
i
FREQUENCY MAP
i
:
1
love
:
1
leetcode
:
1
count '
leetcode
' →
1
INPUT WORDS
i
love
leetcode
i
love
coding
i
FREQUENCY MAP
i
:
2
love
:
2
leetcode
:
1
count '
love
' →
2
INPUT WORDS
i
love
leetcode
i
love
coding
FREQUENCY MAP
i
:
2
love
:
2
leetcode
:
1
coding
:
1
BUCKETS (frequency → words)
freq
2
freq
1
bucket
buckets[freq]
— group words by frequency
INPUT WORDS
i
love
leetcode
i
love
coding
FREQUENCY MAP
i
:
2
love
:
2
leetcode
:
1
coding
:
1
BUCKETS (frequency → words)
freq
2
freq
1
i
love
leetcode
place '
leetcode
' → buckets[
1
]
INPUT WORDS
i
love
leetcode
i
love
coding
FREQUENCY MAP
i
:
2
love
:
2
leetcode
:
1
coding
:
1
BUCKETS (frequency → words)
freq
2
freq
1
i
love
leetcode
coding
sort bucket[
2
] alphabetically
INPUT WORDS
i
love
leetcode
i
love
coding
FREQUENCY MAP
i
:
2
love
:
2
leetcode
:
1
coding
:
1
BUCKETS (frequency → words)
freq
2
freq
1
i
love
leetcode
coding
every bucket is sorted alphabetically
INPUT WORDS
i
love
leetcode
i
love
coding
FREQUENCY MAP
i
:
2
love
:
2
leetcode
:
1
coding
:
1
BUCKETS (frequency → words)
freq
2
freq
1
love
leetcode
coding
RESULT (top 2)
i
collect '
i
' (
1
/ 2)
INPUT WORDS
i
love
leetcode
i
love
coding
FREQUENCY MAP
i
:
2
love
:
2
leetcode
:
1
coding
:
1
BUCKETS (frequency → words)
freq
2
freq
1
leetcode
coding
RESULT (top 2)
i
love
top 2 = [i, love]
algo
master
.
io
Step:
Find the k most frequent words using bucket sort
0 / 19
Input
Standard
Larger
Custom
words
=
[i, love, leetcode, i, love, coding]
,
k
=
2
0 / 19
algo
master
.
io
Step:
Find the k most frequent words using bucket sort