Skip to main content
Back to problems
#3438
Easy Algorithms

Find valid pair of adjacent digits in string

Hash Table String Counting
60.6% acceptance
Feb 25, 2026
77
9
You are given a string s consisting only of digits. A valid pair is defined as two adjacent digits in s such that: The first digit is not equal to the second. Each digit in the pair appears in s exactly as many times as its numeric value. Return the first valid pair found in the string s when traversing from left to right. If no valid pair exists, return an empty string.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn find_valid_pair(s: String) -> String {
    let bytes = s.as_bytes();
    let n = bytes.len();
    let mut freq = [0usize; 10];
    for &b in bytes { freq[(b - b'0') as usize] += 1; }
    for i in 0..n-1 {
      let a = (bytes[i] - b'0') as usize;
      let b = (bytes[i+1] - b'0') as usize;
      if a != b && freq[a] == a && freq[b] == b {
        return format!("{}{}", a, b);
      }
    }
    String::new()
  }
}