Leetcode 556: Next Greater Element III

grid47
grid47
Exploring patterns and algorithms
Sep 12, 2024 4 min read

A sequence of numbers where each next greater element softly illuminates as it’s found for the next number.
Solution to LeetCode 556: Next Greater Element III Problem

Given a positive integer n, find the smallest integer which can be formed by rearranging the digits of n and is greater than n. If no such integer exists, return -1.
Problem
Approach
Steps
Complexity
Input: The input is a positive integer n, which can be up to 2^31-1.
Example: Input: n = 123
Constraints:
• 1 <= n <= 2^31 - 1
Output: The output should be the smallest integer greater than n formed by rearranging its digits, or -1 if no such integer exists.
Example: Output: 132
Constraints:
• The returned value should be within the 32-bit signed integer range.
Goal: The goal is to find the smallest integer greater than n that can be formed using the digits of n.
Steps:
• Convert n to a string of digits.
• Find the next permutation of the digits that is greater than n.
• If such a permutation exists and it fits within the 32-bit integer range, return it.
• If no permutation is possible or the resulting number exceeds the 32-bit limit, return -1.
Goal: The input integer n will be within the range of 1 to 2^31-1.
Steps:
• 1 <= n <= 2^31 - 1
Assumptions:
• The input will always be a valid positive integer within the specified range.
Input: Input: n = 123
Explanation: The next permutation of the digits of 123 is 132, which is the smallest number greater than 123 that can be formed.

Input: Input: n = 321
Explanation: Since no larger number can be formed with the digits of 321, the answer is -1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus