Challenge - 5 Problems
Next Permutation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Next Permutation on a simple array
What is the output of the following C++ code that applies next permutation on the array?
DSA C++
std::vector<int> nums = {1, 2, 3}; std::next_permutation(nums.begin(), nums.end()); for (int n : nums) std::cout << n << " ";
Attempts:
2 left
💡 Hint
Next permutation finds the next lexicographically greater arrangement.
✗ Incorrect
The next permutation after 1 2 3 is 1 3 2 because it is the next bigger sequence in order.
❓ Predict Output
intermediateNext Permutation output on descending array
What will be printed after applying next permutation on this array?
DSA C++
std::vector<int> nums = {3, 2, 1}; std::next_permutation(nums.begin(), nums.end()); for (int n : nums) std::cout << n << " ";
Attempts:
2 left
💡 Hint
If the array is in descending order, next permutation resets to ascending order.
✗ Incorrect
The array {3,2,1} is the highest permutation. Next permutation resets it to the lowest: {1,2,3}.
🔧 Debug
advancedIdentify the error in this next permutation implementation
What error will this code cause when run?
DSA C++
void nextPermutation(std::vector<int>& nums) { int i = nums.size() - 2; while (i >= 0 && nums[i] >= nums[i + 1]) i--; if (i >= 0) { int j = nums.size() - 1; while (nums[j] <= nums[i]) j--; std::swap(nums[i], nums[j]); } std::reverse(nums.begin() + i + 1, nums.end()); } int main() { std::vector<int> arr = {3, 2, 1}; nextPermutation(arr); for (int n : arr) std::cout << n << " "; }
Attempts:
2 left
💡 Hint
Check the parameters passed to std::reverse carefully.
✗ Incorrect
The reverse call should start from i+1 to reverse the suffix. The original code had an error using nums.begin() + i which included the pivot. Corrected code uses nums.begin() + i + 1.
🧠 Conceptual
advancedUnderstanding the pivot in next permutation
In the next permutation algorithm, what is the role of the pivot index 'i' found by scanning from right to left?
Attempts:
2 left
💡 Hint
Think about where the array stops increasing from the right.
✗ Incorrect
The pivot 'i' is the first index from the right where nums[i] < nums[i+1]. This is where the next permutation changes by swapping and reversing the suffix.
❓ Predict Output
expertOutput after multiple next permutation calls
What is the output after applying next permutation three times on this array?
DSA C++
std::vector<int> nums = {1, 2, 3}; for (int i = 0; i < 3; i++) std::next_permutation(nums.begin(), nums.end()); for (int n : nums) std::cout << n << " ";
Attempts:
2 left
💡 Hint
List the permutations in order and count three steps from the start.
✗ Incorrect
The permutations in order are: 1 2 3, 1 3 2, 2 1 3, 2 3 1, 3 1 2, 3 2 1. After three next_permutation calls from 1 2 3, the array is 2 3 1.
