Next Permutation is a good example of turning a small-looking problem into a precise invariant. The Java implementation below captures the core idea, so this post focuses on why the approach works, what it is really solving, and how to debug it when the first attempt goes wrong.


Problem 1: Next Permutation

Problem description: We are given a problem around Next Permutation and need a Java solution that is correct on both normal and edge-case inputs. The challenge is usually not writing a loop or recursion call; it is preserving the one invariant that makes the approach valid from start to finish.

What we are solving actually: We are solving for correctness under the constraints that matter for this problem family. In practice, that means understanding which state must be remembered, what can be derived on the fly, and where a brute-force approach would waste work or break boundary conditions.

What we are doing actually:

  1. scan the input while keeping the main invariant explicit
  2. use the right supporting structure only when it removes repeated work
  3. lean on pointer or search-space narrowing rather than nested brute-force checks
  4. return the result only after boundary cases like duplicates or empty input are accounted for

Why This Problem Matters

  • array problems teach when indexing alone is enough and when hashing or sorting changes the cost model
  • many interview and production debugging tasks hide simple boundary bugs inside otherwise small loops
  • next permutation is a good example of trading brute force for a more intentional invariant

Implementation Context

This post is built around a Java implementation of the problem and keeps the solution shape close to the version I wanted to teach from. The goal is to preserve the underlying idea while making the reasoning easier to follow.

That keeps the article practical. Instead of presenting an overly polished answer detached from how these problems are usually solved, the explanation stays close to interview-style Java code and makes the invariants explicit.

Java Solution


import java.util.Arrays;

/**
 * 31. Next Permutation
 * A permutation of an array of integers is an arrangement of its members into a sequence or linear order.
 * <p>
 * For example, for arr = [1,2,3], the following are considered permutations of arr: [1,2,3], [1,3,2], [3,1,2], [2,3,1].
 * The next permutation of an array of integers is the next lexicographically greater permutation of its integer.
 * More formally, if all the permutations of the array are sorted in one container according to their lexicographical
 * order, then the next permutation of that array is the permutation that follows it in the sorted container.
 * If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in
 * ascending order).
 * <p>
 * For example, the next permutation of arr = [1,2,3] is [1,3,2].
 * Similarly, the next permutation of arr = [2,3,1] is [3,1,2].
 * While the next permutation of arr = [3,2,1] is [1,2,3] because [3,2,1] does not have a lexicographical larger
 * rearrangement.
 * Given an array of integers nums, find the next permutation of nums.
 * <p>
 * The replacement must be in place and use only constant extra memory.
 * <p>
 * Example 1:
 * Input: nums = [1,2,3]
 * Output: [1,3,2]
 * <p>
 * Example 2:
 * Input: nums = [3,2,1]
 * Output: [1,2,3]
 * <p>
 * Example 3:
 * Input: nums = [1,1,5]
 * Output: [1,5,1]
 */
public class NextPermutation {
	public static void nextPermutation(int[] nums) {
		//Step:-1 find the first decreasing sequence from end
		int i = nums.length - 2; // second last element

		while (i >= 0 && nums[i] >= nums[i + 1]) {
			i--;
		}


		//find number just greater than element and swap the two numbers
		// 1 1 5 4 1 >> 1 4 5 1 1
		if (i >= 0) {
			int j = nums.length - 1; // last element

			// compare 1 element with j to find out just greater element
			while (nums[j] <= nums[i]) {
				j--;
			}

			swap(nums, i, j);
		}


		// reverse the rest of the elements
		// 1 4 1 1 5
		reverse(nums, i + 1);

	}

	private static void reverse(int[] nums, int start) {
		int i = start, j = nums.length - 1;
		while (i < j) {
			swap(nums, i, j);
			i++;
			j--;
		}
	}

	private static void swap(int[] nums, int i, int j) {
		int temp = nums[i];
		nums[i] = nums[j];
		nums[j] = temp;
	}

	public static void main(String[] args) {
		int[] nums = {1, 1, 5, 4, 1};
		nextPermutation(nums);

		Arrays.stream(nums).forEach(n -> System.out.print(n + " ,"));
	}
}

Why This Solution Works

The implementation works because it keeps the critical state small and meaningful. Instead of trying to remember every past possibility, it keeps only the information needed for the next step, and that is exactly what makes the solution easier to reason about than a brute-force version.

Another good thing to notice is that the code is direct. The data structure and control flow match the problem shape closely, which is what you want in DSA code: fewer moving parts, cleaner invariants, and a faster path to debugging.

Dry Run

Dry-run one small input and keep track of the exact index, accumulator, or lookup structure after each step. Next Permutation usually becomes easy once you can explain why each element is processed only once or why a second pass is still necessary.

If you can explain the dry run without hand-waving, the code usually stops feeling memorized and starts feeling mechanical. That is the point where interview pressure drops and implementation speed improves.

Edge Cases To Test

  • empty or single-element input
  • duplicates that change lookup behavior
  • already sorted or reverse-ordered input

These edge cases are worth testing before you trust the solution. Many DSA bugs do not come from the main idea; they come from assuming the input shape is always convenient.

Performance Notes

The implementation leans on pointer or search-space narrowing. When you review or optimize it, focus first on how many full passes it makes over the input and what extra state it keeps alive, because those two choices dominate both speed and memory use more than small syntax tweaks do.

Debug Steps

Debug steps:

  • print the running index and any lookup structure after each iteration
  • re-run with duplicates and smallest valid input
  • check whether the algorithm accidentally reuses the same element twice
  • verify what happens before the first successful match

Key Takeaways

  • Next Permutation becomes easier once the central invariant is stated in plain language.
  • This solution is useful because the control flow stays close to the data structure or recursion contract it depends on.
  • If the implementation fails, debug the state transition first, not the syntax.

Comments