Rearrange nums into the next greater permutation in dictionary order. If it's already the largest arrangement, wrap around to the smallest (sorted ascending). Do it in place with O(1) extra memory.
nums = [1,2,3][1,3,2]nums = [3,2,1][1,2,3] (largest โ wraps to smallest)nums = [1,1,5][1,5,1]i with nums[i] < nums[i+1] ๐ปj with nums[j] > nums[i], then swap them ๐nums[i+1..] so the suffix becomes ascending โฉ๏ธAfter the swap, the suffix is still descending: the new value at j fits between its neighbours because it's the smallest number bigger than the pivot. So "sort the suffix ascending" is just reversing it, O(n) instead of O(n log n). And the first j from the right with nums[j] > nums[i] is automatically the smallest such number, because the suffix is descending.
Fully descending ([3,2,1]) โ no dip, reverse everything to get [1,2,3]. Duplicates ([1,1,5], [1,5,1]) โ use >= when looking for the dip and <= when looking for j, or equal values get swapped for nothing. Single element โ unchanged.