# 2399. Check Distances Between Same Letters

• Time: $O(n)$
• Space: $O(26) = O(1)$
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 class Solution { public: bool checkDistances(string s, vector& distance) { vector firstSeenIndex(26, -1); for (int i = 0; i < s.length(); ++i) { const int j = s[i] - 'a'; int& prevIndex = firstSeenIndex[j]; if (prevIndex != -1 && i - prevIndex - 1 != distance[j]) return false; prevIndex = i; } return true; } }; 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 class Solution { public boolean checkDistances(String s, int[] distance) { int[] firstSeenIndex = new int[26]; Arrays.fill(firstSeenIndex, -1); for (int i = 0; i < s.length(); ++i) { final int j = s.charAt(i) - 'a'; final int prevIndex = firstSeenIndex[j]; if (prevIndex != -1 && i - prevIndex - 1 != distance[j]) return false; firstSeenIndex[j] = i; } return true; } } 
  1 2 3 4 5 6 7 8 9 10 11 12 class Solution: def checkDistances(self, s: str, distance: List[int]) -> bool: firstSeenIndex = [-1] * 26 for i, c in enumerate(s): j = ord(c) - ord('a') prevIndex = firstSeenIndex[j] if prevIndex != -1 and i - prevIndex - 1 != distance[j]: return False firstSeenIndex[j] = i return True