File: check-distances-between-same-letters/solution.py

Date: 2026-06-06

Time: 15:34

check-distances-between-same-letters/solution.py

Purpose

This file solves LeetCode 2399: Check Distances Between Same Letters. It owns the single responsibility of validating whether a string is "well-spaced" — meaning that for every letter appearing exactly twice, the number of characters between its two occurrences matches the value specified in a distance array.

Key Components

wellspacedstring(s, distance) -> bool — the sole public function. It takes a string s (where each letter appears exactly twice) and a length-26 distance array (one entry per lowercase letter, indexed a=0 through z=25). Returns True if every letter pair satisfies its required spacing.

Patterns

Single-pass with early exit. The function uses a dictionary first_seen to record the index of each letter's first occurrence. On the second occurrence, it immediately checks the distance constraint and short-circuits with False on the first violation. This avoids scanning the full string when a mismatch appears early.

Index arithmetic for distance. The distance between two positions i and j (where j > i) is defined as i - first_seen[c] - 1 — the count of characters *strictly between* the two occurrences, not inclusive. This matches the LeetCode problem's definition.

ord() mapping for letter-to-index. ord(c) - ord("a") converts a lowercase letter to its 0-based index into the distance array. This is the standard idiom for this kind of problem.

Dependencies

Imports: None — pure Python, no standard library or third-party imports.

Imported by: check-distances-between-same-letters/test_solution.py (the "Imported By" list in the prompt appears to be a test-runner artifact — hundreds of test files reference it, but that's likely because a shared test harness imports all solution modules, not because those other problems depend on this function).

Flow

1. Initialize empty dict first_seen.

2. Iterate over s with enumerate, yielding (index, character) pairs.

3. If the character was seen before (exists in first_seen):

4. If the character hasn't been seen, record its index.

5. If the loop completes without returning False, return True.

Invariants

Error Handling

None. The function trusts its inputs match the problem constraints. No exceptions are raised or caught. Invalid inputs (uppercase letters, missing distance entries, letters appearing more or fewer than twice) would produce silent wrong answers or IndexError, not descriptive failures. This is typical for competitive programming solutions.

Topics to Explore

Beliefs