Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

Permutations in Java: From Basic Concepts to Advanced Techniques and Debugging with Coding Examples

By Rohan Vats

Updated on Feb 03, 2025 | 21 min read

Share:

Permutation is a technique used to arrange a set of elements in a specific order, where the sequence of elements matters. This method is widely applied in various fields, such as memory management, cryptography, and gaming, that require the arrangement or rearrangement of data.

Understanding permutations will prepare you for advanced career opportunities in software development. Let’s dive in.

Understanding Permutations: An Overview of Basics

A permutation 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.

Permutation in mathematics is calculated using the following formula:

P ( n , r ) = n ! ( n - r ) !

Where, 

n! is the factors of n

r is the number of items to arrange

To understand the concept, consider the following example.

Example: Find the total number of permutations of the string "ABD".

Solution: The total number of distinct letters (n) is 3, and you want to arrange all 3 letters. Hence, r is also 3.

Inserting these values in the formula, you get:

P ( 3 , 3 ) = 3 ! ( 3 - 3 ) ! =   3 · 2 · 1 0 ! =   6 1 P ( 3 , 3 ) = 6

Hence, there are 6 possible ways to arrange the letters "A", "B", and "D".

Also Read: Permutation vs Combination: Difference between Permutation and Combination

Now that you’ve explored the mathematical concept of permutations, let’s examine the different types of permutations.

Types of Permutations

Permutation refers to different ways of arranging a set of objects. There are three main types of permutations: ordered permutations, unique permutations, and permutations with repetition. 

Let’s look at these three types in detail.

1. Ordered Permutations
Ordered permutations are those in which the arrangement of the objects is important. When calculating ordered permutations, each distinct arrangement of objects is considered different, even if the objects themselves are the same.

Example: For the set of letters "A", "B", and "C", the ordered permutations would be: ABC, ACB, BAC, BCA, CAB, CBA.

2. Unique Permutations
Unique permutations are used when there are repeated elements in the set. The focus is to find distinct arrangements by removing any duplicate arrangements due to the repetition of elements.

Example: Consider the set "AAB". The unique permutations would be AAB, ABA, BAA

3. Permutations with Repetition
Permutations with repetition occur when objects are repeated, but you are allowed to use the same objects multiple times in the arrangement. This is common in cases where you have multiple slots to fill and can use the same item more than once.

Example: For the set "A", "B", and "C", if you are allowed to repeat the elements and select 2 objects at a time, the permutations with repetition are AA, AB, AC, BA, BB, BC, CA, CB, CC.

Now that you’ve explored the basic concept of permutations and their types, let’s understand how to implement it using Java. 

Getting Started with Permutations in Java: Simplified

Before you start implementing permutations in Java, you need to set up a Java development environment, which will provide an efficient platform for writing, testing, and executing your code to implement permutations.

Here are the steps to setup a Java environment on your systems. 

1. Install Java Development Kit (JDK)

Visit the official website of Oracle and download the latest version of JDK (Java Development Kit). You can follow the installation instructions based on your operating system (Windows, macOS, or Linux).

2. Set up Java Environment Variables

Once Java is installed, you must set up environment variables to allow Java to be accessed from the command line. There are different ways for different operating systems.

  • Windows

Go to Control Panel > System > Advanced System Settings > Environment Variables, and set the JAVA_HOME variable to your Java installation path (e.g., C:\Program Files\Java\jdk-11).

  • Linux/MacOS

Open your terminal and add the following to your shell configuration file (~/.bashrc or ~/.zshrc):

export JAVA_HOME=$(/usr/libexec/java_home)
export PATH=$JAVA_HOME/bin:$PATH

Run the command, run source ~/.bashrc or source ~/.zshrc

3. Install an Integrated Development Environment (IDE)

You need to download an IDE to write your Java code. Popular Java IDEs include IntelliJ IDEA, NetBeans, and Eclipse. After you download and install your IDE, configure it to use the installed JDK.

Also Read: IntelliJ IDEA vs. Eclipse: The Holy War!

4. Test Your Setup

To confirm that Java is set up properly, open a terminal/command prompt and type:

java -version

The output will display the version of Java.

Now that you’ve explored ways to install Java in your systems, you need to understand certain key approaches before writing codes for implementing permutations. Recursion, backtracking, and iterative methods are the three techniques used.

Here are the three main techniques for permutation in Java.

1. Recursion

Recursion is a technique where a function calls itself to solve a smaller instance of the problem. In the case of permutations, you can use recursion to fix one element and recursively find the permutations of the remaining elements.

Approach:

  • Base Case: When the string length is 1, return the string as a valid permutation.
  • Recursive Case: For each character in the string, swap it with the first character and recursively generate permutations of the rest.

2. Backtracking

Backtracking is an extension of recursion that tries to build a solution incrementally. If a solution cannot be completed, it undoes the last choice and tries a different one. The backtracking technique is essentially a depth-first search, where you explore all the possible paths but backtrack when needed.

Approach:

  • Explore a character's possible positions.
  • After each recursive call, backtrack by swapping the characters back to their original position.

3. Iterative Approach

An iterative approach generates all possible permutations using loops. While recursion is more suitable for this type of problem, an iterative approach is also efficient and can be implemented using algorithms like Heap's algorithm.

Approach:

The algorithm systematically generates the next permutation by swapping elements and moving to the next set of choices.

Also Read: Iterator in Java: Understanding the Fundamentals of Java Iterator

Now that you've explored the three different approaches to solving the permutation problem, let's understand how these techniques can help you solve permutation in Java.

Permutation of Strings in Java: Explained 

You can generate a permutation of string in Java using different approaches such as recursion, backtracking, and iterative methods. The methods allow you to design algorithms that are efficient and computationally inexpensive.

Here's how the permutation of string in Java is solved using different approaches.

Permutations of Strings Using Recursion

Recursion is a method where a function calls itself to solve a smaller instance of the problem. For string permutations, the logic is to fix one character at a time and recursively generate permutations of the remaining characters. 

The process continues until the string is reduced to a single character, at which point you can directly return the permutation.

Steps involved:

  • Base Case: If the string is of length 1, return the string.
  • Recursive Case: For each character in the string, swap it with the first character and recursively find permutations of the rest of the string.
  • Backtrack: After each recursive call, undo the swap (backtrack) to restore the original string and continue generating other permutations.

Example of implementation using ABC string:

1. Start with "ABC":

Fix the first character "A". Now permute the rest: "BC".

2. Permuting "BC":

Fix "B", permute "C" (only one character, so "BC" is a valid permutation).

Now, backtrack and swap "B" and "C" → "CB".

3. Permuting "CB":

Fix "C", permute "B" (only one character, so "CB" is a valid permutation).

Backtrack: swap "C" and "B" → "BC" (restore original order).

4. Back to "ABC":

Now swap "A" and "B" → "BAC". Permute the remaining "AC".

5. Permuting "AC":

Fix "A", permute "C" → "AC".

Backtrack: swap "A" and "C" → "CA".

6. Permuting "CA":

Fix "C", permute "A" → "CA".

Backtrack: swap "C" and "A" → "AC" (restore original order).

7. Back to "ABC":

Now swap "A" and "C" → "CAB". Permute the remaining "AB".

8. Permuting "AB":

Fix "A", permute "B" → "AB".

Backtrack: swap "A" and "B" → "BA".

9. Permuting "BA":

Fix "B", permute "A" → "BA".

Backtrack: swap "B" and "A" → "AB" (restore original order).

Code Snippet:

import java.util.ArrayList;
import java.util.List;

public class StringPermutations {

    // Function to generate permutations
    public static void permute(String str, int left, int right, List<String> result) {
        // Base case: if left index equals right, add the permutation
        if (left == right) {
            result.add(str);
        } else {
            // Recursive case: swap each character and recurse
            for (int i = left; i <= right; i++) {
                str = swap(str, left, i);  // Swap characters
                permute(str, left + 1, right, result);  // Recurse
                str = swap(str, left, i);  // Backtrack
            }
        }
    }

    // Helper function to swap characters in a string
    public static String swap(String str, int i, int j) {
        char[] charArray = str.toCharArray();
        char temp = charArray[i];
        charArray[i] = charArray[j];
        charArray[j] = temp;
        return new String(charArray);
    }

    public static void main(String[] args) {
        String str = "ABC";
        List<String> result = new ArrayList<>();
        permute(str, 0, str.length() - 1, result);

        // Print all permutations
        for (String perm : result) {
            System.out.println(perm);
        }
    }
}

Output:

ABC
ACB
BAC
BCA
CAB
CBA

Backtracking Approach to Permutations

In the backtracking approach, you have to build the solution incrementally, exploring each possibility. If a solution turns out to be incorrect, you need to backtrack to a previous step and try a different approach. 

In the context of permutations, backtracking is used to try all possible swaps and generate permutations.

Step involved:

  • Start with the first element: Fix one character and swap it with other characters.
  • Recursion: Recursively swap the remaining characters to generate all possible combinations.
  • Backtrack: If no solution is found or all possibilities are exhausted, undo the swap to explore other possible solutions.

Example of implementation using ABC string:

1. Start with "ABC":

Fix the first character, "A". Now permute the rest: "BC".

2. Permute "BC":

Swap "B" and "B" → "ABC" → Add to result.

Backtrack: Swap "B" and "B" back → "ABC".

3. Permute "CB" (Swap "C" with "B"):

Swap "C" and "B" → "ACB" → Add to result.

Backtrack: Swap "C" and "B" back → "ABC".

4. Backtrack to "ABC":

Swap "B" and "A" → "BAC". Permute the remaining "AC".

5. Permute "AC":

Swap "A" and "A" → "BAC" → Add to result.

Backtrack: Swap "A" and "A" back → "BAC".

6. Permute "CA" (Swap "C" with "A"):

Swap "C" and "A" → "BCA" → Add to result.

Backtrack: Swap "C" and "A" back → "BAC".

7. Backtrack to "ABC":

Swap "C" and "A" → "CAB". Permute the remaining "AB".

8. Permute "AB":

Swap "A" and "A" → "CAB" → Add to result.

Backtrack: Swap "A" and "A" back → "CAB".

9. Permute "BA" (Swap "B" with "A"):

Swap "B" and "A" → "CBA" → Add to result.

Backtrack: Swap "B" and "A" back → "CAB"

Code Snippet:

import java.util.ArrayList;
import java.util.List;

public class BacktrackingPermutations {

    // Function to generate permutations using backtracking
    public static void permuteBacktracking(String str, int start, int end, List<String> result) {
        // Base case: If we have a valid permutation, add it to the result list
        if (start == end) {
            result.add(str);
            return;
        }

        // Recursive case: Try every character in the string
        for (int i = start; i <= end; i++) {
            // Swap characters at positions 'start' and 'i'
            str = swap(str, start, i);
            // Recur for the next position
            permuteBacktracking(str, start + 1, end, result);
            // Backtrack by swapping back
            str = swap(str, start, i);
        }
    }

    // Helper function to swap characters in the string
    public static String swap(String str, int i, int j) {
        char[] charArray = str.toCharArray();
        char temp = charArray[i];
        charArray[i] = charArray[j];
        charArray[j] = temp;
        return new String(charArray);
    }

    public static void main(String[] args) {
        String str = "ABC";
        List<String> result = new ArrayList<>();
        permuteBacktracking(str, 0, str.length() - 1, result);

        // Print all permutations
        for (String perm : result) {
            System.out.println(perm);
        }
    }
}

Output:

ABC
ACB
BAC
BCA
CAB
CBA

Iterative Method for String Permutations

The iterative method generates permutations without recursion, typically by iterating over all possible combinations. One common algorithm for this is Heap's algorithm, which can generate permutations iteratively.

Steps in implementation:

  • Sort the string: Start by sorting the string in lexicographical order.
  • Generate permutations: Use loops to swap elements and generate all possible permutations.
  • Stop when no further permutations are possible: Continue swapping until all permutations are generated.

Example of implementation using ABC string:

1. Start with the sorted string "ABC" (lexicographically smallest permutation):

  • Print: "ABC"

2. Find the next permutation:

  • Identify the largest index i such that arr[i] < arr[i + 1]. Here i = 1 (B < C).
  • Find the largest j such that arr[j] > arr[i]. Here j = 2 (C > B).
  • Swap arr[i] and arr[j] → "ACB".
  • Reverse the substring after i (no change needed).
  • Print: "ACB".

3. Find the next permutation:

  • Identify i = 0 (A < C).
  • Find j = 2 (C > A).
  • Swap arr[i] and arr[j] → "CBA".
  • Reverse the substring after i → "BCA".
  • Print: "BCA".

4. Find the next permutation:

  • Identify i = 1 (B < C).
  • Find j = 2 (C > B).
  • Swap arr[i] and arr[j] → "CAB".
  • Reverse the substring after i → "CBA".
  • Print: "CBA".

Code Snippet:

import java.util.Arrays;

public class IterativePermutations {

    // Function to print all permutations of the string using the iterative approach
    public static void printPermutations(String str) {
        // Convert string to character array
        char[] arr = str.toCharArray();
        Arrays.sort(arr); // Sort the array to generate permutations in lexicographical order
        
        while (true) {
            System.out.println(new String(arr));
            int i = arr.length - 1;
            
            // Find the first element that is smaller than its next element
            while (i > 0 && arr[i - 1] >= arr[i]) {
                i--;
            }
            
            if (i <= 0) {
                break; // All permutations have been generated
            }
            
            int j = arr.length - 1;
            // Find the element just larger than arr[i-1]
            while (arr[j] <= arr[i - 1]) {
                j--;
            }
            
            // Swap arr[i-1] and arr[j]
            char temp = arr[i - 1];
            arr[i - 1] = arr[j];
            arr[j] = temp;
            
            // Reverse the elements from i to the end
            j = arr.length - 1;
            while (i < j) {
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
                i++;
                j--;
            }
        }
    }

    public static void main(String[] args) {
        String str = "ABC";
        printPermutations(str);
    }
}

Output:

ABC
ACB
BAC
BCA
CAB
CBA

Now that you’ve seen how you implement the different approaches to solve permutation of string in Java, let’s implement some examples of permutation code in Java.

Permutation Code in Java: Step-by-Step Implementation with Examples

Java allows you to solve permutation problems using either of the three approaches that you have explored in the previous section. However, the recursive approach is considered to be the most suitable to handle strings due to its ability to check all the possible conditions.

Here are three different examples of implementing permutation code in Java.

Example 1: There are six people participating in a skit. In how many ways first and the second prize can be awarded?

In this example, you have to determine how many ways you can award the first and second prize to six people. You have to find the permutations of 6 people taken 2 at a time.

You can use the following formula to solve the problem.

P ( n , r ) = n ! ( n - r ) !

Here, n = 6 (number of people) and r = 2 (prizes to be awarded).

Inserting these values in the formula, you get:

P ( 6 , 2 ) = 6 ! ( 6 - 2 ) ! =   6 · 5 · 4 · 3 · 2 · 1 4 · 3 · 2 · 1 =   30 1 P ( 6 , 2 ) = 30

Implementation in Java:

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);
    }
}

Output:

Total ways to award first and second prize: 30

Example 2: Find the permutation of a number n greater than the number itself.

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 we are you have to calculate the permutations of 5 items taken 3 at a time.

Using the permutation formula, you get the following:

P ( 5 , 3 ) = 5 ! ( 5 - 3 ) ! =   5 · 4 · 3 · 2 · 1 2 · 1 =   60 P ( 6 , 2 ) = 30

Implementation using Java:

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);
    }
}

Output:

Total permutations of 5 items taken 3 at a time: 60

Example 3: Find all the permutations of a string in Java

In this example, you will have to find all possible permutations of the string "ABC" using recursion. This is a classic permutation problem where you have to swap characters and recurse to explore all possible combinations. The logic of solving permutation in Java using recursion has already been discussed.

Implementation using Java:

import java.util.ArrayList;
import java.util.List;

public class StringPermutations {

    // Method to generate all permutations of a string using recursion
    public static void permute(String str, int left, int right, List<String> result) {
        if (left == right) {
            result.add(str);  // Add the permutation to the result
        } else {
            for (int i = left; i <= right; i++) {
                str = swap(str, left, i);  // Swap characters
                permute(str, left + 1, right, result);  // Recurse for the next position
                str = swap(str, left, i);  // Backtrack (restore the string)
            }
        }
    }

    // Helper method to swap characters in the string
    private static String swap(String str, int i, int j) {
        char[] arr = str.toCharArray();
        char temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
        return new String(arr);
    }

    public static void main(String[] args) {
        String str = "ABC";  // The string for which we need to find permutations
        List<String> result = new ArrayList<>();  // List to store permutations

        // Call the permute method
        permute(str, 0, str.length() - 1, result);

        // Display the result
        System.out.println("All permutations of the string \"" + str + "\":");
        for (String permutation : result) {
            System.out.println(permutation);
        }
    }
}

Output:

All permutations of the string "ABC":
ABC
ACB
BAC
BCA
CAB
CBA

Although you've implemented the permutation code in Java, it can be optimized for better memory and time efficiency.

Here’s how you can optimize your code.

  • Avoid Redundant Calculations: In recursive problems, make sure that no redundant calculations are made by storing intermediate results or reducing the size of sub-problems.
  • Memoization: For repeated permutations or factorial calculations, use memoization to store previously computed results and reuse them when needed.
  • Iterative Solution: For simpler cases, use an iterative approach instead of recursion, as it could be more efficient and easier to understand.
  • StringBuilder for Swapping: Use StringBuilder instead of String when manipulating characters, as string creates a new object each time it is modified.
  • Prune Unnecessary Branches: In the backtracking approach, avoid exploring branches that are not needed by pruning the search space early.

Now that you’ve looked at some tips to optimize your code for permutation in Java, let’s explore applications of permutation in the real world. 

Practical Applications of Permutations in Real Scenarios

Permutations are important in real-world scenarios where the arrangement of elements plays a critical role in decision-making or optimization. From cryptography in cybersecurity to gaming, permutations help you solve complex problems by exploring all possible arrangements or combinations.

Here are the applications of permutation in real life.

Where Permutations Are Used in Real Life

Applications of permutations in real life range from data encryption and password generation to gaming and optimization. Here are its uses in real-life scenarios.

Use Case Description
Data Encryption Encryption algorithms like AES and RSA use permutations to shuffle data before it’s transmitted.
Password Generation Permutations help generate secure passwords by creating a variety of possible combinations of characters, numbers, and symbols.
Captcha Systems Permutations of letters and numbers in captchas create challenges for bots, ensuring that only humans can pass the verification process.
Security Tokens For two-factor authentication (2FA), systems generate secure, random tokens through permutation techniques to prevent unauthorized access.
Cryptographic Hash Functions Hash functions like SHA-256 use permutations to scramble data, producing an output that acts as a unique fingerprint of the original input.

While permutations have wider applications in the real world, they are specifically preferred in the software development process for purposes like game design and optimization. Let’s look at the applications in detail.

Applications in Software Development

Permutations are used extensively for optimizing algorithms, improving game design, and enhancing simulations.

Here are the applications of permutations in software development.

Use Case Description
Simulations  Permutations are used in simulations that require testing different combinations of inputs to predict various outcomes (e.g., weather modeling).
Gaming Permutations are used in games such as card games, board games, or puzzle games (like Sudoku) to generate random sequences or configurations.
Combinatorial Optimization In optimization problems like the Traveling Salesman Problem (TSP), permutations are applied to find the best possible arrangement of items to minimize cost or distance.
Machine Learning  Hyperparameter optimization in machine learning algorithms generates permutations of various parameter combinations to fine-tune models. 
Genetic Algorithms Evolutionary algorithms use permutations of genetic sequences to find optimal solutions for problems such as scheduling or resource allocation.

Now that you’ve explored the applications of permutations in the real world and software development, let’s explore some advanced concepts related to this topic.

Exploring Advanced Topics in Permutations

Advanced concepts in permutations will be useful while dealing with large data sets, duplicate elements, or optimizing performance. With proper permutations, you can ensure that algorithms scale well with increasing data size.

Here’s how you can tackle duplicate characters in permutations.

Handling Duplicate Characters in Permutations

When dealing with permutations of strings containing repeated characters, generating duplicate results can be a major issue. 

Without addressing this, the number of permutations can increase exponentially, leading to redundant computations. 

Here are the techniques to handle duplicate characters.

  • Sorting the Array: Duplicate permutations can be easily avoided by sorting the array and ensuring that each element is processed in a unique order.
  • Backtracking: While generating permutations, skip repeated elements that have already been processed at the current level of recursion.
  • Hashing or Set Data Structures: Use a hash set to store permutations and prevent adding duplicate results.

Now that you know how to handle duplicate characters in permutations, let’s explore different ways to handle large datasets.

Permutations for Large Datasets

Handling permutations for large data sets needs careful optimization to ensure that performance is not affected as the data size increases. 

Here’s how you can handle large datasets.

  • Memoization: Store already computed permutations to avoid recalculating them repeatedly, thus improving time complexity.
  • Iterative Methods: Consider using iterative methods to reduce memory overhead and improve efficiency for large data sets.
  • Dynamic Programming: By breaking down the problem into subproblems, dynamic programming can generate permutations more efficiently.

