Similar RGB Color Problem
Description
LeetCode Problem 800.
The red-green-blue color "#AABBCC" can be written as "#ABC" in shorthand.
- For example,
"#15c"is shorthand for the color"#1155cc".
The similarity between the two colors "#ABCDEF" and "#UVWXYZ" is -(AB - UV)^2 - (CD - WX)^2 - (EF - YZ)^2.
Given a string color that follows the format "#ABCDEF", return a string represents the color that is most similar to the given color and has a shorthand (i.e., it can be represented as some "#XYZ").
Any answer which has the same highest similarity as the best answer will be accepted.
Example 1:
Input: color = "#09f166"
Output: "#11ee66"
Explanation:
The similarity is -(0x09 - 0x11)^2 -(0xf1 - 0xee)^2 - (0x66 - 0x66)^2 = -64 -9 -0 = -73.
This is the highest among any shorthand color.
Example 2:
Input: color = "#4e3fe1"
Output: "#5544dd"
Constraints:
color.length == 7color[0] == '#'color[i]is either digit or character in the range['a', 'f']fori > 0.
Solution
Approach: Round Each Channel to the Nearest Multiple of 17
A shorthand color #XYZ stands for #XXYYZZ, so each of its channels is one of 0x00, 0x11, 0x22, ..., 0xff, which are exactly the multiples of 17 (because 0x11 = 17). The similarity is a sum of three separate squared differences, one per channel, and each channel of the shorthand color can be chosen freely. So we can maximize the similarity by making each channel as close as possible on its own; there is no need to try all 4096 shorthand colors.
For a channel value v (0 to 255), the nearest multiple of 17 is 17 * round(v / 17). With integers that is (v + 8) / 17 (integer division), which gives the hex digit to repeat: if v = 17q + r, the remainder r is at most 16, and r >= 9 means 17(q + 1) is closer. A tie is impossible since 17 is odd.
For example 1, 0x09 = 9 rounds to digit 1 (0x11), 0xf1 = 241 rounds to digit e (0xee = 238), and 0x66 stays 6, giving "#11ee66". The result is lowercase, like the input.
Complexity: O(1) time and space.
class Solution:
def similarRGB(self, color: str) -> str:
ans = "#"
for i in (1, 3, 5):
value = int(color[i:i + 2], 16)
# Shorthand channels are 0x00, 0x11, ..., 0xff (multiples of 17): take the nearest one.
digit = (value + 8) // 17
ans += "0123456789abcdef"[digit] * 2
return ans