KatInterview

818. Similar RGB Color

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find a "shorthand" RGB color that is most similar to a given 6-digit RGB color. A shorthand color is one where the red, green, and blue components are represented by repeating a single hexadecimal digit, like #11EE66, which can be shortened to #1E6. The possible values for each shorthand component are 00, 11, 22, ..., ff.

Solution

Similar RGB Color in Python

class Solution:
    def similarRGB(self, color: str) -> str:
        result = []
        # Process each of the three components (R, G, B).
        # The loop iterates through the starting indices of the components: 1, 3, 5.
        for i in range(1, 7, 2):
            # Extract the 2-character hex component, e.g., "09", "f1", "66".
            component_hex = color[i:i+2]
            # Convert the hex string component to an integer.
            val = int(component_hex, 16)
            
            # Find the index of the closest shorthand value.
            # Shorthand values are multiples of 17 (0, 17, 34, ...).
            # The index of the multiple (0-15) is found by rounding val/17.
            # We use integer arithmetic for rounding: (val + 8) // 17.
            index = (val + 8) // 17
            
            # Convert index to a hex character and repeat it.
            # e.g., index 13 becomes hex 'd', repeated to 'dd'.
            # The format specifier '{:x}' converts an integer to a lowercase hex string.
            shorthand_comp = f'{index:x}' * 2
            
            result.append(shorthand_comp)
            
        # Join the components and prepend '#' to form the final color string.
        return f"#{''.join(result)}"

Similar RGB Color in Java

class Solution {
    public String similarRGB(String color) {
        StringBuilder result = new StringBuilder("#");
        // Define hex characters for easy lookup.
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

        // Process each of the three components (R, G, B).
        for (int i = 1; i < color.length(); i += 2) {
            // Extract the 2-character hex component, e.g., "09", "f1", "66".
            String component = color.substring(i, i + 2);
            // Convert the hex string component to an integer.
            int val = Integer.parseInt(component, 16);

            // Find the index of the closest shorthand value.
            // Shorthand values are multiples of 17 (0, 17, 34, ...).
            // The index of the multiple (0-15) is found by rounding val/17.
            // We use integer arithmetic for rounding: (val + 8) / 17.
            int index = (val + 8) / 17;

            // Look up the hex character for the calculated index.
            char hexChar = hexDigits[index];

            // Append the shorthand component (e.g., "dd") to the result.
            result.append(hexChar);
            result.append(hexChar);
        }
        return result.toString();
    }
}

Similar RGB Color in C++

class Solution {
public:
    string similarRGB(string color) {
        string result = "#";
        // Define hex characters for easy lookup.
        const char hex_digits[] = "0123456789abcdef";
        
        // Process each of the three components (R, G, B).
        for (int i = 1; i < 7; i += 2) {
            // Extract the 2-character hex component, e.g., "09", "f1", "66".
            string component = color.substr(i, 2);
            // Convert the hex string component to an integer.
            int val = std::stoi(component, nullptr, 16);
            
            // Find the index of the closest shorthand value.
            // Shorthand values are multiples of 17 (0, 17, 34, ...).
            // The index of the multiple (0-15) is found by rounding val/17.
            // We use integer arithmetic for rounding: (val + 8) / 17.
            int index = (val + 8) / 17;
            
            // Look up the hex character for the calculated index.
            char hexChar = hex_digits[index];
            
            // Append the shorthand component (e.g., "dd") to the result.
            result += hexChar;
            result += hexChar;
        }
        return result;
    }
};

Similar RGB Color in TypeScript

function similarRGB(color: string): string {
    let result = '#';
    // Define hex characters for easy lookup.
    const hexDigits: string[] = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];

    // Process each of the three components (R, G, B).
    for (let i = 1; i < color.length; i += 2) {
        // Extract the 2-character hex component, e.g., "09", "f1", "66".
        const component: string = color.substring(i, i + 2);
        // Convert the hex string component to an integer.
        const val: number = parseInt(component, 16);

        // Find the index of the closest shorthand value.
        // Shorthand values are multiples of 17 (0, 17, 34, ...).
        // The index of the multiple (0-15) is found by rounding val/17.
        const index: number = Math.round(val / 17);
        
        // Look up the hex character for the calculated index.
        const hexChar: string = hexDigits[index];

        // Append the shorthand component (e.g., "dd") to the result.
        result += hexChar + hexChar;
    }

    return result;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.