LeetCode 0556. Next Greater Element III Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0556. Next Greater Element III

Description

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.

Note that the returned integer should fit in 32-bit integer, if there is a valid answer but it does not fit in 32-bit integer, return -1.

 

Example 1:

Input: n = 12
Output: 21

Example 2:

Input: n = 21
Output: -1

 

Constraints:

  • 1 <= n <= 231 - 1

Solutions

Solution 1

PythonJavaC++Go
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 ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !