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: "#1e4"
💡 Note: RGB components are (9, 242, 74). Closest shorthand digits: R→1 (17 vs 9, diff=8), G→e (238 vs 242, diff=4), B→4 (68 vs 74, diff=6). Result: #1e4
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 - Component-Wise Optimization INPUT #09f24a RGB Components (Hex): R: 09 (9) G: f2 (242) B: 4a (74) Shorthand colors: #XYZ expands to #XXYYZZ Valid values per component: 00, 11, 22, 33, 44, 55, 66, 77, 88, 99, aa, bb, cc, dd, ee, ff (multiples of 17: 0,17,34...255) Find closest for each! ALGORITHM STEPS 1 Parse Components R=09(9), G=f2(242), B=4a(74) 2 Find Nearest x17 Round to closest multiple of 17 3 Calculate Each R: 9/17=0.53 --> round to 1 1*17=17 (0x11) --> "0" closest G: 242/17=14.2 --> round to 14 14*17=238 (0xee) --> "a" closer! B: 74/17=4.35 --> round to 4 4*17=68 (0x44) --> "f" closer! 4 Combine Result #0 + a + f = #0af (expands to #00aaff) FINAL RESULT Original Color: #09f24a Most Similar Shorthand: #0af (#00aaff) Similarity Score: -(9-0)² -(242-170)² -(74-255)² = -81 - 5184 - 32761 Best possible match! OK Key Insight: The similarity formula uses squared differences, so each RGB component can be optimized INDEPENDENTLY. For each component: find the nearest multiple of 17 (0x11). Valid shorthand digits are 0,1,2...9,a,b,c,d,e,f which expand to 00,11,22...99,aa,bb,cc,dd,ee,ff (decimal: 0,17,34,51...255). Formula: round(value/17)*17 TutorialsPoint - Similar RGB Color | Component-Wise Optimization
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