Now that you’ve learned how to handle challenges like large datasets and duplicate characters, it's important to choose the right approach for solving permutation in Java. Let's compare the three techniques.

Comparison of Different Permutation Methods

To choose the best approach to solve permutation in Java, you need to consider factors like time and memory consumption.

Here’s the difference between the three approaches to solving permutation in Java.

Method Approach  Advantage  Disadvantage 
Recursive  Uses a divide-and-conquer approach Easy to implement High memory usage and slower for large datasets.
Iterative Uses loops and iterative constructs.  Memory efficiency for large datasets. More complex to implement and less suitable
Library-Based Uses built-in functions (e.g., itertools.permutations in Python) Simplifies implementation by built-in error-handling  Less flexibility for customization and learning

The comparison between different approaches will help you choose the best one for implementation. However, you may encounter challenges while implementing permutation in Java. 

Let’s explore some tips to handle these errors effectively.

Avoiding Common Errors and Troubleshooting in Permutations

When implementing permutation algorithms, especially recursive, you may encounter problems related to infinite loops and missed edge cases. By understanding these challenges and solutions, you can ensure the correctness of your permutation code.

Here are some common errors and tips to avoid them.

1. Debugging for Recursive Methods

  • Trace Recursion Calls: Use print statements or debugging tools to trace the function calls to understand how the recursion progresses and where it might be going wrong.
  • Check Base Case: Ensure your base case is well-defined. If the base case is incorrectly specified, the recursion will lead to infinite calls.
  • Limit Recursion Depth: For large problem spaces, use iterative methods or adjust the problem size to keep the depth manageable.

2. Handling Stack Overflow Errors in Recursion

  • Optimize Recursion: Use tail recursion or switch to an iterative approach to reduce stack depth.
  • Increase Stack Size: In Java, you can increase the stack size with the -Xss option to address overflow errors.
  • Limit Recursive Calls: Check the state to ensure it won't recurse unnecessarily while dealing with large datasets.

3. Mistakes in Recursion Implementation

  • Infinite Loops: This occurs when the base case isn't properly defined. Ensure that each recursive call moves toward the base case.
  • Incorrect Termination Condition: If the base case is defined incorrectly, the recursion will terminate too early, giving incorrect permutations.
  • Incorrectly Handling Duplicates: In cases where duplicate elements exist, ensure that your recursive algorithm skips repeated elements to avoid generating duplicate permutations.

4. Common Logical Errors

  • Misplacing Recursive Calls: In some recursive implementations, the order of recursive calls can impact the output. Ensure that elements are placed and removed correctly in each recursive step.
  • Skipping Edge Cases: Missing edge cases like empty strings or arrays can give incorrect outputs. Always consider edge cases in your algorithm.
  • Mismanaging Data Structures: In recursive algorithms, mismanagement of data structures like lists, arrays, or sets can lead to incorrect results.

Here are some common problems you may face while implementing permutation in Java. To avoid these issues, it's important to deepen your understanding of Java. Let’s explore how to do that.

How Can upGrad Help You Advance Your Career in Java Development?

The application of permutation in Java will help you solve complex problems in fields like cybersecurity and memory management. Understanding how to implement permutations, along with related techniques like backtracking and dynamic programming, will improve your ability to address real-world computational challenges.

To deepen your understanding of Java, you can explore specialized courses from upGrad. These courses will help you build a strong foundation and advance your skills for professional growth in software development.

Here are some courses that will boost your programming language skills.

Do you need help deciding which courses can help you in Java programming? Contact upGrad for personalized counseling and valuable insights. For more details, you can also visit your nearest upGrad offline center.

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.

Frequently Asked Questions

1. What is the Best Method to Generate Permutation in Java?

2. Can I Use Java Libraries for Permutations?

3. How to Generate Permutations of Numbers or Other Data Types?

4. What is the easiest way to generate permutation in Java?

5. How can I generate permutations of a string in Java?

6. How do I avoid duplicate permutations for strings with repeating characters?

7. What is the difference between permutations and combinations in Java?

8. What is a recursive approach to generating permutations?

9. What is backtracking, and how is it used for permutation in Java?

10. What are the performance concerns when generating large permutations?

11. How do I handle edge cases in permutation generation?

Rohan Vats

421 articles published

Get Free Consultation

+91

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

View Program

Top Resources

RecommendedPrograms

SuggestedBlogs