Given a string on length N. You can swap only the adjacent elements and each element can be swapped atmost once. Find the no of permutations of the string that can be generated after performing the swaps as mentioned.
Input : 12345 Output : 12345 12354 12435 13245 13254 21345 21354 21435
Source: Goldman Sachs Interview
Consider any i-th character in the string. There are two possibilities for this character:
1.) Don’t swap it, i.e. don’t do anything with this character and move to the next character.
2.) Swap it. As it can be swapped with its adjacent,
……..a.) Swap it with the next character. Because each character can be swapped atmost once, we’ll move to the position (i+2).
……. b.) Swap it with the previous character – we don’t need to consider this case separately as i-th character is the next character of (i-1)th which is same as the case 2.a.
12345 12354 12435 13245 13254 21345 21354 21435
This article is contributed by ekta1994. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Generate lexicographically smallest string of 0, 1 and 2 with adjacent swaps allowed
- Generate all binary permutations such that there are more or equal 1's than 0's before every point in all permutations
- Longest common subsequence with permutations allowed
- Minimum insertions to form a palindrome with permutations allowed
- Print distinct sorted permutations with duplicates allowed in input
- Generate all cyclic permutations of a number
- Generate all permutations of a string that follow given constraints
- Iterative program to generate distinct Permutations of a String
- Permutations of string such that no two vowels are adjacent
- Minimum number of adjacent swaps to convert a string into its given anagram
- Check if a grid can become row-wise and column-wise sorted after adjacent swaps
- Minimum string such that every adjacent character of given string is still adjacent
- Largest permutation after at most k swaps
- Minimum Swaps for Bracket Balancing
- Lexicographical smallest number after at most K consecutive swaps
- Sort decreasing permutation of N using triple swaps
- Find lexicographically smallest string in at most one swaps
- Form the largest palindromic number using atmost two swaps
- Minimum swaps required to convert one binary string to another
- Minimum swaps required to make a binary string alternating