Program to find minimum number colors remain after merging in Python

Suppose we have a list of colors (R, G, B). When two different colors are adjacent, they can merge into a single color item of the third color. We need to find the minimum number of colors remaining after any possible sequence of such transformations.

So, if the input is like colors = ["G", "R", "G", "B", "R"], then the output will be 1 as it can transform like below ?

Initial: G R G B R G+R?B: B G B R B+G?R: R B R Final: G

Algorithm

To solve this, we will follow these steps ?

  • n := size of colors
  • if colors has only one distinct color, then
    • return n
  • if n <= 1, then
    • return n
  • x := 0
  • d := a map with key value pairs {("R", 1), ("G", 2), ("B", 3)}
  • for each c in colors, do
    • x := x XOR d[c]
  • return 2 if x is same as 0 otherwise 1

Example

Let us see the following implementation to get better understanding ?

class Solution:
    def solve(self, colors):
        n = len(colors)
        if len(set(colors)) == 1:
            return n
        if n <= 1:
            return n
        x = 0
        d = {"R": 1, "G": 2, "B": 3}
        for color in colors:
            x ^= d[color]
        return 2 if x == 0 else 1

ob = Solution()
colors = ["G", "R", "G", "B", "R"]
print(ob.solve(colors))

The output of the above code is ?

1

How It Works

The algorithm uses XOR properties to determine the minimum colors. Each color is mapped to a unique value (R=1, G=2, B=3). When we XOR all color values:

  • If the XOR result is 0, we can reduce to 2 colors minimum
  • If the XOR result is non-zero, we can reduce to 1 color minimum

This works because XOR operation mimics the color merging rules mathematically.

Conclusion

This problem uses XOR operations to efficiently calculate the minimum remaining colors after all possible merges. The key insight is that color merging follows XOR-like properties where identical elements cancel out.

Updated on: 2026-03-25T13:31:07+05:30

255 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements