×

Java Program to Print Permutations of String

A string is given and you need to print all the possible ways for that string. Permutation is arranging the characters of a string to get outputs from the given string.

For example let ‘rat’ be the string and the list of all possible permutations for string are:

  1. rat
  2. art
  3. tar
  4. rta
  5. tra
  6. atr

In order to solve these type of problems first we need to learn backtracking algorithm.

Backtracking Algorithm

Algorithm

1.Establish a string.

2.Fix one character, then switch the others.

3.For the remaining characters, call permutationFunction().

4.Go back and switch the characters once again.

Java Program To Print Permutations Of String

Procedure

  1. Replace the rest of the characters with the character in the first position after fixing the first character. Similar to ABC, the first iteration results in the formation of three strings: ABC, BAC, and CBA by replacing A with A, B, and C, respectively. For the remaining characters, repeat step 1 by fixing the second character B and so forth.
  2. Switch again to return to your original position. For instance, starting with ABC, we would create ABC by adjusting B once more before going back and switching B and C. We now have ABC and ACB.
  3. Repeat these processes for BAC and CBA to obtain all possible combinations.

If repetition is allowed we can use recursion method to get the output

Repetition- Repeating same strings in the output

Recursion Method 1

In this method the function is called recursively until the string passed gets empty (termination condition). Using this method we will get repeated permutations of the string.

Java program to print all the permutations of the given string

public class Main {
static void printStrings(String str, String ans)
{
// If string is empty
if (str.length() == 0) {
System.out.println(ans + " ");
return;
}
for (int i = 0; i < str.length(); i++) {

char ch = str.charAt(i);
String ros = str.substring(0, i) +str.substring(i + 1);
// Calling the function recursively
printStrings(ros, ans + ch);
}
}// printStrings
//Main method
public static void main(String[] args)
{
String s = "abb";
printStrings(s, "");
} 
}//main

Output

Java Program To Print Permutations Of String

Explanation

In the program above, we are calling the function called "printStrings" with the string "abb" and we are supplying another empty string as a parameter to append the string's remaining characters. The function ends by producing an empty string as output and the programme is ended if the string is empty. Using a for loop, we will go through the string, adding each additional character apart from the one at position I and calling the function repeatedly until the string is empty.

Recursion Method 2

To avoid the repetitions of the string we will use another recursion method.

Program to print all different permutations of string

// Java program to print all the permutations of the given string
public class Main {
    static void Permutations(String s1,String ans)
    {
        if (s1.length() == 0) {
            System.out.println(ans + " ");
            return;
        }
        boolean a[] = new boolean[26];
        for (int i = 0; i < s1.length(); i++) {
            char c = s1.charAt(i);
            String ros = s1.substring(0, i) +s1.substring(i + 1);
            if (a[c - 'a'] == false)
                Permutations(ros, ans + c);
            a[c- 'a'] = true;
        }
    }
    public static void main(String[] args)
    {
        String s = "java";
        Permutations(s,"");
    }
}

Output

Java Program To Print Permutations Of String

Explanation

Make a 26-character long Boolean array that tracks the character being used. The recursive call will be made if the character hasn't been utilised. If not, don't place any calls. When the given string is empty, the sentence will end.

3.Iterative Approach: Using Collection

import java.util.ArrayList;
import java.util.List;
 
class Main
{
    public static void Permutations(String s)
    {
        if (s == null || s.length() == 0) 
        {
            return;
        }
        List<String> result = new ArrayList<>();
        result.add(String.valueOf(s.charAt(0)));
        for (int i = 1; i < s.length(); i++)
        {
            for (int j = result.size() - 1; j >= 0 ; j--)
            {
                String s1 = result.remove(j);
                for (int k = 0; k <= s1.length(); k++)
                {
                    result.add(s1.substring(0, k) + s.charAt(i) + s1.substring(k));
                }
            }
        }
        System.out.println(result);
    }
    public static void main(String[] args)
    {
        String string = "QWE";
        Permutations(string);
    }
}

Output

Java Program To Print Permutations Of String

Related Topics

Set Value to Enum in Java

In this article, you will be acknowledged about Enum in java. Most importantly you will learn how to set value to Enum or how to practically customize a value to...

3 minutes read.

Java List Interface

List interface is used when we have to order a collection which contains duplicate entries. Like an array, the elements of its implementation classes are retrieved and inserted at a...

2 minutes read.

Java vs Dot Net

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

3 minutes read.

Java Full Stack

A person who can create both the front end and back end of an application is a full-stack developer. In essence, the term "Java full-stack" refers to a web developer...

9 minutes read.

Grepcode Java util date

What is java.util.Date Class? The date and time in Java are provided through the java.util.Date class. If you imported java.util, it could be helpful. Use the Java.util.Date class to implement this class...

4 minutes read.

Java Integer numberOfTrailingZeros() method

The numberOfTrailingZeros()  method of Java Integer class returns the total number of zero bits following the lowest-order one-bit in the 2’s complement binary representation of the specified int value. Syntax public static...

1 minute read.

Java instance variable

An instance in object-oriented programming (OOP) is a particular implementation of any object. Each realized version of an item, which might vary in several ways, is an instance. Instantiation is...

3 minutes read.

How to Convert char to int in Java

How to Convert char to int in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

3 minutes read.

What is String in Java?

What is String in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a Java...

4 minutes read.

Banking Application in Java

JDBC (Java Database Connectivity), which provides an API to connect to, execute, and fetch data from any databases, can be used to handle transactions in Java. There are several factors...

7 minutes read.

Best Java IDE

Applications for desktop, workplace, smartphone, and the internet can be created using Java, one of the most popular programming languages. Java will undoubtedly be a popular programming language for so...

5 minutes read.

Java.sql.Time Format

In JDBC API as a cover aroundjava.util.Date that handles SQL-specific requirements we use the java.sql.Time. The java.sql.Time extends java.util.Date class. To represent SQL TIME, without a date this class is...

6 minutes read.

Java Linters

When it comes to programming, everyone makes mistakes. Errors are bad for developers since they are difficult to handle. But handling as many as possible errors will bring out the...

6 minutes read.

JRE (Java Runtime Environment)

JRE is an installation package that provides an environment to run the Java program on any Operating System. It does not deal with the development process of any application. It is a part...

2 minutes read.

Program to Reverse a Number in Java

In order to reverse a number, the digit in the first place must be swapped with the digit in the final position, the second digit with the second-to-last digit, and...

3 minutes read.

How to Return Value from Lambda Expression Java?

What is Lambda Expression in Java? In Java 8, Lambda Expressions were introduced.A lambda expression is a brief section of code that accepts input and outputs a value. Similar to methods,...

4 minutes read.

Java For Keyword

For as a keyword in java: When we need to run a set of statements repeatedly in Java, we use loops. The Java for loop offers a clear way to express...

4 minutes read.

Object class in Java

In Java, a class is a file containing the Java byte code. It can essentially specifically be executed on the JVM (Java Virtual Machine), fairly significant. The JVM mostly generally...

6 minutes read.

Java Integer signum() method

The signum() method of Java Integer class returns the signum function of the specified int value. Syntax public static int signum (int i)  Parameters The parameter ‘i’ represents the value whose signum is to...

1 minute read.

Dutch National Flag Problem in Java

Dutch National Flag (DNF) is a programming issue that Edsger Dijkstra put up. The white, red, and blue hues make up the Dutch flag. The goal is to haphazardly set...

6 minutes read.