Java Program to Permute All Letters of an Input String

This is the Java Program to Print all Possible Permutations of a String.Problem Description

Given a string, print all the different words that can be formed by permuting its letters.

Example:
String str =”ABC”;

Output =
ABC
ACB
BAC
BCA
CAB
CBC

Problem Solution

The solution to this problem is based on the programming paradigm backtracking. The idea used here keep a character constant and find the permutations of the remaining (n-1) characters. However, in case of strings having repeated characters, some strings are printed repeatedly.

Program/Source Code

Here is the source code of the Java Program to Print all Possible Permutations of a String. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.

//Java Program to Print all Possible Permutations of a String
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
 
public class PermutationsOfAString {
    // Function to swap two characters
    static String swap(String str, int i, int j){
        char ch;
        char[] array = str.toCharArray();
        ch = array[i];
        array[i] = array[j];
        array[j] = ch;
        return String.valueOf(array);
    }
    // Function to print all the permutations of the string
    static void permute(String str,int low,int high){
        if(low == high)
            System.out.println(str);
 
        int i;
        for(i = low; i<=high; i++){
            str = swap(str,low,i);
            permute(str, low+1,high);
            str = swap(str,low,i);
        }
    }
    // Function to read user input
    public static void main(String[] args) {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str;
        System.out.println("Enter a string");
        try{
            str = br.readLine();
        }catch (Exception e){
            System.out.println("An error occurred");
            return;
        }
        System.out.println("All the possible permutations of "+ str + "are");
        permute(str,0,str.length()-1);
    }
}

Program Explanation

1. In function swap(), firstly the string is converted into a character array.
2. Secondly, the characters at ith and jth indexes are interchanged and the character array is finally converted back to string.
3. In function permute(), firstly the low and high indexes are compared if(low == high), to see if they are equal.
4. If it is, that means we are processing the last character and no more permutations can be generated. So the string is printed.
5. The loop for(i = low; i<=high; i++) is used to generate all the permutations of the string.
6. Firstly, the character at low and i are swapped using swap(str, low, i). Then keeping this character constant, all the other permutations are generated using permute(arr,low+1, high).
7. Finally, the initially swapped character is swapped back to its original position.

Time Complexity: O(n*(n!) ) where n is the length of the string.

Runtime Test Cases

Case 1 (Simple Test Case):
 
Enter a string
ABC
All the possible permutations of ABC are
ABC
ACB
BAC
BCA
CBA
CAB
 
Case 2 (Simple Test Case - another example):
 
Enter a string
ABCA
All the possible permutations of ABCA are
ABCA
ABAC
ACBA
ACAB
AACB
AABC
BACA
BAAC
BCAA
BCAA
BACA
BAAC
CBAA
CBAA
CABA
CAAB
CAAB
CABA
ABCA
ABAC
ACBA
ACAB
AACB
AABC

Related posts:

Spring Data MongoDB – Indexes, Annotations and Converters
Java Program to Implement Min Heap
Spring Security – security none, filters none, access permitAll
Guide To CompletableFuture
Java Program to Implement Fermat Primality Test Algorithm
Concurrent Test Execution in Spring 5
Java Program to Check Whether an Undirected Graph Contains a Eulerian Cycle
Java Program to Implement Selection Sort
Xử lý ngoại lệ đối với trường hợp ghi đè phương thức trong java
Java Program to Implement Knight’s Tour Problem
Java Program to Perform LU Decomposition of any Matrix
Deque và ArrayDeque trong Java
A Guide to LinkedHashMap in Java
Testing an OAuth Secured API with Spring MVC
Tạo ứng dụng Java RESTful Client không sử dụng 3rd party libraries
Spring Boot With H2 Database
Java Program to Implement Floyd-Warshall Algorithm
OAuth2 for a Spring REST API – Handle the Refresh Token in Angular
Java String to InputStream
Java Collections Interview Questions
Prevent Brute Force Authentication Attempts with Spring Security
Xử lý ngoại lệ trong Java (Exception Handling)
A Guide to Spring Cloud Netflix – Hystrix
Quick Guide to java.lang.System
Hướng dẫn Java Design Pattern – Object Pool
Java Program to Apply Above-Below-on Test to Find the Position of a Point with respect to a Line
Java Program to Implement Euclid GCD Algorithm
Java Program to Check if any Graph is Possible to be Constructed for a Given Degree Sequence
Java 8 and Infinite Streams
Java Program to Implement the Edmond’s Algorithm for Maximum Cardinality Matching
Guide to Java 8’s Collectors
Java Web Services – Jersey JAX-RS – REST và sử dụng REST API testing tools với Postman