#556
Next Greater Element III
MediumMathTwo PointersStringTwo PointersGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach uses a systematic method to find the next greater permutation of the digits without generating all permutations. This is efficient and avoids unnecessary computations.
⚙️
Algorithm
5 steps- 1Step 1: Convert the number to a list of digits.
- 2Step 2: Find the first pair of digits from the right where the left digit is smaller than the right digit.
- 3Step 3: Find the smallest digit on the right side of this pair that is larger than the left digit.
- 4Step 4: Swap these two digits.
- 5Step 5: Reverse the digits to the right of the original position of the left digit to get the smallest order.
solution.py17 lines
1# Full working Python code
2
3def nextGreaterElement(n):
4 digits = list(str(n))
5 length = len(digits)
6 i = length - 2
7 while i >= 0 and digits[i] >= digits[i + 1]:
8 i -= 1
9 if i == -1:
10 return -1
11 j = length - 1
12 while digits[j] <= digits[i]:
13 j -= 1
14 digits[i], digits[j] = digits[j], digits[i]
15 digits[i + 1:] = reversed(digits[i + 1:])
16 result = int(''.join(digits))
17 return result if result < 2**31 else -1ℹ
Complexity note: The time complexity is O(n) because we make a single pass through the digits to find the swap positions and then reverse the tail. The space complexity is O(1) since we only use a few variables for indexing.
- 1Understanding how to manipulate digits is crucial.
- 2Recognizing the need for efficient searching and swapping.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.