Check Distances Between Same Letters - Problem

You are given a 0-indexed string s consisting of only lowercase English letters, where each letter in s appears exactly twice. You are also given a 0-indexed integer array distance of length 26.

Each letter in the alphabet is numbered from 0 to 25 (i.e. 'a' → 0, 'b' → 1, 'c' → 2, ..., 'z' → 25).

In a well-spaced string, the number of letters between the two occurrences of the ith letter is distance[i]. If the ith letter does not appear in s, then distance[i] can be ignored.

Return true if s is a well-spaced string, otherwise return false.

Input & Output

Example 1 — Basic Valid Case
$ Input: s = "abaccb", distance = [1,3,0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Output: true
💡 Note: Character 'a' appears at positions 0,2 with 1 character between (distance[0]=1 ✓). Character 'b' appears at positions 1,5 with 3 characters between (distance[1]=3 ✓). Character 'c' appears at positions 3,4 with 0 characters between (distance[2]=0 ✓).
Example 2 — Invalid Distance
$ Input: s = "aa", distance = [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Output: false
💡 Note: Character 'a' appears at positions 0,1 with 0 characters between, but distance[0]=1 requires 1 character between them.
Example 3 — Perfect Adjacent Match
$ Input: s = "aa", distance = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Output: true
💡 Note: Character 'a' appears at positions 0,1 with 0 characters between, matching distance[0]=0 exactly.

Constraints

  • 2 ≤ s.length ≤ 52
  • s consists only of lowercase English letters
  • Each letter appears in s exactly twice
  • distance.length == 26
  • 0 ≤ distance[i] ≤ 50

Visualization

Tap to expand
Check Distances Between Same LettersInput String: "abaccb"abaccbDistance Requirements:distance[0] = 1 (for 'a')distance[1] = 3 (for 'b')distance[2] = 0 (for 'c')distance[3-25] = don\'t careValidation Process✓ 'a': positions 0,2 → distance = 1✓ 'b': positions 1,5 → distance = 3✓ 'c': positions 3,4 → distance = 0Result: true
Understanding the Visualization
1
Input
String with duplicate characters and distance requirements
2
Process
Calculate actual distances between character pairs
3
Output
Return true if all distances match requirements
Key Takeaway
🎯 Key Insight: Use hash map to track first occurrences and validate distances immediately on second occurrence
Asked in
Google 12 Meta 8 Microsoft 6
12.5K Views
Medium Frequency
~15 min Avg. Time
445 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen