Overflow in intermediate arithmetic
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
Move from brute-force thinking to an efficient approach using math strategy.
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 - 1Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Math · Two Pointers
12
21
next-greater-element-i)next-greater-element-ii)next-palindrome-using-same-digits)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #556: Next Greater Element III
class Solution {
public int nextGreaterElement(int n) {
char[] cs = String.valueOf(n).toCharArray();
n = cs.length;
int i = n - 2, j = n - 1;
for (; i >= 0 && cs[i] >= cs[i + 1]; --i)
;
if (i < 0) {
return -1;
}
for (; cs[i] >= cs[j]; --j)
;
swap(cs, i, j);
reverse(cs, i + 1, n - 1);
long ans = Long.parseLong(String.valueOf(cs));
return ans > Integer.MAX_VALUE ? -1 : (int) ans;
}
private void swap(char[] cs, int i, int j) {
char t = cs[i];
cs[i] = cs[j];
cs[j] = t;
}
private void reverse(char[] cs, int i, int j) {
for (; i < j; ++i, --j) {
swap(cs, i, j);
}
}
}
// Accepted solution for LeetCode #556: Next Greater Element III
func nextGreaterElement(n int) int {
s := []byte(strconv.Itoa(n))
n = len(s)
i, j := n-2, n-1
for ; i >= 0 && s[i] >= s[i+1]; i-- {
}
if i < 0 {
return -1
}
for ; j >= 0 && s[i] >= s[j]; j-- {
}
s[i], s[j] = s[j], s[i]
for i, j = i+1, n-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
ans, _ := strconv.Atoi(string(s))
if ans > math.MaxInt32 {
return -1
}
return ans
}
# Accepted solution for LeetCode #556: Next Greater Element III
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
// Accepted solution for LeetCode #556: Next Greater Element III
struct Solution;
impl Solution {
fn next_greater_element(n: i32) -> i32 {
let mut s: Vec<char> = format!("{}", n).chars().collect();
let n = s.len();
let mut l = n;
for i in (0..n - 1).rev() {
if s[i] < s[i + 1] {
l = i;
break;
}
}
if l == n {
return -1;
}
let mut max = s[l + 1];
let mut r = l + 1;
for i in l + 2..n {
if s[i] > s[l] && s[i] < max {
max = s[i];
r = i;
}
}
s.swap(l, r);
s[l + 1..].sort_unstable();
s.iter().collect::<String>().parse::<i32>().unwrap_or(-1)
}
}
#[test]
fn test() {
let n = 12;
let res = 21;
assert_eq!(Solution::next_greater_element(n), res);
let n = 21;
let res = -1;
assert_eq!(Solution::next_greater_element(n), res);
let n = 1_999_999_999;
let res = -1;
assert_eq!(Solution::next_greater_element(n), res);
}
// Accepted solution for LeetCode #556: Next Greater Element III
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #556: Next Greater Element III
// class Solution {
// public int nextGreaterElement(int n) {
// char[] cs = String.valueOf(n).toCharArray();
// n = cs.length;
// int i = n - 2, j = n - 1;
// for (; i >= 0 && cs[i] >= cs[i + 1]; --i)
// ;
// if (i < 0) {
// return -1;
// }
// for (; cs[i] >= cs[j]; --j)
// ;
// swap(cs, i, j);
// reverse(cs, i + 1, n - 1);
// long ans = Long.parseLong(String.valueOf(cs));
// return ans > Integer.MAX_VALUE ? -1 : (int) ans;
// }
//
// private void swap(char[] cs, int i, int j) {
// char t = cs[i];
// cs[i] = cs[j];
// cs[j] = t;
// }
//
// private void reverse(char[] cs, int i, int j) {
// for (; i < j; ++i, --j) {
// swap(cs, i, j);
// }
// }
// }
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair of elements. The outer loop picks one element, the inner loop scans the rest. For n elements that is n × (n−1)/2 comparisons = O(n²). No extra memory — just two loop variables.
Each pointer traverses the array at most once. With two pointers moving inward (or both moving right), the total number of steps is bounded by n. Each comparison is O(1), giving O(n) overall. No auxiliary data structures are needed — just two index variables.
Review these before coding to avoid predictable interview regressions.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
Wrong move: Advancing both pointers shrinks the search space too aggressively and skips candidates.
Usually fails on: A valid pair can be skipped when only one side should move.
Fix: Move exactly one pointer per decision branch based on invariant.