Skip to main content
Back to problems
#2399
Easy Algorithms

Check distances between same letters

Array Hash Table String
71.4% acceptance
Feb 25, 2026
522
71
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 if s is a well-spaced string, otherwise return false.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn check_distances(s: String, distance: Vec<i32>) -> bool {
    let bytes = s.as_bytes();
    let mut first = [-1i32; 26];
    for (i, &b) in bytes.iter().enumerate() {
      let c = (b - b'a') as usize;
      if first[c] == -1 { first[c] = i as i32; }
      else if i as i32 - first[c] - 1 != distance[c] { return false; }
    }
    true
  }
}