Leetcode 1624. Largest Substring Between Two Equal Characters
Given a string s
, return the length of the longest substring between two equal characters, exclusive of the two characters. If there is no such substring, return -1
.
Input: s = "aa"
Output: 0
Explanation: The only substring between the two ‘a’s is an empty string.
Input: s = "abca"
Output: 2
Explanation: The substring between the two ‘a’s is “bc”.
Input: s = "cbzxy"
Output: -1
Explanation: There are no two identical characters, hence no valid substring exists.
Input: s = "cabbac"
Output: 4
Explanation: The substring between the two ‘c’s is “abba”.
s
lowercase English letters?s
?s
and for each character, do the following:
-1
if no valid substring is found.#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;
int maxLengthBetweenEqualCharacters(string s) {
unordered_map<char, int> firstIndex;
int maxLength = -1;
for (int i = 0; i < s.length(); i++) {
if (firstIndex.find(s[i]) != firstIndex.end()) {
int currentLength = i - firstIndex[s[i]] - 1;
maxLength = max(maxLength, currentLength);
} else {
firstIndex[s[i]] = i;
}
}
return maxLength;
}
// Sample usage
int main() {
string s = "cabbac";
cout << maxLengthBetweenEqualCharacters(s) << endl; // Output: 4
return 0;
}
The time complexity for this solution is O(n) where n
is the length of the string s
. This is because we only traverse the string once, and each operation inside the loop (hash map operations) can be done in constant time on average.
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?