Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Two pointers

The next permutation, in place

Medium · Target 20 minutes · Two pointers· Type asked at

You're given an array of integers nums. Rearrange it into the next permutation in lexicographic order, the smallest arrangement of the same values that's bigger than the one you've got, and return it. If it's already the biggest arrangement there is, wrap round to the smallest one, which is the values sorted ascending. You should use O(1) extra space.

Examples

InputOutputWhy
nums = [1, 2, 3][1, 3, 2]
nums = [3, 2, 1][1, 2, 3]3, 2, 1 is the biggest arrangement there is, so it wraps round to the smallest one.
nums = [1, 1, 5][1, 5, 1]With repeated values you still want the next distinct arrangement, and swapping the two 1's wouldn't change anything.
nums = [2, 4, 3, 1][3, 1, 2, 4]

Constraints

  • 1 ≤ n ≤ 100
  • 0 ≤ nums[i] ≤ 100

Hints

Hint 1

I'd look at the array from the right first and ask how long the run at the end is that only goes down, and why you can't make that bit any bigger by itself.

Hint 2

A run that only goes down is already in its biggest arrangement, so the change has to happen at i, the last index where nums[i] < nums[i + 1]. What do you think should go there?

Hint 3

You want the smallest value to the right of i that's still bigger than nums[i]. Once you've swapped it in the run after i is still going down, and you'd reverse it with two pointers to make it as small as it can be.

Where people lose marks

  • Using nums[i] ≤ nums[i + 1] to find the pivot. With repeated values it'll stop on a level step, and swapping equal values just gives you the same array back.
  • Sorting the suffix when reversing it is enough. It's already in descending order after the swap, so a sort costs O(n log n) for nothing.
  • Forgetting the wrap-round. When there's no pivot the answer's the values in ascending order, and that's the whole array reversed.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.