#3438
Find Valid Pair of Adjacent Digits in String
EasyHash TableStringCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
This approach uses a HashMap to count the occurrences of each digit first, allowing us to check pairs in a single pass, which is much more efficient.
⚙️
Algorithm
3 steps- 1Step 1: Create a frequency map to count occurrences of each digit in the string.
- 2Step 2: Iterate through the string and for each pair of adjacent digits, check if they are different.
- 3Step 3: For each valid pair, check their counts in the frequency map against their numeric values. If valid, return the pair.
solution.py8 lines
1def find_valid_pair(s):
2 from collections import Counter
3 freq = Counter(s)
4 for i in range(len(s) - 1):
5 if s[i] != s[i + 1]:
6 if freq[s[i]] == int(s[i]) and freq[s[i + 1]] == int(s[i + 1]):
7 return s[i] + s[i + 1]
8 return ''ℹ
Complexity note: The time complexity is O(n) because we traverse the string twice: once for counting and once for checking pairs. The space complexity is O(n) due to the frequency map.
- 1Using a frequency map allows for efficient counting and checking of conditions in a single pass.
- 2Adjacent pairs can be checked in linear time after counting, significantly improving performance.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.