Find the Longest Substring Having Vowels in Even Counts

Bitmask parity of vowel counts as state — first-occurrence map gives the longest range with all-zero parity.

Medium
Time O(n) Space O(32)
LeetCode
4 min read
bit-manipulation prefix-state hash-map

Problem#

Return the length of the longest substring in which each of a, e, i, o, u appears an even number of times.

Examples#

  • "eleetminicoworoep"13 (substring "leetminicowor").
  • "leetcodeisgreat"5 ("leetc").
  • "bcbcbc"6.

Constraints#

  • 1 <= s.length <= 5 * 10^5.

Approach#

Encode parity of each vowel as one bit of a 5-bit state. Walk the string maintaining the running XOR state; record the first index at which each state was seen. The longest substring ending at i with all-even parities is i - firstSeen[state].

Solution#

Find the Longest Substring Having Vowels in Even Counts
class Solution {
public:
int findTheLongestSubstring(string s) {
unordered_map<char,int> bit = {{'a',0},{'e',1},{'i',2},{'o',3},{'u',4}};
vector<int> first(32, -2);
first[0] = -1;
int state = 0, ans = 0;
for (int i = 0; i < (int)s.size(); ++i) {
auto it = bit.find(s[i]);
if (it != bit.end()) state ^= (1 << it->second);
if (first[state] == -2) first[state] = i;
else ans = max(ans, i - first[state]);
}
return ans;
}
};

Editorial#

The trick is recognizing “all even counts in a substring” = “running parity at both endpoints matches”. With only 5 vowels, there are exactly 32 possible parity states; storing the first index of each turns the problem into a single linear scan.

Complexity#

  • Time: O(n).
  • Space: O(32).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.