Start learning free

LESSON 229 OF 289 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Most Frequent Element in TypeScript: Count, Then Pick

Practice Read the full explanation

Given an array of integers nums, return the value that appears in it the most times.

If several values tie for the most appearances, return the one that shows up first in nums. nums has at least one number.

Example 1:

Input: nums = [1, 3, 2, 3, 1, 3]
Output: 3
Explanation: 3 appears three times, 1 twice and 2 once.

Example 2:

Input: nums = [5, 2, 2, 5, 9]
Output: 5
Explanation: 5 and 2 both appear twice. 5 shows up first (at index 0, while 2 first shows up at index 1), so the answer is 5.

Example 3:

Input: nums = [7]
Output: 7
Explanation: The only value is also the most frequent one.
STEP 1 OF 8
    Ctrl + Enter to check

    TYPESCRIPT · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Most Frequent Element in TypeScript, explained

    Problem overview

    The method mostFrequent receives an array of integers, nums, and returns the value that appears the most times. If several values tie, it returns the one that shows up first in nums. The array has at least one number.

    For [1, 3, 2, 3, 1, 3] the answer is 3: it appears three times, 1 twice and 2 once. For [5, 2, 2, 5, 9], both 5 and 2 appear twice, and 5 comes first, so the answer is 5. For [7] the answer is 7.

    Approach

    The solution uses two passes over nums.

    1. Count. Build an object that maps each value to how often it appears.
    2. Pick. Walk the array again and keep the value with the highest count.

    The second pass walks nums, not the counts object, and that is what settles ties. nums is visited in its own order, so values are met in the order they first appear. A value replaces the current best only when its count is strictly greater, so among values with the same count, the one met first stays.

    On [1, 3, 2, 3, 1, 3], the first pass produces {"1": 2, "2": 1, "3": 3}. The second pass starts with best = 1, whose count is 2. The number 3 has a count of 3, which is greater, so it becomes the best. Nothing after that beats a count of 3, so the method returns 3.

    On [5, 2, 2, 5, 9] the counts are {"2": 2, "5": 2, "9": 1}. The best starts at 5, with a count of 2. The number 2 also has 2, which is not greater, so 5 stays. The number 9 has 1. The answer is 5, the value that appears first in the array, even though the counts object lists 2 before 5.

    That last detail is the reason for the second pass over nums. The counts say how often each value appears. Only the array knows which value came first.

    A brute-force alternative counts each value by scanning the whole array for it, which takes O(n²) time. The dictionary replaces those repeated scans with one pass that remembers every count, so the later comparisons are lookups instead of searches.

    Step by step

    1. Create the dictionary. counts is an empty object of the type { [key: number]: number }.
    2. Loop over nums. Each number adds 1 to its own count.
    3. Known number. If num in counts, add 1 to counts[num].
    4. New number. Otherwise set counts[num] to 1, since an unknown key reads as undefined and undefined + 1 is NaN.
    5. Start the best at the first number. let best: number = nums[0] is the answer until something beats it.
    6. Walk nums again with a second for...of loop.
    7. Compare counts. If counts[num] > counts[best], make num the new best. The comparison is strict, so on a tie best keeps the earlier value.
    8. Return best.

    The solution in TypeScript

    class Solution {
        mostFrequent(nums: number[]): number {
            const counts: { [key: number]: number } = {};
            for (let num of nums) {
                if (num in counts) {
                    counts[num] += 1;
                } else {
                    counts[num] = 1;
                }
            }
            let best: number = nums[0];
            for (let num of nums) {
                if (counts[num] > counts[best]) {
                    best = num;
                }
            }
            return best;
        }
    }
    

    Details worth knowing:

    • Number keys become strings. The type { [key: number]: number } is allowed, but at run time an object's keys are always strings. counts[3] and counts["3"] are the same entry. Reading with a number works because the number is converted to a string for the lookup. Object keys that look like whole numbers are also listed in ascending numeric order: keys added as 10, 2 and 1 come out as ["1", "2", "10"]. The code never relies on that order.
    • The in operator asks whether the key exists, even when its value is 0 or another falsy value. Here every stored count is at least 1.
    • Negative numbers work. [-1, 4, 4, -1, 4] returns 4. A key such as "-1" is a perfectly good string.
    • Comparing with best. The first round compares nums[0] with itself, which is false, so it changes nothing.

    Complexity

    Time: O(n). Each of the two loops visits every number once, and each object lookup or update takes constant time on average.

    Space: O(k), where k is the number of different values, because counts has one entry per distinct value. In the worst case k equals n.

    Edge cases and common mistakes

    • Walking counts to find the best. The keys come out as strings, in an order that doesn't follow the array, so the tie rule would break and you would have to convert them back to numbers.
    • Using >=. The last tied value would win. For [5, 2, 2, 5, 9] it would return 2.
    • Forgetting the first-time case. The counts would be NaN, and comparisons with NaN are always false, so best would never change.
    • One element. [7] returns 7: the counts object is {"7": 1} and best never changes.
    • All values different. Every count is 1, no count is strictly greater than another, and the method returns nums[0], the first value.

    Testing

    • [1, 3, 2, 3, 1, 3] gives 3.
    • [5, 2, 2, 5, 9] gives 5.
    • [7] gives 7.
    • [-1, 4, 4, -1, 4] gives 4.
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free