Ctrl K

Nearest Short Hex Color

Easy
Web colors are written as #RRGGBB: three pairs of hex digits give the red, green and blue components (each from 0 to 255). When both digits in every pair match, the color has a short form: for example, #2277dd is #27d. The difference between colors #r₁g₁b₁ and #r₂g₂b₂ (components taken as numbers) is (r₁ - r₂)² + (g₁ - g₂)² + (b₁ - b₂)². You are given a color color in full form. Return, in full form (# plus six digits), the color that has a short form and the smallest difference from color. That color is always unique.
Example 1
color='#1a7fe0' → '#2277dd'

0x1a = 26 is closest to 0x22 = 34 (off by 8, versus 9 for 0x11 = 17), 0x7f = 127 is closest to 0x77 = 119 (8 versus 9 for 0x88), and 0xe0 = 224 is closest to 0xdd = 221. That gives #2277dd.

Example 2
color='#33cc00' → '#33cc00'

The color already has the short form #3c0, so nothing changes.

Constraints
  • len(color) = 7
  • color[0] = '#'
  • The other characters are digits 0–9 or lowercase letters a–f
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsMirror Squares in a Range HardErase Digits Until It Divides by 25 MediumEven Vowel and Consonant Pieces MediumValue of a Roman Numeral EasySum of Binary Strings Easy
loading Python…
Input
color='#1a7fe0'
Expected
'#2277dd'

Run checks the first 3 tests in your browser. Submit checks all 163 tests on the server, hidden ones included.