DI String Match — LeetCode 942 Python Solution
- Problem
- #942
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.