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 firstname.lastname@example.org. 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.
- 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
- Generate all cyclic permutations of a number
- Minimum insertions to form a palindrome with permutations allowed
- Generate all permutations of a string that follow given constraints
- Print distinct sorted permutations with duplicates allowed in input
- Permutations of string such that no two vowels are adjacent
- Check if a grid can become row-wise and column-wise sorted after adjacent swaps
- Largest permutation after at most k swaps
- Minimum Swaps for Bracket Balancing
- Minimum swaps required to convert one binary string to another
- Form the largest palindromic number using atmost two swaps
- Minimum swaps required to make a binary string alternating
- Permutations of a given string using STL