Stable Top K Frequent Words
Updated
Problem statement
Given an array of words and an integer k, return the k distinct words with the highest frequencies.
Rank words by descending frequency. When two words have the same frequency, rank the word whose first occurrence has the smaller array index first. Return the selected words in this ranking order.
Function
topKFrequentStable(words: String[], k: int) → String[]Examples
Example 1
words = ["apple","banana","apple","cherry","banana","date"]k = 2return = ["apple","banana"]apple and banana each occur twice. The first apple appears at index 0, before the first banana at index 1.
Example 2
words = ["z","a","z","a","b"]k = 3return = ["z","a","b"]z and a have frequency two and keep first-occurrence order. The remaining word b is third.
Example 3
words = ["solo"]k = 1return = ["solo"]The only distinct word is selected.
Constraints
1 <= words.length <= 2000001 <= words[i].length <= 30- Each word contains lowercase English letters.
1 <= k <=the number of distinct words.
More Google Phone Screen questions
- Best Stock Trade with Buy and Sell DaysPHONE SCREEN · Seen Nov 2026
- Word Chain Jumps in a GridPHONE SCREEN · Seen Nov 2026
- Dice-Walk Winning ProbabilityPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Apartment Housemate PreferencesPHONE SCREEN · Seen Nov 2026
- Price at Query TimestampsPHONE SCREEN · Seen Nov 2026
- Course Schedule Cycle DetectionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Logger Rate Limiter with Every-Arrival HistoryPHONE SCREEN · Seen Nov 2026
- Minimum Total Layover WaitPHONE SCREEN · Seen Nov 2026
- Reach a Destination Through Scheduled FlightsPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
Similar questions at other companies
- Longest Consecutive Login StreakAmazon · ONSITE INTERVIEW
- Group AnagramsWorkday · PHONE SCREEN
- Time-Aware Search AutocompleteRoblox · PHONE SCREENRoblox interview questions
- Group AnagramsMicrosoft · ONSITE INTERVIEWMicrosoft interview questions
- Group AnagramsEPAM · PHONE SCREENEPAM interview questions
- Top K Frequent ElementsCapgemini · ONSITE INTERVIEWCapgemini interview questions
- Mutual-Friend RecommendationsMeta · ONSITE INTERVIEWMeta interview questions
- Find Duplicate File GroupsAnthropic · PHONE SCREENAnthropic interview questions
- Top K Frequent Elements with Larger-Value Tie BreakOracle · ONSITE INTERVIEWOracle interview questions
- Insert an Employee into an Organization HierarchyWaymo · PHONE SCREENWaymo interview questions