Next Greater Element III — LeetCode 556 Python Solution
MediumMathTwo PointersString
- Problem
- #556
- Pattern
- Two Pointers
- Reading time
- 3 min
- Source
- leetcode.com
The problem
Given a positive integer n, find the smallest integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive integer exists, return -1.
Example
- Input
- n = 12
- Output
- 21
Python solution
Python
class Solution:
def nextGreaterElement(self, n: int) -> int:
cs = list(str(n))
n = len(cs)
i, j = n - 2, n - 1
while i >= 0 and cs[i] >= cs[i + 1]:
i -= 1
if i < 0:
return -1
while cs[i] >= cs[j]:
j -= 1
cs[i], cs[j] = cs[j], cs[i]
cs[i + 1 :] = cs[i + 1 :][::-1]
ans = int(''.join(cs))
return -1 if ans > 2**31 - 1 else ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) (after optional sort O(n log n)) |
| Space | O(1) auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 556. Next Greater Element III 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 556. Next Greater Element III?
- LeetCode 556. Next Greater Element III is rated Medium on LeetCode.
- What is the time complexity of LeetCode 556. Next Greater Element III?
- The Python solution on this page runs in O(n) (after optional sort O(n log n)).
- What is the space complexity of LeetCode 556. Next Greater Element III?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 556. Next Greater Element III cover?
- LeetCode 556. Next Greater Element III is tagged Math, Two Pointers and String on LeetCode.