A rectangular board with three rows and $ n$ columns is filled with $ 3n$ counters, of which $ n$ are red, $ n$ are white, and $ n$ are blue. The object is to rearrange the counters to have counters of each of the three different colors in every column. The only operation allowed is to swap counters in the same row. Design an algorithm to accomplish such a task or prove that such an algorithm does not exist.

Let $ \mathcal{O}(1)$ be the cost of swapping the counters in the same row.

Iterate over each column. Let us consider that up to column $ i-1$ , we are done. Now we are at column $ i$ , there will be three counters, if they are of different colors then we are done, else fix one counter ( say white ) and scan other two rows to get two different color counters ( red and blue ). Running the previous step for a constant number of times ( six ) will solve the problem. More precisely there will be six possibilities in each column (123,132,…..,321), so I will try each of those.

The runtime of the above algorithm will be $ \mathcal{O}(n^3)$ as there are $ n$ columns and time spent on each column is $ \mathcal{O}(n^2)$ .

**Question:** Is it possible to solve the above-described problem linear time $ \mathcal{O}(n)$ time as input here has size $ \mathcal{O}(n)$ ? I am not even able to come up with an algorithm faster than $ \mathcal{O}(n^3)$ time.

I have taken this question from the book titled Algorithmic Puzzles ( problem 46 )