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.
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]
Imagine you have a bag full of marbles, each with a different number. Your task is to find the marble that appears the second most number of times in the bag. To solve this, we need to keep track of the number of times each marble appears. We should identify the marble with the highest occurrence first and then look for the marble that comes next in terms of frequency. This way, we ensure that we correctly find the second highest occurring marble in the bag.
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
/* Function to get the second highest
occurring element in array */
int secondMostFrequentElement(vector<int> &nums) {
// Variable to store the size of array
int n = nums.size();
/* Variable to store maximum frequency
and second Max frequency */
int maxFreq = 0;
int secMaxFreq = 0;
/* Variable to store elements with most
and second most frequency */
int maxEle = -1, secEle = -1;
// Visited array
vector<bool> visited(n, false);
// First loop
for(int i = 0; i < n; i++) {
// Skip second loop if already visited
if(visited[i]) continue;
/* Variable to store frequency
of current element */
int freq = 0;
// Second loop
for(int j = i; j < n; j++) {
if(nums[i] == nums[j]) {
freq++;
visited[j] = true;
}
}
/* Update variables if new element
having highest frequency or second
highest frequency is found */
if(freq > maxFreq) {
secMaxFreq = maxFreq;
maxFreq = freq;
secEle = maxEle;
maxEle = nums[i];
}
else if(freq == maxFreq) {
maxEle = min(maxEle, nums[i]);
}
else if(freq > secMaxFreq) {
secMaxFreq = freq;
secEle = nums[i];
}
else if(freq == secMaxFreq) {
secEle = min(secEle, nums[i]);
}
}
// Return the result
return secEle;
}
};
int main() {
vector<int> nums = {4, 4, 5, 5, 6, 7};
/* Creating an instance of
Solution class */
Solution sol;
/* Function call to get the second
highest occurring element in array */
int ans = sol.secondMostFrequentElement(nums);
cout << "The second highest occurring element in the array is: " << ans;
return 0;
}
import java.util.*;
class Solution {
/* Function to get the second highest
occurring element in array */
public int secondMostFrequentElement(int[] nums) {
// Variable to store the size of array
int n = nums.length;
/* Variable to store maximum frequency
and second Max frequency */
int maxFreq = 0;
int secMaxFreq = 0;
/* Variable to store elements with most
and second most frequency */
int maxEle = -1, secEle = -1;
// Visited array
boolean[] visited = new boolean[n];
// First loop
for(int i = 0; i < n; i++) {
// Skip second loop if already visited
if(visited[i]) continue;
/* Variable to store frequency
of current element */
int freq = 0;
// Second loop
for(int j = i; j < n; j++) {
if(nums[i] == nums[j]) {
freq++;
visited[j] = true;
}
}
/* Update variables if new element
having highest frequency or second
highest frequency is found */
if(freq > maxFreq) {
secMaxFreq = maxFreq;
maxFreq = freq;
secEle = maxEle;
maxEle = nums[i];
}
else if(freq == maxFreq) {
maxEle = Math.min(maxEle, nums[i]);
}
else if(freq > secMaxFreq) {
secMaxFreq = freq;
secEle = nums[i];
}
else if(freq == secMaxFreq) {
secEle = Math.min(secEle, nums[i]);
}
}
// Return the result
return secEle;
}
public static void main(String[] args) {
int[] nums = {4, 4, 5, 5, 6, 7};
/* Creating an instance of
Solution class */
Solution sol = new Solution();
/* Function call to get the second
highest occurring element in array */
int ans = sol.secondMostFrequentElement(nums);
System.out.println("The second highest occurring element in the array is: " + ans);
}
}
class Solution:
"""Function to get the second highest
occurring element in array"""
def secondMostFrequentElement(self, nums):
# Variable to store the size of array
n = len(nums)
"""Variable to store maximum frequency
and second Max frequency"""
maxFreq = 0
secMaxFreq = 0
"""Variable to store elements with most
and second most frequency"""
maxEle = -1
secEle = -1
# Visited array
visited = [False] * n
# First loop
for i in range(n):
# Skip second loop if already visited
if visited[i]:
continue
"""Variable to store frequency
of current element"""
freq = 0
# Second loop
for j in range(i, n):
if nums[i] == nums[j]:
freq += 1
visited[j] = True
"""Update variables if new element
having highest frequency or second
highest frequency is found"""
if freq > maxFreq:
secMaxFreq = maxFreq
maxFreq = freq
secEle = maxEle
maxEle = nums[i]
elif freq == maxFreq:
maxEle = min(maxEle, nums[i])
elif freq > secMaxFreq:
secMaxFreq = freq
secEle = nums[i]
elif freq == secMaxFreq:
secEle = min(secEle, nums[i])
# Return the result
return secEle
if __name__ == "__main__":
nums = [4, 4, 5, 5, 6, 7]
"""Creating an instance of
Solution class"""
sol = Solution()
"""Function call to get the second
highest occurring element in array"""
ans = sol.secondMostFrequentElement(nums)
print(f"The second highest occurring element in the array is: {ans}")
class Solution {
/* Function to get the second highest
occurring element in array */
secondMostFrequentElement(nums) {
// Variable to store the size of array
let n = nums.length;
/* Variable to store maximum frequency
and second Max frequency */
let maxFreq = 0;
let secMaxFreq = 0;
/* Variable to store elements with most
and second most frequency */
let maxEle = -1, secEle = -1;
// Visited array
let visited = new Array(n).fill(false);
// First loop
for (let i = 0; i < n; i++) {
// Skip second loop if already visited
if (visited[i]) continue;
/* Variable to store frequency
of current element */
let freq = 0;
// Second loop
for (let j = i; j < n; j++) {
if (nums[i] === nums[j]) {
freq++;
visited[j] = true;
}
}
/* Update variables if new element
having highest frequency or second
highest frequency is found */
if (freq > maxFreq) {
secMaxFreq = maxFreq;
maxFreq = freq;
secEle = maxEle;
maxEle = nums[i];
}
else if (freq === maxFreq) {
maxEle = Math.min(maxEle, nums[i]);
}
else if (freq > secMaxFreq) {
secMaxFreq = freq;
secEle = nums[i];
}
else if (freq === secMaxFreq) {
secEle = Math.min(secEle, nums[i]);
}
}
// Return the result
return secEle;
}
}
// Example usage
let nums = [4, 4, 5, 5, 6, 7];
/* Creating an instance of
Solution class */
let sol = new Solution();
/* Function call to get the second
highest occurring element in array */
let ans = sol.secondMostFrequentElement(nums);
console.log("The second highest occurring element in the array is: " + ans);
Time Complexity: O(N2) (where N is the size of the array given) – Using two nested loops.
Space Complexity: O(N) – Using a visited array of size N and a couple of variables.
An optimal approach to solve this question will be to use a Hashmap, a data structure that stores key-value pairs.
To solve this problem, follow these steps:
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
/* Function to get the second highest
occurring element in array */
int secondMostFrequentElement(vector<int> &nums) {
// Variable to store the size of array
int n = nums.size();
/* Variable to store maximum frequency
and second maximum frequency */
int maxFreq = 0, secMaxFreq = 0;
/* Variable to store element
with maximum frequency and second
highest frequency */
int maxEle = -1, secEle = -1;
// HashMap
unordered_map<int, int> mpp;
// Iterating on the array
for (int i = 0; i < n; i++) {
// Updating hashmap
mpp[nums[i]]++;
}
// Iterate on the map
for(auto it : mpp) {
int ele = it.first; // Key
int freq = it.second; // Value
/* Update variables if new element
having highest frequency or second
highest frequency is found */
if(freq > maxFreq) {
secMaxFreq = maxFreq;
maxFreq = freq;
secEle = maxEle;
maxEle = ele;
}
else if(freq == maxFreq) {
maxEle = min(maxEle, ele);
}
else if(freq > secMaxFreq) {
secMaxFreq = freq;
secEle = ele;
}
else if(freq == secMaxFreq) {
secEle = min(secEle, ele);
}
}
// Return the result
return secEle;
}
};
int main() {
vector<int> nums = {4, 4, 5, 5, 6, 7};
/* Creating an instance of
Solution class */
Solution sol;
/* Function call to get the second
highest occurring element in array */
int ans = sol.secondMostFrequentElement(nums);
cout << "The second highest occurring element in the array is: " << ans;
return 0;
}
import java.util.*;
class Solution {
/* Function to get the second highest
occurring element in array */
public int secondMostFrequentElement(int[] nums) {
// Variable to store the size of array
int n = nums.length;
/* Variable to store maximum frequency
and second maximum frequency */
int maxFreq = 0, secMaxFreq = 0;
/* Variable to store element
with maximum frequency and second
highest frequency */
int maxEle = -1, secEle = -1;
// HashMap
HashMap<Integer, Integer> mpp = new HashMap<>();
// Iterating on the array
for (int i = 0; i < n; i++) {
// Updating hashmap
mpp.put(nums[i], mpp.getOrDefault(nums[i], 0) + 1);
}
// Iterate on the map
for(Map.Entry<Integer, Integer> it : mpp.entrySet()) {
int ele = it.getKey(); // Key
int freq = it.getValue(); // Value
/* Update variables if new element
having highest frequency or second
highest frequency is found */
if(freq > maxFreq) {
secMaxFreq = maxFreq;
maxFreq = freq;
secEle = maxEle;
maxEle = ele;
}
else if(freq == maxFreq) {
maxEle = Math.min(maxEle, ele);
}
else if(freq > secMaxFreq) {
secMaxFreq = freq;
secEle = ele;
}
else if(freq == secMaxFreq) {
secEle = Math.min(secEle, ele);
}
}
// Return the result
return secEle;
}
public static void main(String[] args) {
int[] nums = {4, 4, 5, 5, 6, 7};
/* Creating an instance of
Solution class */
Solution sol = new Solution();
/* Function call to get the second
highest occurring element in array */
int ans = sol.secondMostFrequentElement(nums);
System.out.println("The second highest occurring element in the array is: " + ans);
}
}
from collections import defaultdict
class Solution:
# Function to get the second highest
# occurring element in array
def secondMostFrequentElement(self, nums):
# Variable to store the size of array
n = len(nums)
# Variable to store maximum frequency
# and second maximum frequency
maxFreq = 0
secMaxFreq = 0
# Variable to store element
# with maximum frequency and second
# highest frequency
maxEle = -1
secEle = -1
# HashMap
mpp = defaultdict(int)
# Iterating on the array
for num in nums:
# Updating hashmap
mpp[num] += 1
# Iterate on the map
for ele, freq in mpp.items():
# Update variables if new element
# having highest frequency or second
# highest frequency is found
if freq > maxFreq:
secMaxFreq = maxFreq
maxFreq = freq
secEle = maxEle
maxEle = ele
elif freq == maxFreq:
maxEle = min(maxEle, ele)
elif freq > secMaxFreq:
secMaxFreq = freq
secEle = ele
elif freq == secMaxFreq:
secEle = min(secEle, ele)
# Return the result
return secEle
# Test the function
if __name__ == "__main__":
nums = [4, 4, 5, 5, 6, 7]
# Creating an instance of
# Solution class
sol = Solution()
# Function call to get the second
# highest occurring element in array
ans = sol.secondMostFrequentElement(nums)
print(f"The second highest occurring element in the array is: {ans}")
class Solution {
/* Function to get the second highest
occurring element in array */
secondMostFrequentElement(nums) {
// Variable to store the size of array
let n = nums.length;
/* Variable to store maximum frequency
and second maximum frequency */
let maxFreq = 0, secMaxFreq = 0;
/* Variable to store element
with maximum frequency and second
highest frequency */
let maxEle = -1, secEle = -1;
// HashMap
let mpp = new Map();
// Iterating on the array
for (let i = 0; i < n; i++) {
// Updating hashmap
mpp.set(nums[i], (mpp.get(nums[i]) || 0) + 1);
}
// Iterate on the map
for (let [ele, freq] of mpp) {
/* Update variables if new element
having highest frequency or second
highest frequency is found */
if (freq > maxFreq) {
secMaxFreq = maxFreq;
maxFreq = freq;
secEle = maxEle;
maxEle = ele;
}
else if (freq == maxFreq) {
maxEle = Math.min(maxEle, ele);
}
else if (freq > secMaxFreq) {
secMaxFreq = freq;
secEle = ele;
}
else if (freq == secMaxFreq) {
secEle = Math.min(secEle, ele);
}
}
// Return the result
return secEle;
}
}
// Test the function
let nums = [4, 4, 5, 5, 6, 7];
/* Creating an instance of
Solution class */
let sol = new Solution();
/* Function call to get the second
highest occurring element in array */
let ans = sol.secondMostFrequentElement(nums);
console.log("The second highest occurring element in the array is: " + ans);
Time Complexity: O(N) (where N is the size of the array given) –
Space Complexity: O(N) – In the worst-case scenario, the HashMap will store all the elements in the array when array elements are unique.