Leetcode 3019. Number of Changing Keys
You are given a string s
that contains only lowercase English letters. A “changing key-out” substring is one that contains a sequence of characters where each character appears the same number of times. Your task is to find the number of such substrings in the string s
.
s
?
For this example, I will assume:
s
is within reasonable limits for typical coding interviews (e.g., up to 10^5).left
and right
) to represent the current window of the substring.#include <iostream>
#include <unordered_map>
#include <string>
#include <vector>
using namespace std;
bool is_valid(const unordered_map<char, int>& freq) {
if (freq.empty()) return true;
int count = freq.begin()->second;
for (const auto& [char_, cnt] : freq) {
if (cnt != count) return false;
}
return true;
}
int countChangingKeyOutSubstrings(const string& s) {
int n = s.size();
int count = 0;
for (int start = 0; start < n; ++start) {
unordered_map<char, int> freq;
for (int end = start; end < n; ++end) {
freq[s[end]]++;
if (is_valid(freq)) {
count++;
}
}
}
return count;
}
int main() {
string s;
cout << "Enter the string: ";
cin >> s;
cout << "Number of changing key-out substrings: " << countChangingKeyOutSubstrings(s) << endl;
return 0;
}
n
times representing the start pointer.n
times for each start position.O(26)
i.e., O(1)
time since there are at most 26 lowercase English letters.Therefore, the overall time complexity is O(n^2)
. This is efficient enough given our constraints within typical coding interviews.
Edge Cases:
0
.1
.This approach ensures all substrings are correctly evaluated for the frequency property, and counts are maintained efficiently using hashing (unordered_map).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?