Given a 24-bit RGB color encoded as a binary string color of length 24, where the first 8 bits represent the red channel, the next 8 bits represent the green channel, and the last 8 bits represent the blue channel, find the nearest color from a provided palette.
The palette is a list of [name, hex] pairs, where hex is a 6-character hexadecimal string (for example "FF00AA") representing an RGB color.
Distance is the squared Euclidean distance in RGB space: (r1 - r2)² + (g1 - g2)² + (b1 - b2)². Return the name of the closest palette color. If multiple palette colors tie, return the one that appears first in the palette.
Function Signature
def nearest_color(color: str, palette: list[list[str]]) -> str:
Rules
-
Each 8-bit group of
color
is read with the most significant bit first, so
"10000000"
is 128.
-
In each
hex
string, characters 1-2 are red, 3-4 are green and 5-6 are blue, each a two-digit base-16 number.
-
When two or more entries have the same smallest distance, return the name of the one with the lowest index in
palette
.
Constraints
-
color.length == 24
-
color
consists only of characters
'0'
and
'1'
-
1 <= palette.length <= 1000
-
Each palette entry is
[name, hex]
where
name
is a non-empty string with
name.length <= 20
-
hex
is a 6-character string of uppercase hexadecimal digits (
0
-
9
,
A
-
F
)
Examples
Input: color = "111111110000000000000000", palette = [["red","FF0000"],["green","00FF00"],["blue","0000FF"]]
Output: "red"
The input bits are R = 11111111 (255), G = 00000000 (0) and B = 00000000 (0), which is pure red. The entry "red" (FF0000) is at distance 0.
Input: color = "100000001000000010000000", palette = [["white","FFFFFF"],["black","000000"],["gray","808080"]]
Output: "gray"
R = G = B = 10000000 (128), which is exactly hex 808080, so "gray" is at distance 0. White is at 3 × 127² = 48,387 and black at 3 × 128² = 49,152.
Input: color = "000000000000000000000000", palette = [["maroon","800000"],["navy","000080"]]
Output: "maroon"
The input is black. Maroon (128, 0, 0) and navy (0, 0, 128) are both at distance 128² = 16,384, so the tie goes to "maroon" because it comes first.