Increasing Decreasing String — LeetCode 1370 Python Solution
EasyHash TableStringCounting
- Problem
- #1370
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given a string s. Reorder the string using the following algorithm: Remove the smallest character from s and append it to the result.
Example
- Input
- s = "aaaabbbbcccc"
- Output
- "abccbaabccba"
- Explanation
- After steps 1, 2 and 3 of the first iteration, result = "abc"
Python solution
Python
class Solution:
def sortString(self, s: str) -> str:
cnt = Counter(s)
cs = ascii_lowercase + ascii_lowercase[::-1]
ans = []
while len(ans) < len(s):
for c in cs:
if cnt[c]:
ans.append(c)
cnt[c] -= 1
return "".join(ans)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times |\Sigma|) |
| Space | O(|\Sigma|) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1370. Increasing Decreasing String is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table and Counting.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1370. Increasing Decreasing String?
- LeetCode 1370. Increasing Decreasing String is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1370. Increasing Decreasing String?
- The Python solution on this page runs in O(n \times |\Sigma|).
- What is the space complexity of LeetCode 1370. Increasing Decreasing String?
- The Python solution on this page uses O(|\Sigma|) auxiliary space.
- What topics does LeetCode 1370. Increasing Decreasing String cover?
- LeetCode 1370. Increasing Decreasing String is tagged Hash Table, String and Counting on LeetCode.