#2399

Check Distances Between Same Letters

Easy
ArrayHash TableStringHash MapArray
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(1)

We can optimize by storing the first occurrence of each letter in a single pass through the string, then check the distances in a second pass. This reduces unnecessary repeated searches.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create an array to store the first occurrence index of each letter.
  2. 2Step 2: Iterate through the string and fill this array with the indices of the first occurrences.
  3. 3Step 3: For each letter, calculate the distance using the stored indices and compare it to the distance array.
solution.py10 lines
1def checkDistances(s, distance):
2    first_occurrence = [-1] * 26
3    for i, char in enumerate(s):
4        index = ord(char) - ord('a')
5        if first_occurrence[index] == -1:
6            first_occurrence[index] = i
7        else:
8            if i - first_occurrence[index] - 1 != distance[index]:
9                return False
10    return True

Complexity note: The time complexity is O(n) because we only iterate through the string twice, and the space complexity is O(1) since we use a fixed-size array of size 26.

  • 1Each letter appears exactly twice, which simplifies the problem.
  • 2The distance between two occurrences can be calculated directly using their indices.

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