![]() |
VOOZH | about |
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.
Table of Content
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.
bbb
Time Complexity will be O(n2k) where n is the size of array and k is the average word length.
- 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.
bbb
Time Complexity will be O(n*k) where n is the size of array and k is the average word length.