- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- 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

- 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 minimum length of string after deleting similar ends in Python
- Program to find minimum number of people to teach 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 days to eat N oranges in Python
- Program to find minimum number of operations to make string sorted in Python
- Python program to print sorted number formed by merging all elements in array
- 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

Advertisements