Advance an Array to Its Next Lexicographic Order

Quick Overview

Rearrange an array in place to its next lexicographic permutation, wrapping to the smallest order with constant extra memory and no return value.

Advance an Array to Its Next Lexicographic Order

Company: Amazon

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

### Problem Rearrange the integer array `nums` in place into the next lexicographically greater arrangement of its values. If no greater arrangement exists, replace it with the lexicographically smallest arrangement, which is sorted in nondecreasing order. Lexicographic comparison uses the first position where two arrays differ. Equal values may repeat; compare the value sequences rather than treating equal occurrences as different results. The change must use constant extra memory. Preserve the original void-returning interface: ```cpp void nextPermutation(vector<int>& nums); ``` There is no replacement array to return. The caller observes the changed original argument. ### Examples ```text Input: nums = [2,4,3,3] After the call: nums = [3,2,3,4] ``` This is the smallest arrangement greater than the input. ```text Input: nums = [8,5,5] After the call: nums = [5,5,8] ``` The input is already the greatest arrangement of those values, so the order wraps to the smallest. ### Constraints - `1 <= nums.length <= 100`. - Every entry is between 0 and 100, inclusive. - Modify the supplied array in place using `O(1)` extra space; the procedure returns no value.

Overview: Rearrange an array in place to its next lexicographic permutation, wrapping to the smallest order with constant extra memory and no return value.

Amazon logo
Amazon
Date not reported
mediumSoftware EngineerOtherCoding & Algorithms
0
0

Problem

Rearrange the integer array nums in place into the next lexicographically greater arrangement of its values. If no greater arrangement exists, replace it with the lexicographically smallest arrangement, which is sorted in nondecreasing order.

Lexicographic comparison uses the first position where two arrays differ. Equal values may repeat; compare the value sequences rather than treating equal occurrences as different results.

The change must use constant extra memory. Preserve the original void-returning interface:

void nextPermutation(vector<int>& nums);

There is no replacement array to return. The caller observes the changed original argument.

Examples

Input: nums = [2,4,3,3]
After the call: nums = [3,2,3,4]

This is the smallest arrangement greater than the input.

Input: nums = [8,5,5]
After the call: nums = [5,5,8]

The input is already the greatest arrangement of those values, so the order wraps to the smallest.

Constraints

  • 1 <= nums.length <= 100 .
  • Every entry is between 0 and 100, inclusive.
  • Modify the supplied array in place using O(1) extra space; the procedure returns no value.