Similar RGB Color - Problem
Similar RGB Color
RGB colors can be represented in two formats:
- Full format:
#AABBCCwhere each color component (Red, Green, Blue) uses 2 hexadecimal digits - Shorthand format:
#ABCwhere each color component uses 1 repeated hexadecimal digit (equivalent to#AABBCC)
For example, #15c is shorthand for #1155cc, and #f0a represents #ff00aa.
Your task: Given a color in full format #ABCDEF, find the most similar color that can be represented in shorthand format.
Similarity formula: The similarity between two colors #ABCDEF and #UVWXYZ is calculated as:-(AB - UV)² - (CD - WX)² - (EF - YZ)²
The higher this value (closer to 0), the more similar the colors are. Return any shorthand color with the highest similarity.
Input & Output
example_1.py — Basic Case
$
Input:
"#09f166"
›
Output:
"#11ee66"
💡 Note:
The closest shorthand color to #09f166 is #1e6, which expands to #11ee66. This minimizes the total squared difference across all RGB components.
example_2.py — Perfect Match
$
Input:
"#aabbcc"
›
Output:
"#abc"
💡 Note:
#aabbcc is already in shorthand format as #abc, so the similarity is 0 (perfect match).
example_3.py — High Contrast
$
Input:
"#ffffff"
›
Output:
"#fff"
💡 Note:
The pure white color #ffffff has a perfect shorthand representation #fff.
Visualization
Tap to expand
Understanding the Visualization
1
Parse Target Color
Extract RGB values from the input hex color
2
Generate All Shorthand Colors
Create all 16³ = 4096 possible shorthand combinations
3
Calculate Similarities
Compute similarity score using squared difference formula
4
Return Best Match
Select the shorthand color with highest similarity score
Key Takeaway
🎯 Key Insight: With only 4,096 possible shorthand colors, exhaustive search is both simple and optimal, running in constant time!
Time & Space Complexity
Time Complexity
O(1)
Always checks exactly 4096 combinations (16³), which is constant
✓ Linear Growth
Space Complexity
O(1)
Only uses a few variables to store the best color and similarity
✓ Linear Space
Constraints
-
coloris a valid RGB color in the format#ABCDEF - Color string length is exactly 7 characters (including #)
- All hex digits are lowercase letters a-f or digits 0-9
- Guaranteed unique solution or multiple valid answers accepted
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code