Most Common ElementsLoading saved progress…

Most Common Elements

You're building a "trending now" panel. Every time someone views a product, its id lands in a long array of view events, and you want the k ids that show up most often. This is the classic Top K Frequent Elements problem: given an array of integers, return the k values that appear most frequently. The interesting part is doing it without sorting the whole array, and deciding what happens when two values tie on frequency.

Signature

// nums: an array of integers (may include negatives and duplicates)
// k:    how many of the most frequent values to return (0 ≤ k ≤ number of distinct values)
// returns: an array of k integers, ordered most-frequent first
function arrayMostCommonElements(nums: number[], k: number): number[];

Examples

// 1 appears 3 times, 2 appears twice, 3 appears once.
// The two most frequent are 1 then 2.
arrayMostCommonElements([1, 1, 1, 2, 2, 3], 2); // → [1, 2]
// A tie: both 5 and 9 appear twice, 7 appears once. We need k = 2.
// 5 and 9 are tied on frequency, so the tie-break decides their order:
// 5 first appears at index 0, 9 first appears at index 1, so 5 ranks ahead.
arrayMostCommonElements([5, 9, 5, 9, 7], 2); // → [5, 9]

Notes

  • Order by descending frequency. The most frequent value comes first, then the next, and so on. The return array has exactly k elements.
  • Ties break by first appearance. When two values share the same frequency, the one whose first occurrence in nums has the smaller index ranks higher. This makes the output fully deterministic — no relying on insertion order of a particular data structure.
  • k is within range. You can assume 0 ≤ k ≤ the number of distinct values in nums. You don't need to clamp or throw for an out-of-range k.
  • k = 0 returns []. Asking for the top zero elements yields an empty array.
  • Negatives and duplicates are normal input. Treat -3 like any other value; it's only the count that matters.
  • You don't need to handle non-integer or non-array input. Assume nums is an array of integers.
Loading editor…