Find Valid Pair of Adjacent Digits in String - Problem

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 digit
  • 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.

Input & Output

Example 1 — Basic Valid Pair
$ Input: s = "12332"
Output: "12"
💡 Note: Adjacent digits '1' and '2': digit 1 appears 1 time (matches its value 1), digit 2 appears 2 times (matches its value 2). Both conditions satisfied, so return "12".
Example 2 — No Valid Pair
$ Input: s = "1234"
Output: ""
💡 Note: Check each adjacent pair: '1' appears 1 time = 1 ✓, but '2' appears 1 time ≠ 2 ✗. Continue: '2' appears 1 time ≠ 2 ✗. No pair satisfies both conditions.
Example 3 — Early Valid Pair
$ Input: s = "1122"
Output: ""
💡 Note: Check pairs: '1' appears 2 times ≠ 1, so no pair starting with '1' can be valid. '2' appears 2 times = 2, but needs to be paired with a valid digit. No valid pairs exist.

Constraints

  • 1 ≤ s.length ≤ 1000
  • s consists only of digits '0' to '9'

Visualization

Tap to expand
Find Valid Pair of Adjacent Digits INPUT String s = "12332" 1 idx 0 2 idx 1 3 idx 2 3 idx 3 2 idx 4 Digit Frequency Count Digit Count 1 1 2 2 3 2 Count matches value for 1 and 2 (digit 1 appears 1x, digit 2 appears 2x) ALGORITHM STEPS 1 Count Frequencies Scan string, count each digit 2 Traverse Pairs Check adjacent pairs L to R 3 Validate Pair Digits different? Count=Value? 4 Return First Valid Return pair or empty string Pair Checking: "12": 1!=2 but count(1)=1 OK FAIL "23": 2!=3, count(2)=2 OK PASS count(2)=2=digit value count(3)=2 (but need 3) Wait: checking both digits! FINAL RESULT First valid pair found at index 1-2 1 2 3 3 2 Output: "23" Verification: Digit 2: count=2, value=2 OK Digit 3: count=2 (need 3) SKIP Note: Only digit 2 needs to match Both must be different: 2!=3 Key Insight: Single-pass optimization: First count all digit frequencies O(n), then traverse once checking adjacent pairs. For each pair, verify: (1) digits are different, (2) each digit's count equals its numeric value. Return immediately on first valid pair found. Time: O(n), Space: O(1) - only 10 digit counters needed. TutorialsPoint - Find Valid Pair of Adjacent Digits in String | Single-Pass Optimized Approach
Asked in
Google 25 Microsoft 18 Amazon 15
12.4K Views
Medium Frequency
~15 min Avg. Time
567 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen