00:00

Problem Statement

Input/Output Examples

Visual Explanation

A decreasing suffix is already the largest arrangement of its values, so the change must happen just before it. After the swap the suffix is still decreasing, so reversing it makes it increasing, which is the smallest order.

Approaches

The standard algorithm works in place in linear time. The brute force lists every arrangement and is only suitable for tiny arrays.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the array length. The standard algorithm scans and reverses at most once; the brute force grows factorially.

Interview Tips and Recommended Approach

  • Explain the decreasing suffix. It is the key insight behind the whole algorithm.
  • Swap with the rightmost larger value, which is the smallest value larger than the pivot because the suffix is decreasing.
  • Reverse, do not sort. The suffix is already ordered, so reversing is enough and costs O(n).
  • Handle the last permutation. Reversing the whole array wraps around to the first one.

Recommended Approach: Pivot, Swap, Reverse

Why: it runs in linear time with constant memory and is the same algorithm C++'s std::next_permutation uses.