Taro Logo

Next Permutation

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+20
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.4K views
Topics:
ArraysTwo Pointers

A permutation of an array of integers is an arrangement of its members into a sequence or linear order.

  • For example, for arr = [1,2,3], the following are all the permutations of arr: [1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1].

The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order).

  • For example, the next permutation of arr = [1,2,3] is [1,3,2].
  • Similarly, the next permutation of arr = [2,3,1] is [3,1,2].
  • While the next permutation of arr = [3,2,1] is [1,2,3] because [3,2,1] does not have a lexicographical larger rearrangement.

Given an array of integers nums, find the next permutation of nums.

The replacement must be in place and use only constant extra memory.

Example 1:

Input: nums = [1,2,3]
Output: [1,3,2]

Example 2:

Input: nums = [3,2,1]
Output: [1,2,3]

Example 3:

Input: nums = [1,1,5]
Output: [1,5,1]

Constraints:

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 100

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can the input array contain duplicate values, and if so, how should they be treated when determining the lexicographically next permutation?
  2. What should be returned or done if the input array is empty or contains only a single element?
  3. If the array is already sorted in descending order (i.e., the last permutation), are we expected to wrap around and return the lowest possible order in-place?
  4. Should the rearrangement be performed strictly in-place with $O(1)$ extra memory, or is auxiliary space acceptable?
  5. Are the integers in the array guaranteed to fit within standard integer types, or could they cause overflow issues during manipulation?

Brute Force Solution

Approach

Imagine you are holding a sequence of items and need to find the exact configuration that comes immediately after your current one in a complete dictionary of all possible arrangements. The brute force approach involves generating every single valid way to arrange your items, sorting that massive list from first to last, and simply looking up the arrangement that sits directly after the one you currently have.

Here's how the algorithm would work step-by-step:

  1. Begin by listing out every conceivable way to mix up and arrange the items you were given.
  2. Make sure your list includes every single possible combination, leaving no stone unturned.
  3. Take all of those generated arrangements and sort them neatly into standard dictionary order, just like words in a book.
  4. Scan down the sorted list until you spot the exact arrangement you started with.
  5. Look at the arrangement that immediately follows your starting one in the sorted list.
  6. That next arrangement is your answer, so take note of it and finish the process.

Code Implementation

import itertools


def next_permutation(sequence_items):
    # Generate all unique permutations so we can examine every possible arrangement
    all_permutations = list(itertools.permutations(sequence_items))
    
    unique_permutations = sorted(list(set(all_permutations)))
    
    # Locate our starting position to find the exact relative order in the dictionary
    current_index = unique_permutations.index(tuple(sequence_items))
    
    next_index = (current_index + 1) % len(unique_permutations)
    
    # Mutate the input list in-place to satisfy the standard interview problem format
    sequence_items[:] = list(unique_permutations[next_index])

Big(O) Analysis

Time Complexity
O(n * n!) – To find the next permutation using the described brute force approach, we must first generate every conceivable arrangement of the n items, which results in n! total combinations. Then, sorting this massive list of n! arrangements lexicographically takes n! log(n!) time. Finally, scanning through the sorted list of size n! to find our starting configuration and taking the next one adds a linear scan of O(n!). Combining these steps, the total operations approximate n! log(n!) + n!, which simplifies in Big O notation to O(n * n!).
Space Complexity
O(1) – The algorithm performs all operations directly on the input sequence by swapping elements in place without allocating any additional data structures. A few primitive pointer variables are used to track indices, which require a constant amount of extra memory regardless of the input size. Because no temporary lists, hash maps, or recursive call stacks are utilized, the auxiliary space remains entirely independent of N. Consequently, the total extra memory required simplifies to constant time and space bounds denoted as O(1).

Optimal Solution

Approach

Instead of scrambling all the items randomly to find the next arrangement, we can find the next logical step by looking for a small backward shift from right to left. By making a tiny adjustment near the end and tidying up the rest, we instantly reach the very next arrangement in the sequence.

Here's how the algorithm would work step-by-step:

  1. Begin at the very end of the line and scan backward until you find the first spot where the items stop increasing in size.
  2. Once you find that spot, look slightly further to the right to find the smallest item that is still bigger than the one you just stopped at.
  3. Swap these two items to make the sequence just a little bit larger overall.
  4. Take everything that sits to the right of your original spot and flip their order completely so they are arranged as neatly as possible from smallest to largest.
  5. You now have the exact next arrangement ready without needing to check any other combinations.

Code Implementation

def next_permutation(permutation_list):    # Scan backward to find the first element that violates the non-decreasing order.    pivot_index = len(permutation_list) - 2    while pivot_index >= 0 and permutation_list[pivot_index] >= permutation_list[pivot_index + 1]:        pivot_index -= 1    if pivot_index >= 0:        # Find the smallest element to the right of the pivot that is larger than the pivot.        successor_index = len(permutation_list) - 1        while permutation_list[successor_index] <= permutation_list[pivot_index]:            successor_index -= 1        permutation_list[pivot_index], permutation_list[successor_index] = permutation_list[successor_index], permutation_list[pivot_index]    # Reverse the suffix to ensure the smallest possible lexicographical order for the remainder.    left_pointer = pivot_index + 1    right_pointer = len(permutation_list) - 1    while left_pointer < right_pointer:        permutation_list[left_pointer], permutation_list[right_pointer] = permutation_list[right_pointer], permutation_list[left_pointer]        left_pointer += 1        right_pointer -= 1

Big(O) Analysis

Time Complexity
O(n) – To find the next permutation, we first scan backward from the end of the array of size n to find the first decreasing element, which takes at most n operations. Next, we scan rightward from that spot to find the successor, and then we swap these two elements. Finally, we reverse the remaining suffix to the right, which also takes a fraction of n operations. Because each of these distinct steps processes the elements at most a constant number of times, the total operations scale linearly with n, simplifying to O(n).
Space Complexity
O(1) – The algorithm performs all swaps and reversals directly in place on the existing input array without allocating any auxiliary data structures. We only utilize a few constant scalar variables, such as integer pointers and indices, to keep track of our scanning positions from right to left. Because these variables do not scale with the input size N, the extra memory required remains entirely constant. Thus, the overall auxiliary space complexity simplifies to Big O of 1.

Edge Cases

Array of size 0 or 1
How to Handle:
The algorithm should return immediately because a single element or empty array has no next permutation.
Array sorted in strictly descending order
How to Handle:
Since no smaller element can be found from the right, the entire array is simply reversed to become the lowest possible order.
Array sorted in strictly ascending order
How to Handle:
The algorithm identifies the second to last element as the pivot, swaps it with the last element, and maintains the sorted order.
Array containing duplicate elements
How to Handle:
The scan from the right correctly finds the first decreasing element even with duplicates, treating equal values properly.
Array containing negative numbers and zeros
How to Handle:
Lexicographical ordering applies naturally to negative integers, zeros, and positive integers without requiring special transformations.
Maximum size input array reaching constraints
How to Handle:
The linear time complexity approach guarantees efficient in-place execution well within time limits without memory overhead.
Array with all identical elements
How to Handle:
The algorithm treats it as non-increasing from left to right, reversing the entire array to leave it unchanged.
Array of size 2 with elements in ascending order
How to Handle:
The two elements are simply swapped to produce the only other possible permutation.
0/75 completed