#1370
Increasing Decreasing String
EasyHash TableStringCounting
Approaches
💡
Intuition
Time Space
The brute force approach involves repeatedly finding the smallest and largest characters in the string, appending them to the result, and removing them from the original string. This is simple but inefficient due to repeated searches.
⚙️
Algorithm
6 steps- 1Step 1: Initialize an empty result string.
- 2Step 2: While there are characters left in the string, find and append the smallest character to the result.
- 3Step 3: Continue to find and append the next smallest character greater than the last appended character.
- 4Step 4: Once no more characters can be appended, find and append the largest character.
- 5Step 5: Continue to find and append the next largest character smaller than the last appended character.
- 6Step 6: Repeat steps 2-5 until all characters are processed.
solution.py18 lines
1def increasingDecreasingString(s):
2 result = ''
3 while s:
4 smallest = min(s)
5 result += smallest
6 s = s.replace(smallest, '', 1)
7 while s and (next_smallest := min(c for c in s if c > smallest)):
8 result += next_smallest
9 s = s.replace(next_smallest, '', 1)
10 if not s:
11 break
12 largest = max(s)
13 result += largest
14 s = s.replace(largest, '', 1)
15 while s and (next_largest := max(c for c in s if c < largest)):
16 result += next_largest
17 s = s.replace(next_largest, '', 1)
18 return resultSolutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.