[LeetCode] Find Valid Pair of Adjacent Digits in String

3438. Find Valid Pair of Adjacent Digits in String

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package main

func findValidPair(s string) string {
freq := make([]int, 10)

for _, ch := range s {
freq[ch-'0']++
}

for i := 0; i < len(s)-1; i++ {
if freq[s[i]-'0'] == int(s[i]-'0') && freq[s[i+1]-'0'] == int(s[i+1]-'0') && s[i] != s[i+1] {
return string([]byte{s[i], s[i+1]})
}
}

return ""
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/02/02/PS/LeetCode/find-valid-pair-of-adjacent-digits-in-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.