File: di-string-match/solution.py

Date: 2026-06-06

Time: 16:22

DI String Match — di-string-match/solution.py

Purpose

Solves LeetCode 942: DI String Match. Given a string s of length n containing only 'I' (increase) and 'D' (decrease) characters, construct a permutation perm of [0, 1, ..., n] such that for every i: if s[i] == 'I' then perm[i] < perm[i+1], and if s[i] == 'D' then perm[i] > perm[i+1].

Key Components

Solution.diStringMatch(self, s: str) -> list[int] — The sole method. Uses a greedy two-pointer approach with low and high tracking the smallest and largest unused values in [0..n].

Patterns

Greedy with extremal values. The core insight: when you see 'I', placing the current smallest unused value guarantees the next value (whatever it is) will be larger. Symmetrically, 'D' places the current largest unused value, guaranteeing the next will be smaller. This is a classic greedy pattern — making the locally safest choice at each step produces a globally valid permutation.

The algorithm avoids any sorting, backtracking, or search. It's a single linear pass.

Dependencies

Imports: None — pure algorithmic code with no external dependencies.

Imported by: The di-string-match/test_solution.py file directly. The large "Imported By" list in the prompt is an artifact of the repo's test infrastructure — those other test files don't actually import this solution; they share a common test harness pattern.

Flow

1. Initialize low = 0, high = n — the full range of available values.

2. Iterate over each character in s:

3. After the loop, low == high — exactly one value remains. Append it. This is the n+1th element (the permutation has length n+1 for a string of length n).

Time: O(n). Space: O(n) for the output list.

Invariants

Error Handling

None. The method assumes valid input per LeetCode constraints — s contains only 'I' and 'D', and len(s) >= 1. An empty string would produce [0], which is correct (trivial permutation).

Topics to Explore

Beliefs