File: similar-rgb-color/solution.py

Date: 2026-06-06

Time: 19:07

Purpose

This file solves LeetCode 800 - Similar RGB Color. It finds the closest "shorthand" hex color (where each RGB component is a repeated digit like #aabbcc) to a given arbitrary hex color, minimizing the sum of squared differences across the three channels. It also contains its own inline unit tests.

Key Components

Solution.similarRGB(color: str) -> str

The public interface matching LeetCode's expected signature. Takes a 7-character hex string (#RRGGBB) and returns the nearest shorthand-representable color.

closest(comp: str) -> str (nested helper)

The core math. Given a 2-character hex component (e.g. "09"), it finds the nearest value in the set {0x00, 0x11, 0x22, ..., 0xff} — the 16 values where both hex digits are identical.

The technique: shorthand values are all multiples of 17 (0x11 = 17). So round(val / 17) * 17 snaps to the nearest one. The result is formatted back to a zero-padded 2-digit hex string.

Patterns

Independent channel decomposition. The problem decomposes into three independent subproblems — one per color channel. The similarity metric (sum of squared differences) is separable, so minimizing each channel independently minimizes the total. This is why closest is applied to each channel slice independently rather than searching over all 4096 shorthand colors.

Nested helper. closest is defined inside similarRGB as a closure, which is a common pattern in LeetCode solutions to keep the helper tightly scoped. It doesn't actually capture any state from the enclosing scope, so it could be a static method, but the nesting keeps things compact.

Inline tests. Tests live in the same file as the solution rather than in a separate test_solution.py, though a separate test file also exists and imports from here.

Dependencies

Imports: Only unittest from the standard library — no external dependencies.

Imported by: The separate similar-rgb-color/testsolution.py imports the Solution class. The massive "Imported By" list in the prompt is misleading — those are *all* test files across the repo, not files that specifically import this module. Only similar-rgb-color/testsolution.py actually imports from this file.

Flow

1. Caller passes a string like "#09f166".

2. similarRGB slices it into three 2-char components: "09", "f1", "66".

3. Each component goes through closest:

4. Concatenate with "#" prefix: "#11ee66".

Invariants

Error Handling

None. The function assumes valid input per LeetCode's constraints. An invalid hex string would propagate a ValueError from int(comp, 16). A string too short would raise an IndexError from the slicing.

Topics to Explore

Beliefs