- Related Questions & Answers
- Program to find minimum cost to paint fences with k different colors in Python
- Program to find minimum possible maximum value after k operations in python
- Program to find intervals by merging target interval in Python
- Program to find number of sublists containing maximum and minimum after deleting only one element in Python
- Program to find most occurring number after k increments in python
- Program to find minimum number of rocketships needed for rescue in Python
- Python Program for Find minimum sum of factors of number
- Program to find number of minimum steps to reach last index in Python
- Program to find minimum number of operations required to make one number to another in Python
- Program to find number of items left after selling n items in python
- Program to find minimum number of days to wait to make profit in python
- Program to find minimum number of days to make m bouquets using Python
- Program to find minimum number of vertices to reach all nodes using Python
- Find minimum possible digit sum after adding a number d in C++
- Program to find minimum number of hops required to reach end position in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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

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

1

Advertisements