Please read the new rule regarding the restriction on the use of AI tools. ×

code_fille's blog

By code_fille, history, 9 years ago, In English

Given an array of 3 different colored balls, we have to sort it using minimum number of swaps. It could be done in O(n) using 3-pointers and two traversals(one to count no. of occurrences of each color and other to sort). Could this be implemented in one traversal(count is not known before).

  • Vote: I like it
  • -2
  • Vote: I do not like it

»
9 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Yes, it can be done with a single traversal. For easier explanation, assume you have an array of integers, and those integers are either 1, 2 or 3. While you read the input, count how many 1's, 2's and 3's you have. Now you know what portion of the array should have 1's in the end, what portion should have 2's and what portion should have 3's. Let G1 be the portion of the array that should have 1's at the end, and similarly, G2 and G3 the same for 2's and 3's.

  • Step 1: Do a traversal of the array and let sxy be the amount of x's that are in Gy. A swap affects at most two elements, so you can't correct more than that with a single swap. Swap 1's in G2 with 2's in G1, 1's in G3 with 3's in G1 and 2's in G3 with 3's in G2. You'll be correcting two elements with every one of those swaps, so it's optimum. That's min(s12, s21) + min(s13, s31) + min(s23, s32).
  • Step 2: Suppose you're not finished yet, then it means that there's some group Gx that contains an element y (y! = x), which also means that group Gy contains an unwanted element z (z! = y), but this also implies that z! = x because otherwise it's a swap we should have done in step 1, and finally group Gz contains an unwanted element which must be x. In other words, the remaining unordered elements form cycles, and whatever the direction of the cycles, there must either be a 1 in G2 or a 2 in G1 and you need two swaps to correct three elements. So the remaining number of swaps is 2*(max(s12, s21)- min(s12, s21)).