3438. Find Valid Pair of Adjacent Digits in String
Description
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
sexactly 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.
Example 1:
Input: s = "2523533"
Output: "23"
Explanation:
Digit '2' appears 2 times and digit '3' appears 3 times. Each digit in the pair "23" appears in s exactly as many times as its numeric value. Hence, the output is "23".
Example 2:
Input: s = "221"
Output: "21"
Explanation:
Digit '2' appears 2 times and digit '1' appears 1 time. Hence, the output is "21".
Example 3:
Input: s = "22"
Output: ""
Explanation:
There are no valid adjacent pairs.
Constraints:
2 <= s.length <= 100sonly consists of digits from'1'to'9'.
Solutions
Solution 1: Counting
Thinking
A valid pair uses two distinct digits whose global frequencies equal the digits themselves. \(|s|\le 100\), so a count plus one adjacent scan is enough.
Counting while scanning would miss occurrences to the right of the pair.
We fill a length-\(10\) frequency array first, then return the leftmost adjacent pair with \(x\neq y\), \(cnt[x]=x\) and \(cnt[y]=y\).
We can use an array \(\textit{cnt}\) of length \(10\) to record the occurrences of each digit in the string \(\textit{s}\).
Then, we traverse the adjacent digit pairs in the string \(\textit{s}\). If the two digits are not equal and the occurrences of these two digits are equal to the digits themselves, we have found a valid pair of adjacent digits and return it.
After traversing, if no valid pair of adjacent digits is found, we return an empty string.
The time complexity is \(O(n)\), where \(n\) is the length of the string \(\textit{s}\). The space complexity is \(O(|\Sigma|)\), where \(\Sigma\) is the character set of the string \(\textit{s}\). In this problem, \(\Sigma = \{1, 2, \ldots, 9\}\).
1 2 3 4 5 6 7 8 9 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |