
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 −
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))
Input
["G", "R", "G", "B", "R"]
Output
1
- Related Articles
- Program to find minimum cost to paint fences with k different colors in Python
- Program to find minimum amplitude after deleting KLength sublist in Python
- Program to find minimum amplitude after deleting K elements in Python
- Program to find minimum possible maximum value after k operations in python
- Program to find number of sublists containing maximum and minimum after deleting only one element in Python
- Program to find intervals by merging target interval 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 minimum number of monotonous string groups in Python
- Python program to print sorted number formed by merging all elements in array
- Program to find most occurring number after k increments in python
- Program to find minimum number of rocketships needed for rescue in Python
- 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

Advertisements