Program to find minimum number colors remain after merging in Python

Suppose we have a list of colors (R, G, B). Now if two different colors are there next to each other then they can transform into a single color item of the third color. We have to find the smallest number of them 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 −

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 (Python)

Let us see the following implementation to get better understanding −

 Live Demo

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 qux in colors:
         x ^= d[qux]
      return 2 if x == 0 else 1   
ob = Solution()
colors = ["G", "R", "G", "B", "R"]


["G", "R", "G", "B", "R"]



Updated on: 12-Dec-2020


Kickstart Your Career

Get certified by completing the course

Get Started