Find the second most repeated word in string

1 min read

https://practice.geeksforgeeks.org/problems/second-most-repeated-string-in-a-sequence/0

class Solution {
public:
  string secFrequent(string arr[], int n) {
    map<string, int> mp;

    for (int i = 0; i < n; i++) {
      mp[arr[i]]++;
    }

    int maxFreq = -1, notMaxFreq = -1;
    string ans = "";

    for (auto it : mp) {
      if (it.second > maxFreq) {
        notMaxFreq = maxFreq;
        maxFreq = it.second;
      } else if (it.second > notMaxFreq && it.second != maxFreq) {
        notMaxFreq = it.second;
      }
    }

    for (auto it : mp) {
      if (it.second == notMaxFreq) {
        return it.first;
      }
    }
  }
};
Number of flips to make binary string alternate
Minimum number of swaps for bracket balancing