EasyNo. 0800LeetCode Premium

Similar RGB Color — LeetCode 800 Python Solution

Topics
Math, String, Enumeration
Reading time
2 min

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

PythonSolution
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

Time
O(n) or O(1)
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
0906Super PalindromesHard
0043Multiply StringsMedium
0168Excel Sheet Column TitleEasy
0171Excel Sheet Column NumberEasy
0204Count PrimesMedium
0273Integer to English WordsHard

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.