Interview question
Return the top K frequent values
Implements top-K frequency selection with deterministic tie-breaking.
TL;DR
Implements top-K frequency selection with deterministic tie-breaking.
Dictionary counting, ordering, tie-breaking, input validation, and complexity trade-offs.
Practice the problem like a real interview: restate, reason, implement, and test.
Implement TopKFrequent(IEnumerable<string> values, int k). Count non-empty values case-insensitively, return at most K values ordered by frequency descending, then value ascending.
Next in Coding Practice: Flatten Tree Paths
Input: api, sql, api, cache, sql, api, with k = 2
Output: api, sql
k <= 0 returns an empty list.I would count normalized values in a dictionary and then sort the unique values by count descending and value ascending. For normal interview sizes this is clear and reliable. If the interviewer pushes on very large input, I would discuss a heap to avoid sorting every unique value, but I would start with the simpler correct solution.
public static IReadOnlyList<string> TopKFrequent(IEnumerable<string?>? values, int k)
{
if (values is null || k <= 0)
{
return Array.Empty<string>();
}
var counts = new Dictionary<string, int>(StringComparer.Ordinal);
foreach (var value in values)
{
if (string.IsNullOrWhiteSpace(value))
{
continue;
}
var normalized = value.Trim().ToLowerInvariant();
counts[normalized] = counts.TryGetValue(normalized, out var count) ? count + 1 : 1;
}
return counts
.OrderByDescending(pair => pair.Value)
.ThenBy(pair => pair.Key, StringComparer.Ordinal)
.Take(k)
.Select(pair => pair.Key)
.ToList();
}
Counting is O(n). Sorting unique values is O(m log m), where m is the number of unique normalized values. Space is O(m). A heap can reduce selection cost when m is huge and k is small.
API, api, and api to verify normalization.k <= 0.Spot a weak answer, missing edge case, or clearer explanation? Send it in.