Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

How to Solve Next Permutation on LeetCode

The Next Permutation problem is a popular LeetCode question that demonstrates your ability to manipulate arrays in-place and reason about permutations.

Leetcode

Problem Statement

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, rearrange it as the lowest possible order (i.e., sorted in ascending order).

Example:

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

Why This Problem Matters for Interviews

This problem:

  • Tests in-place array manipulation
  • Builds understanding of permutation theory
  • Requires identifying and reversing subarrays

Steps for Next Permutation

In-Place Modification (Optimal)

  1. Find first decreasing element from right.
  2. Swap it with just larger element on the right.
  3. Reverse the subarray after original index.

Time Complexity: O(n)
Space Complexity: O(1)

def nextPermutation(nums: list[int]) -> None: i = len(nums) - 2 while i >= 0 and nums[i] >= nums[i+1]: i -= 1 if i >= 0: j = len(nums) - 1 while nums[j] <= nums[i]: j -= 1 nums[i], nums[j] = nums[j], nums[i] left, right = i+1, len(nums)-1 while left < right: nums[left], nums[right] = nums[right], nums[left] left += 1 right -= 1

Key Interview Talking Points

  • Why reverse is required after swap
  • Handling already highest permutation (descending)
  • Lexicographical ordering definition
  • Edge cases: single-element array

Big O Complexity Recap

ApproachTime ComplexitySpace Complexity
In-place SwapO(n)O(1)

Pro Interview Tips

  • Walk through the algorithm step-by-step on example input.
  • Use pointers and drawing for explanation.
  • Practice with test cases

Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2025 Stealth Interview ™All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy