#31

Next Permutation

MediumTwo PointersHas vizArrayTwo Pointers
Related studio

Problem

Next Permutation

You must solve the interview problem titled "Next Permutation".

Difficulty: Medium. Topics: Array, Two Pointers. Primary pattern: Two Pointers.

Read the title as the specification: implement the exact behavior it names, return the correct output type, and aim for an interview-optimal Two Pointers solution. Use the examples to lock input/output format, then confirm edge cases (empty, single element, duplicates, extremes).

Example 1

Input: sample input for Next Permutation

Output: sample output for Next Permutation

Apply a Two Pointers approach and match the required return type.

Example 2

Input: edge-case input for Next Permutation

Output: edge-case output for Next Permutation

Verify empty/single/boundary behavior.

Constraints

  • Interview-scale limits for a Medium Two Pointers problem.
  • Handle empty and single-element inputs when they are valid.
  • Prefer the optimal asymptotic complexity expected in interviews.
Loading visualization…

Explanation

Next Permutation is a Medium interview problem tagged [Array, Two Pointers]. The winning approach is typically **Two Pointers**.

Intuition

Each pointer only moves forward/backward once, guaranteeing O(n) after any required sort.

Approach

Place two indices and move them based on a comparison or invariant (sorted order, palindrome symmetry, partition).

  1. Establish the invariant (e.g., array sorted).
  2. Initialize L and R.
  3. Move the pointer that improves the condition.
  4. Handle duplicates carefully if uniqueness is required.

Solution

Pattern-level skeleton only — not this problem’s exact answer. Adapt it to the statement.

Pattern templateTwo Pointers

Edge cases

  • •Empty or single-element input
  • •Duplicates and ties
  • •Maximum constraints / overflow
  • •Disconnected or unreachable states (for graphs)

Complexity

Time: O(n log n) or O(n)

Space: O(n)

Before coding, restate the problem, name the pattern (Two Pointers), and write the invariant or DP state in one sentence.

Learn the topic

Got it?

Mark #31 Next Permutation as understood when the pattern clicks.