Prepin
Log in

Discover all the permutations of a specified string.

Approach / Explanation

This question requires you to develop a program that generates all permutations of a specified string. A permutation involves creating every possible arrangement of the characters in the given string, where all characters are distinct in each permutation. For instance, if the input string is "abc", the output should include all possible permutations of this string: ["abc", "acb", "bac", "bca", "cab", "cba"] . To effectively tackle this question, a solid understanding of recursion is essential, as it is the most effective method for finding the solution.

Suggested Answer

An effective method to tackle this problem is through recursion. Below is a solution implemented in Python: def permute ( data , start , end ) : if start == end : print ( '' . join ( data ) ) else : for i in range ( start , end ) : data [ start ] , data [ i ] = data [ i ] , data [ start ] permute ( data , start + 1 , end ) data [ start ] , data [ i ] = data [ i ], data [ start ] # backtrack string = 'ABC' n = len ( string ) data = list ( string ) permute ( data , 0 , n ) In this implementation, we swap each character with the starting character and then recursively call the function on the remaining characters. Once we have all permutations, we backtrack to prevent duplicates in the order of the results.

Alternative Answer

You can also tackle this problem using built-in Python functions, specifically itertools.permutations() . Here is a solution implemented in Python: import itertools def all_permutations ( given_string ) : return [ '' . join ( p ) for p in itertools . permutations ( given_string ) ] print ( all_permutations ( 'abc' ) ) This solution utilizes the Python library itertools , which includes the permutations() method that generates all possible permutations of a string. We simply concatenate the resulting tuples to produce the final string output. While this method is straightforward, understanding the recursive approach can provide a deeper insight into the concepts of permutations and algorithm design overall.

Question Details

Difficulty & Category

Medium
algorithms

Companies

Amazon

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.