VOOZH about

URL: https://www.geeksforgeeks.org/dsa/second-repeated-word-sequence/

⇱ Second most repeated word in a sequence - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Second most repeated word in a sequence

Last Updated : 26 Mar, 2025

Given a sequence of strings, the task is to find out the second most repeated (or frequent) string in the given sequence. You may assume that 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
Explanation: "bbb" is the second most repeated word and is repeated 2 times after "aaa" which is repeated 3 times.
Input: ["geeks", "for", "geeks", "for", "geeks", "aaa"]
Output: for
Explanation: "for" is the second most repeated word and is repeated 2 times after "geeks" which is repeated 3 times.

[Naive Approach] Using Nested Loops – O(n^2*k) Time and O(1) Space

We use nested loops to compare each word with the rest of the words to count its occurrences. Then, we find the second most repeated word by keeping track of the highest and second-highest counts.


Output
bbb

 Time Complexity will be O(n2k) where n is the size of array and k is the average word length.

[Expected Approach] Using Hashing – O(n*k) Time and O(n) Space

  • Counting Words: We use a map (or dictionary) to store the frequency of each word.
  • Track Most and Second Most Frequent Words: We iterate over the map to find the word with the highest count and the second highest count.
  • Return Second Most Frequent Word: After finding the counts, the second most frequent word is returned.

Output
bbb

 Time Complexity will be O(n*k) where n is the size of array and k is the average word length.

Comment
Article Tags:
Article Tags: