DI String Match — LeetCode 942 Python Solution

EasyGreedyArrayTwo PointersString
Problem
#942
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

Python
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

MeasureComplexity
TimeO(n)
SpaceO(n), where n is the length of the string `s` auxiliary

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

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.

Get Stealth Interview