Given a sequence of strings, the task is to find out the second most repeated (or frequent) string in the given sequence.(Considering no two words are the second most repeated, there will be always a single word).
Examples:
Input : {"aaa", "bbb", "ccc", "bbb",
"aaa", "aaa"}
Output : bbb
Input : {"geeks", "for", "geeks", "for",
"geeks", "aaa"}
Output : for
Asked in : Amazon
BRUTE FORCE METHOD:
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
string secFrequent(string arr[], int N)
{
unordered_map<string, int > um;
for ( int i = 0; i < N; i++) {
if (um.find(arr[i]) != um.end()) {
um[arr[i]]++;
}
else {
um[arr[i]] = 1;
}
}
int max = INT_MIN;
vector< int > a;
for ( auto j : um) {
if (j.second > max) {
max = j.second;
}
}
for ( auto j : um) {
if (j.second != max) {
a.push_back(j.second);
}
}
sort(a.begin(), a.end());
for ( auto x : um) {
if (x.second == a[a.size() - 1]) {
return x.first;
}
}
return "-1" ;
}
int main()
{
string arr[]
= { "ccc" , "aaa" , "ccc" , "ddd" , "aaa" , "aaa" };
int N = sizeof (arr) / sizeof (arr[0]);
string ans = secFrequent(arr, N);
cout << ans << endl;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
public static String secFrequent(String arr[], int N)
{
HashMap<String, Integer> hm = new HashMap<>();
for ( int i = 0 ; i < N; i++) {
if (hm.containsKey(arr[i])) {
hm.put(arr[i], hm.get(arr[i]) + 1 );
}
else {
hm.put(arr[i], 1 );
}
}
int max = Collections.max(hm.values());
ArrayList<Integer> a = new ArrayList<>();
for (Map.Entry<String, Integer> j : hm.entrySet()) {
if (j.getValue() != max) {
a.add(j.getValue());
}
}
Collections.sort(a);
for (Map.Entry<String, Integer> x : hm.entrySet()) {
if (x.getValue() == a.get(a.size() - 1 )) {
return x.getKey();
}
}
return "-1" ;
}
public static void main(String[] args)
{
String arr[] = { "ccc" , "aaa" , "ccc" ,
"ddd" , "aaa" , "aaa" };
int N = arr.length;
String ans = secFrequent(arr, N);
System.out.println(ans);
}
}
|
Python3
from collections import Counter
def secFrequent(arr):
freq = Counter(arr)
max_freq = max (freq.values())
a = [x for x in freq.values() if x ! = max_freq]
a.sort()
for x in freq:
if freq[x] = = a[ - 1 ]:
return x
return "-1"
arr = [ "ccc" , "aaa" , "ccc" , "ddd" , "aaa" , "aaa" ]
ans = secFrequent(arr)
print (ans)
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class GFG
{
static string SecFrequent( string [] arr)
{
Dictionary< string , int > um = new Dictionary< string , int >();
for ( int i = 0; i < arr.Length; i++)
{
if (um.ContainsKey(arr[i]))
{
um[arr[i]]++;
}
else
{
um[arr[i]] = 1;
}
}
int max = int .MinValue;
List< int > a = new List< int >();
foreach ( var j in um)
{
if (j.Value > max)
{
max = j.Value;
}
}
foreach ( var j in um)
{
if (j.Value != max)
{
a.Add(j.Value);
}
}
a.Sort();
foreach ( var x in um)
{
if (x.Value == a[a.Count - 1])
{
return x.Key;
}
}
return "-1" ;
}
static void Main( string [] args)
{
string [] arr = { "ccc" , "aaa" , "ccc" , "ddd" , "aaa" , "aaa" };
string ans = SecFrequent(arr);
Console.WriteLine(ans);
}
}
|
Javascript
function secFrequent(arr) {
let um = new Map();
for (let i = 0; i < arr.length; i++) {
if (um.has(arr[i])) {
um.set(arr[i], um.get(arr[i]) + 1);
} else {
um.set(arr[i], 1);
}
}
let max = Number.MIN_SAFE_INTEGER;
let a = [];
for (let [key, value] of um) {
if (value > max) {
max = value;
}
}
for (let [key, value] of um) {
if (value !== max) {
a.push(value);
}
}
a.sort((a, b) => a - b);
for (let [key, value] of um) {
if (value === a[a.length - 1]) {
return key;
}
}
return "-1" ;
}
let arr = [ "ccc" , "aaa" , "ccc" , "ddd" , "aaa" , "aaa" ];
let ans = secFrequent(arr);
console.log(ans);
|
- Time Complexity: O(NLog(N)).
- Space Complexity: O(N).
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
string secMostRepeated(vector<string> seq)
{
unordered_map<string, int > occ;
for ( int i = 0; i < seq.size(); i++)
occ[seq[i]]++;
int first_max = INT_MIN, sec_max = INT_MIN;
for ( auto it = occ.begin(); it != occ.end(); it++) {
if (it->second > first_max) {
sec_max = first_max;
first_max = it->second;
}
else if (it->second > sec_max &&
it->second != first_max)
sec_max = it->second;
}
for ( auto it = occ.begin(); it != occ.end(); it++)
if (it->second == sec_max)
return it->first;
}
int main()
{
vector<string> seq = { "ccc" , "aaa" , "ccc" ,
"ddd" , "aaa" , "aaa" };
cout << secMostRepeated(seq);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static String secMostRepeated(Vector<String> seq)
{
HashMap<String, Integer> occ = new HashMap<String,Integer>(seq.size()){
@Override
public Integer get(Object key) {
return containsKey(key) ? super .get(key) : 0 ;
}
};
for ( int i = 0 ; i < seq.size(); i++)
occ.put(seq.get(i), occ.get(seq.get(i))+ 1 );
int first_max = Integer.MIN_VALUE, sec_max = Integer.MIN_VALUE;
Iterator<Map.Entry<String, Integer>> itr = occ.entrySet().iterator();
while (itr.hasNext())
{
Map.Entry<String, Integer> entry = itr.next();
int v = entry.getValue();
if ( v > first_max) {
sec_max = first_max;
first_max = v;
}
else if (v > sec_max &&
v != first_max)
sec_max = v;
}
itr = occ.entrySet().iterator();
while (itr.hasNext())
{
Map.Entry<String, Integer> entry = itr.next();
int v = entry.getValue();
if (v == sec_max)
return entry.getKey();
}
return null ;
}
public static void main(String[] args)
{
String arr[] = { "ccc" , "aaa" , "ccc" ,
"ddd" , "aaa" , "aaa" };
List<String> seq = Arrays.asList(arr);
System.out.println(secMostRepeated( new Vector<>(seq)));
}
}
|
Python3
def secMostRepeated(seq):
occ = {}
for i in range ( len (seq)):
occ[seq[i]] = occ.get(seq[i], 0 ) + 1
first_max = - 10 * * 8
sec_max = - 10 * * 8
for it in occ:
if (occ[it] > first_max):
sec_max = first_max
first_max = occ[it]
elif (occ[it] > sec_max and
occ[it] ! = first_max):
sec_max = occ[it]
for it in occ:
if (occ[it] = = sec_max):
return it
if __name__ = = '__main__' :
seq = [ "ccc" , "aaa" , "ccc" ,
"ddd" , "aaa" , "aaa" ]
print (secMostRepeated(seq))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static String secMostRepeated(List<String> seq)
{
Dictionary<String, int > occ =
new Dictionary<String, int >();
for ( int i = 0; i < seq.Count; i++)
if (occ.ContainsKey(seq[i]))
occ[seq[i]] = occ[seq[i]] + 1;
else
occ.Add(seq[i], 1);
int first_max = int .MinValue,
sec_max = int .MinValue;
foreach (KeyValuePair<String, int > entry in occ)
{
int v = entry.Value;
if ( v > first_max)
{
sec_max = first_max;
first_max = v;
}
else if (v > sec_max &&
v != first_max)
sec_max = v;
}
foreach (KeyValuePair<String, int > entry in occ)
{
int v = entry.Value;
if (v == sec_max)
return entry.Key;
}
return null ;
}
public static void Main(String[] args)
{
String []arr = { "ccc" , "aaa" , "ccc" ,
"ddd" , "aaa" , "aaa" };
List<String> seq = new List<String>(arr);
Console.WriteLine(secMostRepeated(seq));
}
}
|
Javascript
<script>
function secMostRepeated(seq)
{
let occ = new Map();
for (let i = 0; i < seq.length; i++)
{
if (occ.has(seq[i])){
occ.set(seq[i], occ.get(seq[i])+1);
}
else occ.set(seq[i], 1);
}
let first_max = Number.MIN_VALUE, sec_max = Number.MIN_VALUE;
for (let [key,value] of occ) {
if (value > first_max) {
sec_max = first_max;
first_max = value;
}
else if (value > sec_max && value != first_max)
sec_max = value;
}
for (let [key,value] of occ)
if (value == sec_max)
return key;
}
let seq = [ "ccc" , "aaa" , "ccc" , "ddd" , "aaa" , "aaa" ];
document.write(secMostRepeated(seq));
</script>
|
Time Complexity: O(N), where N represents the size of the given vector.
Auxiliary Space: O(N), where N represents the size of the given vector.
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
15 Sep, 2023
Like Article
Save Article