GeeksforGeeks App
Open App
Browser
Continue

# Second most repeated word in a sequence

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```

BRUTE FORCE METHOD:

Implementation:

## C++

 `#include ``using` `namespace` `std;` `string secFrequent(string arr[], ``int` `N)``{``    ``unordered_map um;``    ``// Counting frequency of each element``    ``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;``    ``// Finding second maximum frequency``    ``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());``    ``// Returning second most frequent element``    ``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

 `// Java program to find out the second``// most repeated word` `import` `java.io.*;``import` `java.util.*;` `class` `GFG {``    ``public` `static` `String secFrequent(String arr[], ``int` `N)``    ``{``        ``// your code here``        ``HashMap 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 a = ``new` `ArrayList<>();``        ``for` `(Map.Entry j : hm.entrySet()) {``            ``if` `(j.getValue() != max) {``                ``a.add(j.getValue());``            ``}``        ``}``        ``Collections.sort(a);``        ``for` `(Map.Entry 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);``    ``}``}``//This code is contributed by Raunak Singh`

## Python3

 `from` `collections ``import` `Counter` `def` `secFrequent(arr):``    ``# Counting frequency of each element``    ``freq ``=` `Counter(arr)` `    ``max_freq ``=` `max``(freq.values())``    ``a ``=` `[x ``for` `x ``in` `freq.values() ``if` `x !``=` `max_freq]``    ``a.sort()` `    ``# Returning second most frequent element``    ``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)`

Output

`ccc`
• Time Complexity: O(NLog(N)).
• Space Complexity: O(N).

Implementation:

## C++

 `// C++ program to find out the second``// most repeated word``#include ``using` `namespace` `std;` `// Function to find the word``string secMostRepeated(vector seq)``{` `    ``// Store all the words with its occurrence``    ``unordered_map occ;``    ``for` `(``int` `i = 0; i < seq.size(); i++)``        ``occ[seq[i]]++;` `    ``// find the second largest occurrence``    ``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;``    ``}` `    ``// Return string with occurrence equals``    ``// to sec_max``    ``for` `(``auto` `it = occ.begin(); it != occ.end(); it++)``        ``if` `(it->second == sec_max)``            ``return` `it->first;``}` `// Driver program``int` `main()``{``    ``vector seq = { ``"ccc"``, ``"aaa"``, ``"ccc"``,``                          ``"ddd"``, ``"aaa"``, ``"aaa"` `};``    ``cout << secMostRepeated(seq);``    ``return` `0;``}`

## Java

 `// Java program to find out the second``// most repeated word` `import` `java.util.*;` `class` `GFG``{``    ``// Method to find the word``    ``static` `String secMostRepeated(Vector seq)``    ``{``        ``// Store all the words with its occurrence``        ``HashMap occ = ``new` `HashMap(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``);``     ` `        ``// find the second largest occurrence``       ``int` `first_max = Integer.MIN_VALUE, sec_max = Integer.MIN_VALUE;``        ` `       ``Iterator> itr = occ.entrySet().iterator();``       ``while` `(itr.hasNext())``       ``{``           ``Map.Entry 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;``       ``}``       ` `       ``// Return string with occurrence equals``        ``// to sec_max``       ``itr = occ.entrySet().iterator();``       ``while` `(itr.hasNext())``       ``{``           ``Map.Entry entry = itr.next();``           ``int` `v = entry.getValue();``           ``if` `(v == sec_max)``                ``return` `entry.getKey();``       ``}``       ` `       ``return` `null``;``    ``}``    ` `    ``// Driver method``    ``public` `static` `void` `main(String[] args)``    ``{``        ``String arr[] = { ``"ccc"``, ``"aaa"``, ``"ccc"``,``                         ``"ddd"``, ``"aaa"``, ``"aaa"` `};``        ``List seq =  Arrays.asList(arr);``        ` `        ``System.out.println(secMostRepeated(``new` `Vector<>(seq)));``    ``}   ``}``// This program is contributed by Gaurav Miglani`

## Python3

 `# Python3 program to find out the second``# most repeated word` `# Function to find the word``def` `secMostRepeated(seq):``    ` `    ``# Store all the words with its occurrence``    ``occ ``=` `{}``    ``for` `i ``in` `range``(``len``(seq)):``        ``occ[seq[i]] ``=` `occ.get(seq[i], ``0``) ``+` `1` `    ``# Find the second largest occurrence``    ``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]` `    ``# Return with occurrence equals``    ``# to sec_max``    ``for` `it ``in` `occ:``        ``if` `(occ[it] ``=``=` `sec_max):``            ``return` `it` `# Driver code``if` `__name__ ``=``=` `'__main__'``:``    ` `    ``seq ``=` `[ ``"ccc"``, ``"aaa"``, ``"ccc"``,``            ``"ddd"``, ``"aaa"``, ``"aaa"` `]``    ``print``(secMostRepeated(seq))` `# This code is contributed by mohit kumar 29`

## Javascript

 ``

## C#

 `// C# program to find out the second``// most repeated word``using` `System;``using` `System.Collections.Generic;` `class` `GFG``{``    ``// Method to find the word``    ``static` `String secMostRepeated(List seq)``    ``{``        ``// Store all the words with its occurrence``        ``Dictionary occ =``        ``new` `Dictionary();``                ` `        ``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);``    ` `        ``// find the second largest occurrence``        ``int` `first_max = ``int``.MinValue,``            ``sec_max = ``int``.MinValue;``        ` `        ``foreach``(KeyValuePair 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;``        ``}``        ` `        ``// Return string with occurrence equals``        ``// to sec_max``        ``foreach``(KeyValuePair entry ``in` `occ)``        ``{``            ``int` `v = entry.Value;``            ``if` `(v == sec_max)``                ``return` `entry.Key;``        ``}``            ` `        ``return` `null``;``    ``}``    ` `    ``// Driver method``    ``public` `static` `void` `Main(String[] args)``    ``{``        ``String []arr = { ``"ccc"``, ``"aaa"``, ``"ccc"``,``                        ``"ddd"``, ``"aaa"``, ``"aaa"` `};``        ``List seq = ``new` `List(arr);``        ` `        ``Console.WriteLine(secMostRepeated(seq));``    ``}``}` `// This code is contributed by Rajput-Ji`

Output

`ccc`

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.

This article is contributed by Sahil Chhabra. 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.

My Personal Notes arrow_drop_up