Skip to main content

py_pattern_tracker — Count Consecutive Ascending Digit Pairs

Difficulty: medium

Count the number of valid consecutive digit pairs in a string. A valid pair is two adjacent characters that are both digits where the second is exactly one greater than the first. A 9 followed by a 0 is not a valid pair.

def pattern_tracker(text: str) -> int:

Examples

>>> pattern_tracker("123")
2

>>> pattern_tracker("12a34")
2

>>> pattern_tracker("987654321")
0

>>> pattern_tracker("01234567")
7

>>> pattern_tracker("abc")
0

>>> pattern_tracker("1a2b3c4")
0

>>> pattern_tracker("112233")
2

Solution

Download py_pattern_tracker.py
def pattern_tracker(text: str) -> int:
count = 0
for i in range(len(text) - 1):
a, b = text[i], text[i + 1]
if a.isdigit() and b.isdigit() and int(b) == int(a) + 1:
count += 1
return count

How It Works

Goal: Count adjacent pairs (text[i], text[i+1]) where both are digits and the second is exactly one greater than the first.

Approach: Single pass over each adjacent pair, with three guards: both must be digits, and the numeric difference must be +1.

Step by step:

  1. Loop i from 0 to len(text) - 2.
  2. Skip the pair unless both characters are digits.
  3. Convert each to its integer value and check b == a + 1.
  4. Increment a counter on each match.

Key concept: Pairwise/window scans — many string and array problems reduce to "look at element i and i+1", which is just a loop with the upper bound shifted down by 1.