Similar RGB Color - Problem

The red-green-blue color #AABBCC can be written as #ABC in shorthand when each pair has identical characters. For example, #15c is shorthand for the color #1155cc.

The similarity between two colors #ABCDEF and #UVWXYZ is calculated as: -(AB - UV)² - (CD - WX)² - (EF - YZ)².

Given a string color that follows the format #ABCDEF, return a string that 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.

Input & Output

Example 1 — Basic Case
$ Input: color = "#09f24a"
Output: "#0af"
💡 Note: RGB components are (9, 242, 74). Closest shorthand digits: R→0 (0 vs 9), G→f (255 vs 242), B→a (170 vs 74). Result: #0af
Example 2 — Already Shorthand
$ Input: color = "#aabbcc"
Output: "#abc"
💡 Note: Input is already in shorthand-compatible format. RGB (170, 187, 204) maps perfectly to shorthand #abc
Example 3 — Dark Color
$ Input: color = "#123456"
Output: "#123"
💡 Note: RGB components (18, 52, 86). Closest shorthand: R→1 (17 vs 18), G→3 (51 vs 52), B→5 (85 vs 86). Very close matches.

Constraints

  • color is a valid 6-digit hexadecimal color string
  • color follows the format "#ABCDEF" where A, B, C, D, E, F are hexadecimal digits
  • Return value should be in format "#XYZ" where X, Y, Z are hexadecimal digits

Visualization

Tap to expand
Similar RGB Color: Convert to Closest Shorthand#09f24aRGB: (9, 242, 74)Input: Full Hex ColorFind closest shorthand digits:R: 9 → 0 (distance: 9)G: 242 → f (distance: 13)B: 74 → 7 (distance: 11)#077RGB: (0, 119, 119)Output: Shorthand ColorSimilarity = -(0-9)² - (119-242)² - (119-74)² = -18170Maximum similarity among all 4096 shorthand options!
Understanding the Visualization
1
Input
Full hex color #09f24a with RGB values
2
Process
Find closest shorthand hex digits for each component
3
Output
Shorthand color #0af with maximum similarity
Key Takeaway
🎯 Key Insight: Shorthand colors have identical hex digit pairs, so we only need to find the best single digit for each RGB component
Asked in
Google 15 Facebook 12
18.5K Views
Medium Frequency
~15 min Avg. Time
324 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen