Find Permutation — LeetCode 484 Python Solution
- Problem
- #484
- Pattern
- Stack
- Reading time
- 2 min
- Source
- leetcode.com
The problem
A permutation perm of n integers of all the integers in the range [1, n] can be represented as a string s of length n - 1 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 lexicographically smallest permutation perm and return it.
Example
- Input
- s = "I"
- Output
- [1,2]
- Explanation
- [1,2] is the only legal permutation that can represented by s, where the number 1 and 2 construct an increasing relationship.
Python solution
class Solution:
def findPermutation(self, s: str) -> List[int]:
n = len(s)
ans = list(range(1, n + 2))
i = 0
while i < n:
j = i
while j < n and s[j] == 'D':
j += 1
ans[i : j + 1] = ans[i : j + 1][::-1]
i = max(i + 1, j)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) |
| Space | O(1) to O(n) auxiliary |
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 484. Find Permutation is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.
The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 484. Find Permutation?
- LeetCode 484. Find Permutation is rated Medium on LeetCode.
- What topics does LeetCode 484. Find Permutation cover?
- LeetCode 484. Find Permutation is tagged Stack, Greedy, Array and String on LeetCode.
- Is LeetCode 484. Find Permutation a premium problem?
- Yes. LeetCode 484. Find Permutation is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.