Second highest occurring element

Beginner Problems Basic Hashing Easy
  • This type of algorithm is quite often used in the world of data analytics and marketing
  • Understanding frequency distribution in a dataset is key for identifying trends or patterns
  • For example, a streaming service like Netflix or Spotify might use a similar algorithm to identify the second most frequently watched or listened-to genre or artist, to suggest it to their viewers or listeners, enhancing personalization and user experience based on these insights
  • It could also be used in text analytics or natural language processing to find the second most frequently used word in a text, which can be instrumental in sentiment analysis, SEO keyword analysis, and more

Given an array of n integers, find the second most frequent element in it. If there are multiple elements that appear a maximum number of times, find the smallest of them. If second most frequent element does not exist return -1.

Examples:

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


Output: 2


Explanation: The number 2 appears the second most (2 times) and number 3 appears the most(3 times). 

Input: arr = [4, 4, 5, 5, 6, 7]


Output: 6


Explanation: Both 6 and 7 appear second most times, but 6 is smaller.

Input: arr = [10, 9 ,7, 7]

Constraints

  • 1 <= n <= 104
  • 1 <= arr[i] <= 104

Company Tags

TCS Cognizant Accenture Infosys Capgemini Wipro IBM HCL Tech Mahindra MindTree