Sponsored
Sponsored
This approach uses a hash map to store the first and last occurrence of each character as you traverse the string. For each character, calculate the distance between its occurrences and keep track of the maximum distance found. This efficiently provides the length of the longest substring between two identical characters.
Time Complexity: O(n) where n is the length of the string.
Space Complexity: O(1) since the hash map size is constant (fixed at 256 for all possible lowercase characters).
1var maxLengthBetweenEqualCharacters = function(s) {
2 let firstOccurrence = {};
3 let maxLen = -1;
4 for (let i = 0; i < s.length; i++) {
5 if (!(s[i] in firstOccurrence)) {
6 firstOccurrence[s[i]] = i;
7 } else {
8 maxLen = Math.max(maxLen, i - firstOccurrence[s[i]] - 1);
9 }
10 }
11 return maxLen;
12};
13
14console.log(maxLengthBetweenEqualCharacters('abca'));
This JavaScript solution uses an object as a hashmap to store the indices of the first occurrence of each character, facilitating a calculation of the desired maximum length for the substring between identical characters.
This approach involves two pass-throughs of the string. The first pass records each character's first occurrence, while the second calculates potential maximum lengths using each character's last occurrence.
Time Complexity: O(n).
Space Complexity: O(1).
1#include <unordered_map>
using namespace std;
int maxLengthBetweenEqualCharacters(string s) {
unordered_map<char, int> firstOccurrence;
unordered_map<char, int> lastOccurrence;
int maxLen = -1;
for (int i = 0; i < s.length(); i++) {
if (firstOccurrence.find(s[i]) == firstOccurrence.end()) {
firstOccurrence[s[i]] = i;
}
lastOccurrence[s[i]] = i;
}
for (auto pair : firstOccurrence) {
maxLen = max(maxLen, lastOccurrence[pair.first] - pair.second - 1);
}
return maxLen;
}
int main() {
string s = "abca";
int result = maxLengthBetweenEqualCharacters(s);
cout << result << endl;
return 0;
}
C++ implementation makes use of two unordered maps for recording first and last occurrences, facilitating the calculation of the longest substring length between identical characters.