#556
Medium Algorithms Next greater element iii
Math Two Pointers String
35.2% acceptance
Jan 13, 2026
3931
495
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.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn next_greater_element(n: i32) -> i32 {
let mut digits: Vec<u8> = n.to_string().bytes().collect();
let len = digits.len();
// Find the rightmost digit that is smaller than the digit to its right
let mut i = len as isize - 2;
while i >= 0 && digits[i as usize] >= digits[i as usize + 1] {
i -= 1;
}
if i < 0 { return -1; }
let i = i as usize;
// Find the rightmost digit greater than digits[i] to the right of i
let mut j = len - 1;
while digits[j] <= digits[i] {
j -= 1;
}
digits.swap(i, j);
digits[i + 1..].reverse();
let result: i64 = digits.iter().fold(0i64, |acc, &d| acc * 10 + (d - b'0') as i64);
if result > i32::MAX as i64 { -1 } else { result as i32 }
}
}