Given a string s
of lowercase English letters and an array of integers distance
of length 26, where distance[i]
represents the desired distance between the two occurrences of the i-th letter in the alphabet (0-indexed), return true if for every letter in s
, the distance between the two occurrences of the letter is equal to the respective value in the distance
array. Otherwise, return false.
s
and distance
will have appropriate lengths as described in the problem constraints.s
and keep track of the first occurrence of each letter with the help of a dictionary.distance
array.Here’s the code implementing the strategy:
def checkDistances(s: str, distance: list[int]) -> bool:
letter_pos = {}
for idx, char in enumerate(s):
if char in letter_pos:
actual_distance = idx - letter_pos[char] - 1
expected_distance = distance[ord(char) - ord('a')]
if actual_distance != expected_distance:
return False
else:
letter_pos[char] = idx
return True
# Example usage:
s = "abaccb"
distance = [1, 2, 0, ...] # for simplicity in this example
print(checkDistances(s, distance)) # Output should be True or False based on the distance array
s
. We scan through the string once and perform constant-time dictionary operations.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?