Leetcode Problem 556. Next Greater Element III

556. Next Greater Element III

Leetcode Solutions

Next Greater Element with Single Pass and Reversal

  1. Convert the number to a list of its digits.
  2. Traverse the list from right to left to find the first pair of digits where the right digit is greater than the left digit.
  3. If no such pair is found, return -1 as no greater permutation is possible.
  4. Find the smallest digit to the right of the found pair that is larger than the left digit of the pair.
  5. Swap this digit with the left digit of the pair.
  6. Reverse the sublist to the right of the original left digit's position to get the smallest permutation.
  7. Convert the list back to an integer.
  8. Check if the result fits in a 32-bit integer, if not return -1.
UML Thumbnail

Brute Force Permutation Approach

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...