Similar RGB Color — LeetCode 800 Python Solution
EasyLeetCode PremiumMathStringEnumeration
- Problem
- #800
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
The problem
The red-green-blue color "#AABBCC" can be written as "#ABC" in shorthand. For example, "#15c" is shorthand for the color "#1155cc".
Example
- Input
- color = "#09f166"
- Output
- "#11ee66"
- Explanation
- The similarity is -(0x09 - 0x11)2 -(0xf1 - 0xee)2 - (0x66 - 0x66)2 = -64 -9 -0 = -73.
Python solution
Python
class Solution:
def similarRGB(self, color: str) -> str:
def f(x):
y, z = divmod(int(x, 16), 17)
if z > 8:
y += 1
return '{:02x}'.format(17 * y)
a, b, c = color[1:3], color[3:5], color[5:7]
return f'#{f(a)}{f(b)}{f(c)}'Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) or O(1) |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 800. Similar RGB Color is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 800. Similar RGB Color?
- LeetCode 800. Similar RGB Color is rated Easy on LeetCode.
- What topics does LeetCode 800. Similar RGB Color cover?
- LeetCode 800. Similar RGB Color is tagged Math, String and Enumeration on LeetCode.
- Is LeetCode 800. Similar RGB Color a premium problem?
- Yes. LeetCode 800. Similar RGB Color is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.