Problem 942

Abstract / Summary

Given a string of I and D, build a list of numbers so that I increases and D decreases the next number.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0942.py

class Solution:
    def diStringMatch(self, s: str) -> List[int]:
        low  = 0
        high = len(s)
        for c in s:
            if c == "I":
                yield low
                low  += 1
            else:
                yield high
                high -= 1
        yield low
12 lines | 303 bytes | submitted November 29, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 81% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Greedy
  • String
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the “DI String Match” problem by constructing a permutation of the integers 0 through n (where n = len(s)) that satisfies the pattern described by the input string s. The algorithm walks through the characters of s once, deciding at each step whether to place the smallest remaining number or the largest remaining number in the output sequence. The final value is emitted after the loop, completing the permutation.

Core Logic

The algorithm maintains two pointers, low and high, that delimit the current range of unused numbers.

low  = 0
high = len(s)

During the iteration over s, each character determines which end of the range is chosen.

for c in s:
    if c == "I":
        yield low
        low += 1
    else:
        yield high
        high -= 1

When the loop finishes, the remaining number (which is equal to low and high) is yielded.

yield low

The use of yield makes the function a generator, allowing the caller to consume the result lazily or convert it to a list with list(solution.diStringMatch(s)).

Edge-Case Handling

The code correctly processes an empty input string. In that situation len(s) is 0, so high is initialized to 0. The for loop does not execute, and the final yield low produces a single element 0, which is the only valid permutation for an empty pattern.

When the pattern consists solely of 'I' characters, the generator always selects the current low value, incrementing it each time. This yields the strictly increasing sequence [0, 1, 2, …, n].

Conversely, a pattern of only 'D' characters forces the generator to pick high each iteration, decrementing it afterwards. The output becomes the strictly decreasing sequence [n, n-1, …, 0].

Mixed patterns are handled naturally because the two pointers converge toward each other, guaranteeing that each integer in the required range is emitted exactly once.

Performance Optimizations

The algorithm operates in a single pass over the input string, performing only constant-time arithmetic and conditional checks per character. By using two integer variables to track the bounds of the remaining pool, it avoids any auxiliary data structures such as lists or sets, which eliminates allocation overhead.

The generator approach means that the permutation is produced on demand; memory consumption is limited to the call stack and the two pointers, regardless of the length of s. If the caller materializes the result into a list, the memory usage becomes O(n) for the final list, but the algorithm itself does not allocate intermediate containers.

Because the pointers move monotonically toward each other, there is no need for additional bookkeeping to detect already-used numbers. This deterministic movement ensures that each step is simple and predictable, contributing to a low constant factor in execution time.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long row of numbered toy blocks starting from zero and going up to a big number at the end. You also have a secret code made of letters. The letter I stands for increase and the letter D stands for decrease.

When you see the letter I, you pick the smallest number available from your set of blocks. Since that block is now used, the next smallest number becomes one step bigger. When you see the letter D, you pick the very biggest number currently sitting in your pile. After using that big block, the next biggest number available becomes one step smaller.

You keep looking at your code letter by letter and grabbing either the smallest or the biggest block until you have used almost all of them. Once you reach the very end of your secret code, there will be exactly one block left waiting for you. You pick up that final block to finish your line. Doing this creates a special pattern where the numbers go up and down just like a roller coaster.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.85 | σ = 1.98

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Go Rust TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fsq C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
suxrobGM C#
varunu28 Java
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fsq C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
suxrobGM C#
varunu28 Java
wisdompeak C++
34 links | 20 authors | 10 languages

Videos

10 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

4 solutions   November 29, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality