FrontendInterviews.dev

Loading problem…

76. Next Lexicographical Permutation

Medium•
Acceptance: 75.00%
•
🔓3/3 Pro unlocks today

Find the next lexicographical permutation of an array. If no next permutation exists (array is in descending order), return the array sorted in ascending order.

Requirements

1. Basic Functionality

  • Modify the array in-place (don't create a new array)
  • Find the next lexicographically greater permutation
  • If it's the last permutation, return the first permutation (sorted ascending)

2. Lexicographical Order

  • Permutations are ordered lexicographically (like dictionary order)
  • [1, 2, 3] < [1, 3, 2] < [2, 1, 3] < [2, 3, 1] < [3, 1, 2] < [3, 2, 1]

Example Usage

const nums = [1, 2, 3];
nextPermutation(nums);
console.log(nums); // [1, 3, 2]

const nums2 = [3, 2, 1];
nextPermutation(nums2);
console.log(nums2); // [1, 2, 3] (wrap around to first)

Constraints

  • Modify the array in-place (O(1) extra space)
  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 100
  • If no next permutation exists, return the first permutation
  • Time complexity should be O(n)