#1624

Largest Substring Between Two Equal Characters

Easy
Hash TableStringHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a HashMap to store the first occurrence of each character. This allows us to find the maximum distance between the first and last occurrence of each character in a single pass, making it much more efficient.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a HashMap to store the first index of each character.
  2. 2Step 2: Iterate through the string, and for each character, check if it is already in the HashMap.
  3. 3Step 3: If it is, calculate the distance from its first occurrence to the current index and update max_length if this distance is greater.
  4. 4Step 4: If it is not in the HashMap, add it with its index.
solution.py9 lines
1def maxLengthBetweenEqualCharacters(s):
2    index_map = {}
3    max_length = -1
4    for i, char in enumerate(s):
5        if char in index_map:
6            max_length = max(max_length, i - index_map[char] - 1)
7        else:
8            index_map[char] = i
9    return max_length

Complexity note: The time complexity is O(n) because we traverse the string once. The space complexity is O(n) due to the HashMap storing the indices of characters.

  • 1Using a HashMap allows us to track indices efficiently.
  • 2The longest substring can be found by calculating distances between first and last occurrences.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.