Second Highest Occurring Element

Pattern: Hashing basics

easy

Count values, find the highest count, then pick the best value among those whose count is strictly lower.

The problem

You are given an array nums of between 1 and 100,000 whole numbers. Find the highest count any value has. Among the values whose count is strictly lower than that, return the one with the highest count. If several tie, return the smallest. If every value has the highest count (so nothing is lower), return -1.

For example, in [1, 2, 2, 3, 3, 3] the answer is 2, and in [4, 4, 1, 1] the answer is -1, because 4 and 1 both have the highest count.

On the original site the problem is written a little differently, so use the link above for its exact wording and its tie rules. The function name secondMostFrequentElement and the rules above are this guide's own.

Think first

  • In [1, 1, 1, 2, 2, 3, 3, 4], which value is most frequent? Which values come "second"?
  • If two values both have the highest count, is either of them second?
  • What should be returned for [7]?

Hints

    Brute force, and why it fails

    Sort the distinct values by count (highest first, then smaller value first) and walk down the list until the count drops. That works in O(n log n) and is a reasonable answer. Two passes over the counts do it in O(n) without sorting.

    The key insight

    "Second" means "best among everything strictly below the top count". Find the top count first, then run the usual best-so-far scan while skipping values with that count.

    Dry run

    10 
    11 
    12 
    23 
    24 
    35 
    36 
    47 
    count{1: 3, 2: 2, 3: 2, 4: 1}

    nums = [1, 1, 1, 2, 2, 3, 3, 4]. After the counting pass, 1 appears 3 times, 2 and 3 twice each, and 4 once.

    Step 1 of 6

    The plan

    count = map from value to how many times it appears
    maxCount = the largest count in the map
    
    second = -1
    secondCount = 0
    for each (value, times) in count:
        if times == maxCount:
            continue                      # most frequent: not a candidate
        if times > secondCount or (times == secondCount and value < second):
            second = value
            secondCount = times
    return second
    

    Complexity

    Time
    O(n)
    Space
    O(k)

    One pass to count and two passes over the k distinct values. The map holds k entries.

    Edge cases

    • [7]: the only value has the top count, so the answer is -1.
    • All values with the same count, such as [4, 4, 1, 1]: -1.
    • Several values tie for second: the smallest wins, so [9, 8, 9, 8, 7, 7, 7, 6] returns 8.
    • Negative values are fine. [-3, -3, -3, -2, -2, -1, -1] returns -2. (A real answer of -1 would look the same as "none", which is a weakness of the -1 convention.)
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int secondMostFrequentElement(int[] nums) {
            Map<Integer, Integer> count = new HashMap<>();
            for (int x : nums) {
                count.put(x, count.getOrDefault(x, 0) + 1);
            }
            int maxCount = 0;
            for (int times : count.values()) {
                maxCount = Math.max(maxCount, times);
            }
            int second = -1;
            int secondCount = 0;
            for (Map.Entry<Integer, Integer> entry : count.entrySet()) {
                int value = entry.getKey();
                int times = entry.getValue();
                if (times == maxCount) {
                    continue;                       // the most frequent values are not candidates
                }
                if (times > secondCount || (times == secondCount && value < second)) {
                    second = value;
                    secondCount = times;
                }
            }
            return second;
        }
    }

    C++

    class Solution {
    public:
        int secondMostFrequentElement(vector<int>& nums) {
            unordered_map<int, int> count;
            for (int x : nums) {
                count[x]++;
            }
            int maxCount = 0;
            for (auto& entry : count) {
                maxCount = max(maxCount, entry.second);
            }
            int second = -1;
            int secondCount = 0;
            for (auto& entry : count) {
                int value = entry.first;
                int times = entry.second;
                if (times == maxCount) {
                    continue;                       // the most frequent values are not candidates
                }
                if (times > secondCount || (times == secondCount && value < second)) {
                    second = value;
                    secondCount = times;
                }
            }
            return second;
        }
    };

    Python

    class Solution:
        def secondMostFrequentElement(self, nums):
            count = {}
            for x in nums:
                count[x] = count.get(x, 0) + 1
            max_count = max(count.values())
            second = -1
            second_count = 0
            for value, times in count.items():
                if times == max_count:
                    continue                        # the most frequent values are not candidates
                if times > second_count or (times == second_count and value < second):
                    second = value
                    second_count = times
            return second

    Common mistakes

    • Treating "second" as the second entry in some order, instead of the best value with a lower count.
    • Picking a value that ties with the top count.
    • Tracking the top and second in one pass without handling a new top correctly, which is easy to get wrong. Two passes are simpler and still O(n).

    Similar problems