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:

Giới thiệu Design Patterns
Hướng dẫn Java Design Pattern – Service Locator
Base64 encoding và decoding trong Java 8
Convert String to Byte Array and Reverse in Java
Quick Guide on Loading Initial Data with Spring Boot
Giới thiệu Java Service Provider Interface (SPI) – Tạo các ứng dụng Java dễ mở rộng
Spring Boot - Rest Template
A Guide to the Java LinkedList
Java Program to Implement the Bin Packing Algorithm
Java Program to Implement LinkedList API
Anonymous Classes in Java
Understanding Memory Leaks in Java
Spring Boot - Servlet Filter
ThreadPoolTaskExecutor corePoolSize vs. maxPoolSize
Java Program to Check Whether Topological Sorting can be Performed in a Graph
Java Program to Implement HashMap API
Concrete Class in Java
Java Program to Construct K-D Tree for 2 Dimensional Data
Java Program to Implement the One Time Pad Algorithm
A Guide to ConcurrentMap
Guide to java.util.concurrent.BlockingQueue
Spring Boot - Admin Server
Java Program to Find Location of a Point Placed in Three Dimensions Using K-D Trees
Java Program to Generate Random Numbers Using Middle Square Method
Netflix Archaius with Various Database Configurations
Introduction to Spring Cloud Netflix – Eureka
Java Program to Implement VList
Spring WebClient Filters
Java Program to Perform Matrix Multiplication
Java Program to Implement the linear congruential generator for Pseudo Random Number Generation
Java Program to Implement Hash Tables Chaining with List Heads
Running Spring Boot Applications With Minikube