Loading...
You are given an integer n. Treat its decimal digits as a sequence, and consider every arrangement (permutation) of that same multiset of digits, ordered lexicographically. Return the next arrangement after n in that order, read back as a number.
If n's digits are already arranged in descending order, meaning n is the largest possible arrangement, return the smallest arrangement instead: its digits in ascending order, read back as a number. Note that reading a digit sequence back as a number drops any leading zeros, so the smallest arrangement of the digits of 210, namely 012, is returned as 12.
Input: n = 123
Output: 132
Input: n = 321
Output: 123
Explanation: 321 is the largest arrangement of the digits 1, 2, and 3, so the answer wraps around to the smallest arrangement, 123.
Input: n = 115
Output: 151
Click "Run" to test with sample cases or "Submit" to run all tests.