Problem Statement:
There is a tournament in which different teams are participating,Each Team member has been given a TShirt with Team Name on it,For eg: All the players of team "A" will be having TShirts printed with "A",
Initially you have been given a sequence of team members,All the team members want to reorder themselves in order to form Good sequence,
There are two types of Sequences:
1) Bad Sequence: If a team member is adjacent to same team members.
eg: BAA, AAB ,AAA (These all are Bad Sequences)
2) Good Sequence: If a team member is not adjacent to same teams members.
eg: BAB , ABA (These are Good Sequences)You have to find the minimum numbers of swaps (between any team members) required to form the Good sequence.Return -1 ,If Good sequence can't be formed.
Examples:
Example 1:
Input: ABAACD
Output: 1
Explanation: "A" at 3rd index can be swapped with "C" at 4th index (ABACAD).
Example 2:
Input: AABA
Output: -1My Approach:
This question has been asked in Google onsite interview,
I am able to come up with Max Heap solution to form a new string which will be a good sequence,
but unable to think about the approach for minimum number of swaps.
I am also thinking in terms of recursion,
like we can try to swap every index with other and verify whether the resultant string is Good or not!
But its time complexity will be huge,
I am also getting the intuition of DP here but unable to approach the problem.