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.
// 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[];
// 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]
k elements.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.-3 like any other value; it's only the count that matters.nums is an array of integers.