Problem Description
We are given a string s consisting only of digits from '1' to '9'. We need to find the first adjacent pair in s where:
- The two digits are different.
- Each digit in the pair appears in s exactly as many times as its numeric value. Return the valid pair as a string, or return an empty string if no valid pair exists.
Key Insights
- Use a hash table (frequency map) to count the frequency of each digit in s.
- Iterate through the string examining each adjacent pair.
- For each pair, check if:
- The digits are distinct.
- Frequency of the first digit equals its numeric value.
- Frequency of the second digit equals its numeric value.
- Return the first pair satisfying these conditions.
Space and Time Complexity
Time Complexity: O(n), where n is the length of s (we traverse the string to build the frequency map and again to find the pair).
Space Complexity: O(1), since the frequency map will only store counts for digits '1' to '9' (constant size).
Solution
We first build a frequency table for all digits in s. Then, we scan through s checking each adjacent pair. For each pair, we verify that they are not equal and that each digit’s frequency matches the numeric value of the digit. If such a pair is found, we return it immediately. Otherwise, if no valid pair is found, we return an empty string.