Common Technical Interview Questions Series — #1
you can find the link to the series homepage here
Most frequently occurring item in an array
In this part, we will look at a very simple problem of finding the most frequent element in a given array
Import the ‘random’ module to create a random array and the time module to record the execution time of the program
import random
import time
a random array can be created like this:
# returns an array of 50 numbers from 1 to 20arr = [random.randint(1,20) for _ in range(50)]
this is just a decorator function to calculate the execution time of any function
the main idea behind solving this problem is to store the count of each unique element in a dictionary or a hash map.
first, iterate through all the elements of the array and if the element exists in the dictionary as a key then increment the value(count) of it by one. else, create a new key(element) and initialize its value(count) as one.
after going through the entire array, you now have the count of all the elements. all you need to do now is to iterate through the (key, value) pairs of the dictionary to find the key(element) with the maximum value(count)
and since we are going through the array only once, the time complexity of this function is O(n)
un-comment the @time_it line to return the execution time instead of the output
however, this can also be done in another way by getting the max_value as we are going through the array instead of separately iterating through the final dictionary