Skip to main content
  1. LeetCode/

LeetCode 556: Next Greater Element III

·1 min· ·
LeetCode Blog Medium
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2025-04-13

  • Total time: 5:00.00

Intuition
#

This is the classic Next Permutation problem, but with one additional constraint:
the number must fit within a 32-bit signed integer.
Therefore, we need to perform an extra check at the end of the algorithm to ensure the result is valid.

Approach
#

class Solution:
    def nextGreaterElement(self, n: int) -> int:
        digits = list(str(n))

        i = len(digits)-2
        while i != -1 and digits[i]>=digits[i+1]:
            i -= 1

        if i == -1:
            return -1

        j = len(digits)-1
        while digits[i]>=digits[j]: 
            j -=1

        digits[i], digits[j] = digits[j], digits[i]
        digits[i+1:] = reversed(digits[i+1:])
        res = int("".join(digits))

        return res if res < 1<<31 else -1

Findings
#

  1. 1 << 32 means shifting the number 1 to the 32nd bit position, which is equivalent to calculating 2 raised to the power of 32.

Encountered Problems
#

NA

Related

LeetCode 1922: Count Good Numbers
·2 mins
LeetCode Blog Daily Medium
LeetCode Problem Solving
LeetCode 3517: Smallest Palindromic Rearrangement I
·1 min
LeetCode Blog Weekly Medium
LeetCode Problem Solving
LeetCode 3513: Number of Unique XOR Triplets I
·2 mins
LeetCode Blog Bi-Weekly Medium Unsolved
LeetCode Problem Solving
LeetCode 3516: Find Closest Person
·1 min
LeetCode Blog Weekly Easy
LeetCode Problem Solving
LeetCode 3512: Minimum Operations to Make Array Sum Divisible by K
·1 min
LeetCode Blog Bi-Weekly Easy
LeetCode Problem Solving
LeetCode 2843: Count Symmetric Integers
·1 min
LeetCode Blog Daily Easy
LeetCode Problem Solving