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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code