Find Valid Pair of Adjacent Digits in String - Problem
๐ข Find Valid Pair of Adjacent Digits in String
You're given a string s containing only digits (0-9). Your task is to find the first valid pair of adjacent digits when scanning from left to right.
A valid pair must satisfy these conditions:
- ๐ Adjacent: The two digits must be next to each other in the string
- ๐ซ Different: The first digit โ second digit
- ๐ Count Match: Each digit appears in the entire string exactly as many times as its numeric value
Example: In string "1122", the pair "12" is valid because:
- 1 and 2 are adjacent and different
- Digit '1' appears 2 times, but its value is 1 โ
- Digit '2' appears 2 times, and its value is 2 โ
Return the first valid pair found, or an empty string if none exists.
Input & Output
example_1.py โ Basic Valid Pair
$
Input:
s = "1221"
โบ
Output:
"12"
๐ก Note:
Digits '1' appears 2 times (but should appear 1 time), '2' appears 2 times (should appear 2 times). The pair "12" at positions 0-1 has '1' with wrong count, so invalid. The pair "22" at positions 1-2 is skipped (same digits). The pair "21" at positions 2-3 is also invalid. Actually, no valid pair exists, so output should be empty string.
example_2.py โ Multiple Valid Pairs
$
Input:
s = "321"
โบ
Output:
"32"
๐ก Note:
Digit '3' appears 1 time (should appear 3 times - invalid), '2' appears 1 time (should appear 2 times - invalid), '1' appears 1 time (should appear 1 time - valid). Only '1' has correct count. No valid pairs exist.
example_3.py โ No Valid Pairs
$
Input:
s = "1111"
โบ
Output:
""
๐ก Note:
All digits are the same, so no adjacent pairs of different digits exist. Return empty string.
Constraints
- 1 โค s.length โค 103
- s consists only of digits (0-9)
- Adjacent means consecutive positions in the string
- Count validation: digit d must appear exactly d times in the entire string
Visualization
Tap to expand
Understanding the Visualization
1
Count All Performers
Walk through the circus lineup once and count how many times each numbered performer appears
2
Create Performer Registry
Build a registry (hash table) with each performer's actual appearance count
3
Validate Adjacent Pairs
Check each adjacent pair of different performers against the registry
4
Quick Registry Lookup
Use the registry for instant validation - no need to recount performers
5
First Valid Pair Wins
Return the first pair where both performers have correct appearance counts
Key Takeaway
๐ฏ Key Insight: By building a frequency map first, we transform expensive O(n) counting operations into O(1) hash table lookups, achieving optimal O(n) time complexity with clean, maintainable code.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code