MEDIUM
DATA STRUCTURES AND ALGORITHMS

How to Solve Most Frequent Element in an Array

Written By
Adam Bhula

Most Frequent Element in an Array Introduction

The Most Frequent Element in an Array problem asks us to element that appears the most in a given array. This problem can be solved simply by using a map to increment the frequent count of each element as we come across them and return the integer with the highest count at the end.

Most Frequent Element in an Array Problem

Given an array of integers, find the most frequent element in the array. Write a method that takes an array of integers and returns an integer. If there is a tie, you can just return any.

Example Inputs and Outputs

Example 1

Input: arr = [1, 2, 3, 3]
Output: 3

Most Frequent Element in an Array Solutions

To solve this problem, we can use a map or a map-like data structure to iterate through the given array and keep track of the count of each integer. We start by initializing an empty count map and two variables: mostFrequent to store the current most frequent integer, and maxCount to keep track of its count. Next, we iterate through the array element by element. For each integer we find, we check if it exists in the count map. If it does, we increment its count; otherwise, we add it to the count map with an initial count of 1.

During the iteration, we also update the mostFrequent and maxCount variables whenever we find an integer with a count higher than the current maximum count. This way, by the end of the iteration, we'll have identified the integer with the highest count. This integer represents the most frequent integer in the array.

def findMostFrequent(nums):
    countMap = {}
    maxCount = 0
    mostFrequent = None

    for num in nums:
        if num in countMap:
            countMap[num] += 1
        else:
            countMap[num] = 1

        if countMap[num] > maxCount:
            maxCount = countMap[num]
            mostFrequent = num

    return mostFrequent

# Test case
arr = [1, 2, 3, 3]
result = findMostFrequent(arr)
print(result)  # Output: 3

Time/Space Complexity Analysis

  • Time Complexity: O(N), where N is the size of the input array.
  • Space Complexity: O(K), where k is the number of unique integers in the input array.

About interviewing.io

interviewing.io is a mock interview practice platform. We've hosted over 100K mock interviews, conducted by senior engineers from FAANG & other top companies. We've drawn on data from these interviews to bring you the best interview prep resource on the web.

We know exactly what to do and say to get the company, title, and salary you want.

Interview prep and job hunting are chaos and pain. We can help. Really.