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:

Java Program to Test Using DFS Whether a Directed Graph is Strongly Connected or Not
Converting a Stack Trace to a String in Java
Python String title()
Converting Strings to Enums in Java
Pagination and Sorting using Spring Data JPA
Spring Boot - Application Properties
Java Program to Generate Random Numbers Using Probability Distribution Function
Java Program to Describe the Representation of Graph using Incidence Matrix
Giới thiệu Google Guice – Aspect Oriented Programming (AOP)
Jackson – JsonMappingException (No serializer found for class)
HttpAsyncClient Tutorial
Tổng quan về ngôn ngữ lập trình java
Convert Character Array to String in Java
Copy a List to Another List in Java
Một số ký tự đặc biệt trong Java
Java Program to Implement Wagner and Fisher Algorithm for online String Matching
Python Program to Check Whether a String is Palindrome or Not
Java Program to Implement Threaded Binary Tree
ETL with Spring Cloud Data Flow
Getting Started with Stream Processing with Spring Cloud Data Flow
Java Program to Implement Hash Tables with Quadratic Probing
Hướng dẫn Java Design Pattern – DAO
Java Program to Implement Heap
Java Program to Implement Queue
Java Program to Check Whether an Input Binary Tree is the Sub Tree of the Binary Tree
Java Program to Check Whether an Undirected Graph Contains a Eulerian Path
An Intro to Spring Cloud Task
Spring Security Login Page with React
The Spring @Controller and @RestController Annotations
Java – Delete a File
Batch Processing with Spring Cloud Data Flow
Hướng dẫn Java Design Pattern – Interpreter