Turn Complexity into Code: Learn Permutation in Java with Examples
By Rohan Vats
Updated on Jul 21, 2025 | 11 min read | 8.03K+ views
Share:
For working professionals
For fresh graduates
More
By Rohan Vats
Updated on Jul 21, 2025 | 11 min read | 8.03K+ views
Share:
Table of Contents
Did you know? By 2025, over 90% of Fortune 500 companies are expected to use Java for their software development needs, underscoring its dominance in the enterprise sector. |
Permutation in Java is the process of generating all possible ordered arrangements of a set of elements, where the order significantly affects the outcome. Understanding Java permutation techniques helps you tackle challenges in data structure problems, algorithm design, and combinatorial problems that require systematic exploration of sequences.
This blog explains the fundamentals of permutation in Java, practical approaches to creating permutations with examples.
A permutation in Java refers to an arrangement of objects in a specific order. For a particular set, the number of possible permutations is calculated based on how many objects are selected and their order of arrangement. When considering permutations, the order in which the objects appear is important. It is then used to calculate the number of ways to arrange or order items from a set.
To strengthen your skills in Java and other advanced technologies, check these leading programs:
Let’s break down permutation in Java mathematically to understand how it works.
Permutation is a way to find out how many different ways you can arrange a certain number of items when the order matters. It answers questions like: "How many ways can I arrange 3 letters?" or "How many ways can I line up 5 people?"
The formula to calculate permutations is:
Where,
Breaking down the formula:
Example: How many ways can you arrange the letters in “ABD”?
Using the formula:
P(3,3)=(3−3)!/3!=0!/3!
We know:
This means there are 6 different ways to arrange the letters A, B, and D. This concept helps solve many problems where the order of arrangement matters, such as passwords, seating arrangements, or scheduling tasks.
Software Development Courses to upskill
Explore Software Development Courses for Career Progression
Also Read: Permutation vs Combination: Difference between Permutation and Combination
Now that you’ve explored the basic concept of permutation in Java, let’s understand how to implement it using Java.
You can solve permutation problems using three common approaches: recursion with backtracking, iterative methods, and sometimes a combination of both. These approaches help you build a deeper understanding of algorithmic thinking and are often asked in coding interviews. Using Java, you'll write logic that generates all possible arrangements of a given set of elements, whether for characters, numbers, or objects.
Let’s look at the implementations of permutation in Java using different approaches.
This approach is widely used for its simplicity and clarity. Using recursion and backtracking, you systematically explore all possible arrangements of elements. It’s ideal for solving permutation problems in coding interviews and algorithmic challenges.
Sample Code:
import java.util.*;
public class PermutationRecursive {
public static void permute(String str, String result) {
if (str.length() == 0) {
System.out.println(result);
return;
}
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
String remaining = str.substring(0, i) + str.substring(i + 1);
permute(remaining, result + ch);
}
}
public static void main(String[] args) {
String input = "ABC";
permute(input, "");
}
}
Code Explanation:
Output:
ABC
ACB
BAC
BCA
CAB
CBA
Also Read: Permutation vs Combination: Discover the Crucial Differences Now!
This approach is known for its efficiency and structured process. Using Heap’s algorithm, you iteratively generate all possible permutations through smart in-place swaps. It’s a great fit for performance-critical tasks and understanding iterative logic in Java.
Sample Code:
public class PermutationIterative {
public static void heapPermutation(char[] arr, int size) {
if (size == 1) {
System.out.println(String.valueOf(arr));
return;
}
for (int i = 0; i < size; i++) {
heapPermutation(arr, size - 1);
if (size % 2 == 1) {
char temp = arr[0];
arr[0] = arr[size - 1];
arr[size - 1] = temp;
} else {
char temp = arr[i];
arr[i] = arr[size - 1];
arr[size - 1] = temp;
}
}
}
public static void main(String[] args) {
char[] input = {'A', 'B', 'C'};
heapPermutation(input, input.length);
}
}
Code Explanation:
Output:
ABC
BAC
CBA
BCA
CAB
ACB
This approach is efficient and systematic, particularly when generating permutations in sorted or dictionary order. By following a well-defined algorithm, you iterate through each possible arrangement without recursion. It's handy in problems that require the next immediate permutation or ordered output.
Sample Code:
import java.util.Arrays;
public class PermutationNext {
public static void main(String[] args) {
String input = "ABC";
char[] chars = input.toCharArray();
Arrays.sort(chars);
do {
System.out.println(String.valueOf(chars));
} while (nextPermutation(chars));
}
private static boolean nextPermutation(char[] arr) {
int i = arr.length - 2;
while (i >= 0 && arr[i] >= arr[i + 1]) i--;
if (i < 0) return false;
int j = arr.length - 1;
while (arr[j] <= arr[i]) j--;
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
Arrays.sort(arr, i + 1, arr.length);
return true;
}
}
Code Explanation:
Output:
ABC
ACB
BAC
BCA
CAB
CBA
Subscribe to upGrad's Newsletter
Join thousands of learners who receive useful tips
Now that you've learned how permutations work and how to implement them in Java, it's time to apply that knowledge to real-world challenges.
To truly master the concept, you need to solve problems that introduce complexity, such as handling duplicates, generating permutations for integers, or working with subsets. These problems test your Java skills but also help you think algorithmically and write optimized, interview-ready code.
Here are some classic and advanced permutation problems that you can try implementing in Java to enhance your coding skills.
In this example, you have to determine how many ways you can award the first and second prizes to six people. You have to find the permutations of 6 people taken 2 at a time. You can use the permutation formula to solve the problem.
Here, n = 6 (number of people) and r = 2 (prizes to be awarded).
Sample Code:
public class PermutationExample1 {
// Method to calculate permutations (nPr) of n items taken r at a time
public static int permutation(int n, int r) {
return factorial(n) / factorial(n - r); // P(n, r) = n! / (n - r)!
}
// Method to calculate factorial of a number
public static int factorial(int num) {
int result = 1;
for (int i = 1; i <= num; i++) {
result *= i;
}
return result;
}
public static void main(String[] args) {
int n = 6; // Total number of participants
int r = 2; // Number of prizes to be awarded
// Calculate and display the number of permutations (ways to award prizes)
int result = permutation(n, r);
System.out.println("Total ways to award first and second prize: " + result);
}
}
Code Explanation:
The Example class calculates the number of permutations (nPr) of n items taken r at a time, which is often used to determine the number of ways to award prizes in a competition.
Output:
Total ways to award first and second prize: 30
Also Read: 50 Java Projects With Source Code in 2025: From Beginner to Advanced
In this example, let's assume you are given a number n (for example, 3), and you want to find the permutations of a number greater than n (for instance, 5). This means you have to calculate the permutations of 5 items taken 3 at a time.
Sample Code:
public class PermutationExample2 {
// Method to calculate permutations (nPr)
public static int permutation(int n, int r) {
return factorial(n) / factorial(n - r);
}
// Method to calculate factorial
public static int factorial(int num) {
int result = 1;
for (int i = 1; i <= num; i++) {
result *= i;
}
return result;
}
public static void main(String[] args) {
int n = 5; // Total number of items
int r = 3; // Number of items to choose
// Calculate and display the number of permutations
int result = permutation(n, r);
System.out.println("Total permutations of " + n + " items taken " + r + " at a time: " + result);
}
}
Code Explanation:
The PermutationExample2 class calculates the number of permutations (nPr) of n items taken r at a time, which is useful for determining how many ways a subset of items can be chosen when the order matters.
Output:
Total permutations of 5 items taken 3 at a time: 60
Also Read: Top 135+ Java Interview Questions You Should Know in 2025
Permutations in Java help you build logic that handles complex arrangements, whether you're solving algorithmic problems, generating combinations, or designing smarter systems. From recursive methods to iterative logic, understanding how permutations work is key to becoming a stronger Java programmer.
To build confidence, apply these concepts by solving problems and coding challenges. Platforms like LeetCode and CodeChef are great for testing your problem-solving skills in these areas.
Many learners struggle to apply concepts like permutations in real code. upGrad’s software development courses help you build strong Java skills through hands-on projects and expert guidance. Here are some additional courses that will boost your programming language skills.
Feeling unsure about where to begin with your programming career? Connect with upGrad’s expert counselors or visit your nearest upGrad offline centre to explore a learning plan tailored to your goals. Transform your programming journey today with upGrad!
Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.
Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.
Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.
Reference:
https://www.netguru.com/blog/is-java-still-used-in-2025
The best method depends on the problem at hand. Recursive methods are easy to implement and work well for small datasets. However, for larger datasets or when avoiding duplicates is a concern, iterative and backtracking approaches are more efficient. These methods are faster and consume less memory when dealing with large input sizes.
Yes, Java provides built-in libraries like java.util.Collections and third-party libraries like Apache Commons Lang, which offer easy-to-use methods to generate permutations. These libraries simplify the process significantly by handling the internal logic, saving time and reducing the need for custom implementations.
You can generate permutations of numbers or any other data types by treating them as arrays or lists. Once the data is represented as an array or list, you can apply the same permutation algorithms, like recursion or iteration, to generate all possible permutations of the elements, just as you would with strings.
The easiest way is to use Java's built-in libraries such as java.util.Collections or Apache Commons Lang. These libraries offer pre-built methods for generating permutations, thereby eliminating the need to implement complex algorithms manually. They simplify the process and ensure that error-handling is taken care of automatically.
To generate permutations of a string in Java, first convert the string into a character array. Then, you can apply recursive or iterative permutation algorithms, such as backtracking or the next-permutation algorithm, to rearrange the characters and generate all possible permutations of the string.
To avoid duplicate permutations, first sort the string. Then, during the permutation generation, skip over repeated characters at the current recursion level to prevent processing the same character twice. This ensures that each generated permutation is unique, even when repeated characters are present in the input.
Permutation in Java accounts for the order of elements, meaning that different orderings of the same elements are considered distinct. Combinations, on the other hand, do not consider order; different orderings of the same set of elements are treated as the same. Permutations are valid when order matters, while combinations are used when order is irrelevant.
Backtracking is a technique where you explore all possible options and undo the last decision if it doesn't lead to a valid solution. In generating permutations, you try all character arrangements and backtrack when necessary, ensuring that each valid permutation is generated without duplication and in an efficient manner.
Generating permutations of large datasets can lead to performance issues due to the high time complexity (factorial growth) and high memory consumption, especially when using recursion. Recursive methods can also cause stack overflow for huge input sizes, while iterative methods may require more complex logic to manage memory efficiently.
To handle edge cases, ensure that your algorithm considers special cases such as empty strings, strings with a single character, and strings where all characters are the same. For empty or single-character strings, return the string itself. For strings with identical characters, avoid generating duplicate permutations by skipping over repeated characters during the permutation process.
Yes, permutation in Java can be adapted to handle duplicates, but it requires extra logic to avoid repeating the same arrangement. Common techniques include using a Set to track generated permutations or sorting the input and skipping over repeated elements during generation. This ensures that your output only contains unique permutations, which is especially useful in problems involving repeated characters or numbers.
408 articles published
Rohan Vats is a Senior Engineering Manager with over a decade of experience in building scalable frontend architectures and leading high-performing engineering teams. Holding a B.Tech in Computer Scie...
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources