Python 2399.py
class Solution:
def checkDistances(self, s: str, distance: List[int]) -> bool:
done = [ False ] * 26
for i, c in enumerate(s):
value = ord(c) - ord("a")
if done[value]:
continue
done[value] = True
j = i + distance[value] + 1
if j >= len(s) or s[j] != c:
return False
return True
Difficulty
and has an acceptance rate of about 71% (90k+ submissions).
Typical patterns to solve this problem:
- Array
- Hash Table
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The checkDistances method determines whether a given string s satisfies a set of distance constraints defined by the integer list distance. For each lowercase letter that appears in s, the method checks that the second occurrence of the letter is exactly distance[letter] characters away from the first occurrence. The function returns True only when all letters meet their respective constraints; otherwise it returns False.
Key Steps
The algorithm begins by allocating a Boolean array named done with 26 entries, each initialized to False. This array tracks whether the first occurrence of each alphabet character has already been processed.
done = [ False ] * 26
Next, the method iterates over the characters of s together with their indices using enumerate. For each character c at position i, it computes the zero-based alphabet index value by subtracting the ASCII code of 'a' from the ASCII code of c.
for i, c in enumerate(s):
value = ord(c) - ord("a")
If done[value] is already True, the loop skips further processing for that character because its distance has been verified during the earlier encounter.
if done[value]:
continue
When the character is encountered for the first time, the algorithm marks it as processed.
done[value] = True
The expected position of the matching second occurrence is calculated by adding the required distance plus one (to account for the characters between the two occurrences) to the current index i. This target index is stored in j.
j = i + distance[value] + 1
A boundary check ensures that j does not exceed the length of the string. If j is out of range or the character at position j does not match c, the method immediately returns False, indicating a violation of the distance rule.
if j >= len(s) or s[j] != c:
return False
If the loop completes without triggering a failure, the method concludes that all distance constraints are satisfied and returns True.
return True
Edge Cases Handled
The implementation gracefully handles the situation where a character appears only once in the string. In such a case, the computed target index j will either fall outside the string bounds or point to a different character, causing the early False return. This prevents false positives when a required second occurrence is missing.
When the required distance for a character is zero, the algorithm expects the same character to appear in the immediate next position (j = i + 1). The boundary check still applies, ensuring that the string is long enough to contain the adjacent duplicate.
If the input string contains characters outside the 'a'-'z' range, the calculation of value would produce an index outside the 0-25 range, but the problem constraints guarantee only lowercase letters, so the code safely assumes valid input.
Performance Optimizations
The use of a fixed-size Boolean list done eliminates the need for dynamic data structures such as dictionaries or sets, providing constant-time access for marking and checking processed characters. By skipping further work for characters already verified (continue), the algorithm avoids redundant distance calculations, ensuring that each distinct letter is examined at most once.
The early exit strategy (return False as soon as a mismatch is detected) prevents unnecessary scanning of the remainder of the string once a violation is found, reducing the total number of iterations in failing cases.
Overall, the method operates with a single pass over the input string, leveraging direct index arithmetic and preallocated arrays to achieve efficient execution.
ELI5 - Simplified Explanation
Imagine there is a line of alphabet blocks where each letter needs a special friend of the same kind. This code acts like a detective checking if every letter is exactly the right distance away from its twin.
First, it creates a list of twenty-six hidden spots to keep track of which letters have already been found. It looks at the string of letters one by one from start to finish. For every letter it finds, it checks if it has seen that letter before by looking at those hidden spots. If the letter is new, the detective marks it as found.
Then, it peeks at the distance array to see how many spaces away the identical twin letter should be hiding. It jumps forward that many spots to investigate the location where the twin should live. If the spot is off the edge of the line or if the letter there is not the same twin, the detective knows something is wrong. Everything continues until all the letters have been checked to make sure they are standing the correct distance from their match.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | Java | Python | C++ | TS | |||||
| WalkCCC | Java | Python | C++ | |||||||
| leetcode.ca | Java | Python | C++ | C | Go | Rust | TS | |||
| Progiez | Java | Python | C++ | |||||||
| github | charles-wangkai | Java | ||||||||
| DimitrisJim | C | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| fsq | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| lkwq007 | Python | |||||||||
| varunu28 | Java | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C, C++, Go, Java, Python, Rust, TypeScript | |||||||||
| Progiez | C++, Java, Python | |||||||||
| charles-wangkai | Java | |||||||||
| DimitrisJim | C | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| fsq | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| lkwq007 | Python | |||||||||
| varunu28 | Java |
Videos
Similar Problems
- problem 1: Two Sum
- problem 821: Shortest Distance to a Character
Solved On The Same Day
- problem 2389: Longest Subsequence With Limited Sum
- problem 2395: Find Subarrays With Equal Sum
- problem 2400: Number of Ways to Reach a Position After Exactly k Steps
- problem 2328: Number of Increasing Paths in a Grid
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality