Minimize swaps of pairs of characters required such that no two adjacent characters in the string are same
Given a string S consisting of N characters, the task is to find the minimum number of pairs of characters that are required to be swapped such that no two adjacent characters are the same. If it is not possible to do so, then print “-1”.
Examples:
Input: S = “ABAACD”
Output: 1
Explanation: Swapping S[3] and S[4] modifies the given string S to “ABACAD”. Since no two adjacent characters are the same, the minimum number of operations required is 1.Input: S = “AABA”
Output: -1
Approach: The given problem can be solved by using Backtracking. The idea is to generate all possible combinations of swapping of a pair of indices and then if the string is generated having no adjacent characters same with minimum swap, then print that minimum number of swaps operations performed. Follow the steps below to solve the problem:
- Define a function minimumSwaps(string &str, int &minimumSwaps, int swaps=0, int idx) and perform the following operations:
- If the adjacent characters of the string str are different then update the value of minimumSwaps to the minimum of minimumSwaps and swaps.
- Iterate over the range [idx, N] using the variable i and performing the following operations:
- Iterate over the range [i + 1, N] using the variable j and performing the following operations:
- Initialize the variable, say ansSwaps as INT_MAX to store the count of minimum swaps required.
- Call the function minimumSwaps(str, ansSwaps) to find the minimum number of swaps required to make all the adjacent characters different.
- After completing the above steps, if the value of ansSwaps is INT_MAX, then print -1. Otherwise, print the value of ansSwaps as the resultant minimum swaps.
Below is the implementation of the above approach:
C++
|
Time Complexity: O(N3*2N)
Auxiliary Space: O(1)
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.
Original page link
Best Cool Tech Gadgets
Top favorite technology gadgets
0 comments:
Post a Comment