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
ifs
_is awell-spaced string, otherwise return _false
.
Examples
Example 1
|
|
Example 2
|
|
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
Solution
Method 1 – Index Tracking and Distance Comparison
Intuition: Since each letter appears exactly twice, we can record the index of the first occurrence for each letter, then when we see the second occurrence, check if the distance matches the required value.
Approach:
- Create an array of size 26 to store the first index of each letter (initialized to -1).
- Iterate through the string:
- If the letter is seen for the first time, record its index.
- If seen for the second time, check if the difference between indices minus 1 equals the required distance.
- If not, return false.
- If all checks pass, return true.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the length of s. - 🧺 Space complexity:
O(1)