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).
1def maxLengthBetweenEqualCharacters(s: str) -> int:
2 first_occurrence = {}
3 max_len = -1
4 for i, char in enumerate(s):
5 if char not in first_occurrence:
6 first_occurrence[char] = i
7 else:
8 max_len = max(max_len, i - first_occurrence[char] - 1)
9 return max_len
10
11s = "abca"
12result = maxLengthBetweenEqualCharacters(s)
13print(result)
This Python function also employs a dictionary to store character first occurrences. It computes the longest substring by the difference of current and first indices for repeated characters, minus one.
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).
1using System.Collections.Generic;
public class Solution {
public int MaxLengthBetweenEqualCharacters(string s) {
Dictionary<char, int> firstOccurrence = new Dictionary<char, int>();
Dictionary<char, int> lastOccurrence = new Dictionary<char, int>();
int maxLen = -1;
for (int i = 0; i < s.Length; i++) {
if (!firstOccurrence.ContainsKey(s[i])) {
firstOccurrence[s[i]] = i;
}
lastOccurrence[s[i]] = i;
}
foreach (var pair in firstOccurrence) {
maxLen = Math.Max(maxLen, lastOccurrence[pair.Key] - pair.Value - 1);
}
return maxLen;
}
public static void Main(string[] args) {
Solution sol = new Solution();
Console.WriteLine(sol.MaxLengthBetweenEqualCharacters("abca"));
}
}
This C# code leverages two-pass logic with dictionaries for keeping track of where characters first and last appear, which helps derive substring lengths aptly.