EasyNo. 0942

DI String Match — LeetCode 942 Python Solution

Topics
Greedy, Array, Two Pointers, String
Reading time
2 min

The problem

A permutation perm of n + 1 integers of all the integers in the range [0, n] can be represented as a string s of length n where: s[i] == 'I' if perm[i] < perm[i + 1], and s[i] == 'D' if perm[i] > perm[i + 1]. Given a string s, reconstruct the permutation perm and return it.

Example

Input
s = "IDID"
Output
[0,4,1,3,2]

Python solution

PythonSolution
class Solution:
    def diStringMatch(self, s: str) -> List[int]:
        low, high = 0, len(s)
        ans = []
        for c in s:
            if c == "I":
                ans.append(low)
                low += 1
            else:
                ans.append(high)
                high -= 1
        ans.append(low)
        return ans

Complexity

Time
O(n)
Space · auxiliary
O(n)where n is the length of the string `s`

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 942. DI String Match is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0948Bag of TokensMedium
0011Container With Most WaterMedium
0179Largest NumberMedium
0455Assign CookiesEasy
0611Valid Triangle NumberMedium
0680Valid Palindrome IIEasy

Frequently asked questions

How hard is LeetCode 942. DI String Match?

LeetCode 942. DI String Match is rated Easy on LeetCode.

What is the time complexity of LeetCode 942. DI String Match?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 942. DI String Match?

The Python solution on this page uses O(n), where n is the length of the string `s` auxiliary space.

What topics does LeetCode 942. DI String Match cover?

LeetCode 942. DI String Match is tagged Greedy, Array, Two Pointers and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.