Solving " Tricolor Arrangement " Efficiently
Here is an algorithm with $O(n)$ time-complexity.

First, count how many counters of each color there are on each row. With $O(n)$ time, we will obtain the number of red counters $r_i$, the number of white counters $w_i$, the number of blue counters $b_i$ on row $i$, $i=1,2,3$.

Second, we can solve the following equations for nonnegative integer variables $a_k$, $1\le k\le6$ in $O(1)$ time.

$$r_1 = a_1 + a_2$$
$$w_1 = a_3 + a_4$$
$$b_1 = a_5 + a_6$$
$$r_2 = a_4 + a_5$$
$$w_2 = a_1 + a_6$$
$$b_2 = a_2 + a_3$$
$$r_3 = a_3 + a_6$$
$$w_3 = a_2 + a_5$$
$$b_3 = a_1 + a_4$$

Third, we arrange the three rows into the following configuration.
$$
\begin{array}{|l|l|l|l|l|l|} \hline
    a_1\text{ red} &amp; a_2\text{ red} &amp; a_3\text{ white} &amp; a_4\text{ white} &amp; a_5\text{ blue} &amp; a_6\text{ blue}  \\\hline
    a_1\text{ white} &amp; a_2\text{ blue} &amp; a_3\text{ blue} &amp; a_4\text{ red} &amp; a_5\text{ red} &amp; a_6\text{ white}  \\\hline
    a_1\text{ blue} &amp; a_2\text{ white} &amp; a_3\text{ red} &amp; a_4\text{ blue} &amp; a_5\text{ white} &amp; a_6\text{ red}  \\\hline
\end{array}
$$



We are done. 



Here are a couple of exercises that fill the gap in the above specification of the algorithm.

Exercise 1. Find an algorithm that solves in $O(1)$ time that system of 9 equations for nonnegative integer variables $a_k$, $1\le k\le6$, given the condition that $r_i+w_i+b_i=n$ for all $i$ and $\sum_{i=1}^3r_i=\sum_{i=1}^3w_i=\sum_{i=1}^3b_i=n$. Show that there is always a solution.



Exercise 2. Check that arrangement in third step can be done in $O(n)$ time by swapping the counters in each row.



Here is a problem that may not be easy to do.

Problem 1. Generalize the problem of tricolor arrangement to $m$ rows and $m$ colors, $m&gt;3$. Solve it with an $O(n)$ algorithm, assuming $m$ is a constant.  (Hint, use Hall's marriage theorem to reduce the sum of the number of distinct colors in each row.)