The Next Greater Element III problem gives you a positive integer n and asks you to find the smallest integer greater than n that uses the same digits as n. This is equivalent to finding the next permutation of n's digit sequence. If no such number exists or it overflows a 32-bit integer, return -1. This Next Greater Element III coding problem applies the next permutation algorithm to integer digits.
Goldman Sachs, Microsoft, Meta, Amazon, Google, and Bloomberg ask this because it applies the Next Permutation algorithm to a real-world scenario — rearranging digits to find the next larger number. The math, two pointers, and string interview pattern is directly applied, and the overflow check adds practical implementation detail.
Next Permutation on digit array. Convert n to a digit string/array. Apply the next permutation algorithm: (1) find the rightmost digit that is smaller than the digit to its right (pivot); (2) find the rightmost digit greater than the pivot and swap them; (3) reverse the suffix after the pivot position. Convert back to integer. If no pivot found (digits are non-increasing), return -1. Check for 32-bit overflow.
n = 1243. Digits: [1, 2, 4, 3].
Next Permutation is one of the most important two-pointer algorithms. The three-step pattern — find pivot, swap with next-greater, reverse suffix — is elegant and widely applicable. Memorize it until you can write it in under 2 minutes. Next Greater Element III adds the digit-extraction and overflow-check wrapper. Practice applying Next Permutation in different contexts: string permutations, number rearrangements, and sequence generation problems.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Move Pieces to Obtain a String | Medium | Solve | |
| Reverse Words in a String | Medium | Solve | |
| Compare Version Numbers | Medium | Solve | |
| Magical String | Medium | Solve | |
| String Compression | Medium | Solve |