Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Backtracking
  • Interview Problems on Backtracking
  • MCQs on Backtracking
  • Tutorial on Backtracking
  • Backtracking vs Recursion
  • Backtracking vs Branch & Bound
  • Print Permutations
  • Subset Sum Problem
  • N-Queen Problem
  • Knight's Tour
  • Sudoku Solver
  • Rat in Maze
  • Hamiltonian Cycle
  • Graph Coloring
Open In App
Next Article:
All permutations of a string using iteration
Next article icon

Print all permutations of a string in Java

Last Updated : 08 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string str, the task is to print all the permutations of str. A permutation is an arrangement of all or part of a set of objects, with regard to the order of the arrangement. For instance, the words ‘bat’ and ‘tab’ represents two distinct permutation (or arrangements) of a similar three letter word.

Examples: 

Input: str = “cd” 
Output: cd dc

Input: str = “abb” 
Output: abb abb bab bba bab bba 

Approach: Write a recursive function that prints every permutation of the given string. Terminating condition will be when the passed string is empty.

Below is the implementation of the above approach:

Java




// Java program to print all the permutations
// of the given string
public class GFG {
 
    // Function to print all the permutations of str
    static void printPermutn(String str, String ans)
    {
 
        // If string is empty
        if (str.length() == 0) {
            System.out.print(ans + " ");
            return;
        }
 
        for (int i = 0; i < str.length(); i++) {
 
            // ith character of str
            char ch = str.charAt(i);
 
            // Rest of the string after excluding
            // the ith character
            String ros = str.substring(0, i) +
                        str.substring(i + 1);
 
            // Recursive call
            printPermutn(ros, ans + ch);
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String s = "abb";
        printPermutn(s, "");
    }
}
 
 
Output
abb abb bab bba bab bba 

Time Complexity: O(N2), where N is the length of the given string
Auxiliary Space: O(N)

When the permutations need to be distinct.

Examples: 

Input: str = “abb” 
Output: abb bab bba 

Input: str = “geek” 
Output: geek geke gkee egek egke eegk eekg ekge ekeg kgee kege keeg 

Approach: Write a recursive function that print distinct permutations. Make a boolean array of size ’26’ which accounts the character being used. If the character has not been used then the recursive call will take place. Otherwise, don’t make any call. Terminating condition will be when the passed string is empty.

Below is the implementation of the above approach:

Java




// Java program to print all the permutations
// of the given string
public class GFG {
 
    // Function to print all the distinct
    // permutations of str
    static void printDistinctPermutn(String str,
                                    String ans)
    {
 
        // If string is empty
        if (str.length() == 0) {
 
            // print ans
            System.out.print(ans + " ");
            return;
        }
 
        // Make a boolean array of size '26' which
        // stores false by default and make true
        // at the position which alphabet is being
        // used
        boolean alpha[] = new boolean[26];
 
        for (int i = 0; i < str.length(); i++) {
 
            // ith character of str
            char ch = str.charAt(i);
 
            // Rest of the string after excluding
            // the ith character
            String ros = str.substring(0, i) +
                        str.substring(i + 1);
 
            // If the character has not been used
            // then recursive call will take place.
            // Otherwise, there will be no recursive
            // call
            if (alpha[ch - 'a'] == false)
                printDistinctPermutn(ros, ans + ch);
            alpha[ch - 'a'] = true;
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String s = "geek";
        printDistinctPermutn(s, "");
    }
}
 
 
Output
geek geke gkee egek egke eegk eekg ekge ekeg kgee kege keeg 

Time Complexity: O(N2), where N is the length of the given string
Auxiliary Space: O(N)



Next Article
All permutations of a string using iteration
author
dekay
Improve
Article Tags :
  • Backtracking
  • DSA
  • Recursion
  • Strings
  • permutation
  • Permutation and Combination
Practice Tags :
  • Backtracking
  • permutation
  • Recursion
  • Strings

Similar Reads

  • Print all Unique permutations of a given string.
    Given a string that may contain duplicates, the task is find all unique permutations of given string in any order. Examples: Input: "ABC"Output: ["ABC", "ACB", "BAC", "BCA", "CAB", "CBA"]Explanation: Given string ABC has 6 unique permutations as "ABC", "ACB", "BAC", "BCA", "CAB" and "CBA". Input: "A
    12 min read
  • Print all palindrome permutations of a string
    Given a string s, consisting of lowercase Latin characters [a-z]. Find out all the possible palindromes that can be generated using the letters of the string and print them in lexicographical order. Note: Return an empty array if no possible palindromic string can be formed. Examples: Input: s = aab
    10 min read
  • All permutations of a string using iteration
    A permutation, also called an “arrangement number” or “order”, is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation ( Source: Mathword ) Below are the permutations of string ABC. ABC ACB BAC BCA CBA CAB We hav
    4 min read
  • Print all lexicographical greater permutations of a given string
    Given a string S, print those permutations of string S which are lexicographically greater than S. If there is no such permutation of string, print -1. Examples: Input : BCA Output : CAB, CBA Explanation: Here, S = "BCA", and there are 2 strings "CAB, CBA" which are lexicographically greater than S.
    13 min read
  • Permutations of given String
    Given a string s, the task is to return all permutations of a given string in lexicographically sorted order. Note: A permutation is the rearrangement of all the elements of a string. Duplicate arrangement can exist. Examples: Input: s = "ABC"Output: "ABC", "ACB", "BAC", "BCA", "CAB", "CBA" Input: s
    5 min read
  • Permutations of a given string using STL
    Given a string s, the task is to return all unique permutations of a given string in lexicographically sorted order. Note: A permutation is the rearrangement of all the elements of a string. Examples: Input: s = "ABC"Output: "ABC", "ACB", "BAC", "BCA", "CBA", "CAB" Input: s = "XY"Output: "XY", "YX"
    4 min read
  • Time complexity of all permutations of a string
    Time complexity of printing all permutations of a string. void perm(String str){ perm(str, ""); } void perm(String str, String prefix){ if(str.length() == 0){ System.out.println(prefix); } else{ for(int i = 0; i < str.length(); i++){ String rem = str.substring(0, i) + str.substring(i + 1); perm(r
    3 min read
  • Number of distinct permutation a String can have
    We are given a string having only lowercase alphabets. The task is to find out total number of distinct permutation can be generated by that string. Examples: Input : aab Output : 3 Different permutations are "aab", "aba" and "baa". Input : ybghjhbuytb Output : 1663200 A simple solution is to find a
    6 min read
  • Print all permutations of a number N greater than itself
    Given a number N, our task is to print those permutations of integer N which are greater than N.Examples: Input: N = 534 Output: 543Input: N = 324 Output: 342, 423, 432 Approach: To solve this problem, we can obtain all the lexicographically larger permutations of N using next_permutation() method i
    6 min read
  • Print k different sorted permutations of a given array
    Given an array arr[] containing N integers, the task is to print k different permutations of indices such that the values at those indices form a non-decreasing sequence. Print -1 if it is not possible. Examples: Input: arr[] = {1, 3, 3, 1}, k = 3 Output: 0 3 1 2 3 0 1 2 3 0 2 1 For every permutatio
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences