Check Distances Between Same Letters — LeetCode 2399 Python Solution

EasyArrayHash TableString
Problem
#2399
Pattern
Hash Map
Reading time
2 min

The 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.

Example

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
Explanation
- 'a' appears at indices 0 and 2 so it satisfies distance[0] = 1.

Python solution

Python
class Solution:
    def checkDistances(self, s: str, distance: List[int]) -> bool:
        d = defaultdict(int)
        for i, c in enumerate(map(ord, s), 1):
            j = c - ord("a")
            if d[j] and i - d[j] - 1 != distance[j]:
                return False
            d[j] = i
        return True

Complexity

MeasureComplexity
TimeO(n), where n is the length of the string s
SpaceO(|\Sigma|), where \Sigma is the character set, which in this case is the set of lowercase letters auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2399. Check Distances Between Same Letters is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2399. Check Distances Between Same Letters?
LeetCode 2399. Check Distances Between Same Letters is rated Easy on LeetCode.
What is the time complexity of LeetCode 2399. Check Distances Between Same Letters?
The Python solution on this page runs in O(n), where n is the length of the string s.
What is the space complexity of LeetCode 2399. Check Distances Between Same Letters?
The Python solution on this page uses O(|\Sigma|), where \Sigma is the character set, which in this case is the set of lowercase letters auxiliary space.
What topics does LeetCode 2399. Check Distances Between Same Letters cover?
LeetCode 2399. Check Distances Between Same Letters is tagged Array, Hash Table and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview