Leetcode!
  • LeetCode!
  • My personal guide to Leetcode
  • Array
    • 11. Container With Most Water
    • 15. 3Sum
    • 219. Contains Duplicate II
    • 238. Product of Array Except Self
    • 245. Shortest Word Distance III
    • 392. Is Subsequence
    • 442. Find All Duplicates in an Array
    • 561. Array Partition I
    • 661. Image Smoother
    • 697. Degree of an Array
    • 723. Candy Crush
    • 832. Flipping an Image
  • Backtracking
    • 294. Flip Game II
    • 401. Binary Watch
    • 1079. Letter Tile Possibilities
  • Binary Search
    • 744. Find Smallest Letter Greater Than Target
    • 852. Peak Index in a Mountain Array
  • String
    • 6. ZigZag Conversion
    • 17. Letter Combinations of a Phone Number
    • 38. Count and Say
    • 521. Longest Uncommon Subsequence I
    • 544. Output Contest Matches
    • 937. Reorder Data in Log Files
  • Design
    • 251. Flatten 2D Vector
    • 281. Zigzag Iterator
  • Hash Table
    • 1. Two Sum
    • 508. Most Frequent Subtree Sum
    • 884. Uncommon Words from Two Sentences
    • 734. Sentence Similarity
  • Linked List
    • 2. Add Two Numbers
  • Unsorted
    • 917. Reverse Only Letters
  • Math
    • 43. Multiply Strings
    • 462. Minimum Moves to Equal Array Elements II
    • 553. Optimal Division
    • 800. Similar RGB Color
  • Greedy
    • 406. Queue Reconstruction by Height
    • 861. Score After Flipping Matrix
  • Tree
    • 701. Insert into a Binary Search Tree
    • 897. Increasing Order Search Tree
  • Divide and Conquer
    • 53. Maximum Subarray
  • Dynamic Programming
    • 62. Unique Paths
    • 63. Unique Paths II
    • 64. Minimum Path Sum
    • 120. Triangle
    • 198. House Robber
    • 213. House Robber II
    • 303. Range Sum Query - Immutable
    • 518. Coin Change 2
    • 750. Number Of Corner Rectangles
    • 337. House Robber III
  • Depth first search
    • 841. Keys and Rooms
  • Trie
    • 677. Map Sum Pairs
  • Two pointer
    • 42. Trapping Rain Water
Powered by GitBook
On this page
  • Approach 1: Check nearest neighbours two characters at a time
  • Approach 2: Use more advanced math
  1. Math

800. Similar RGB Color

Approach 1: Check nearest neighbours two characters at a time

class Solution(object):
    def similarRGB(self, color):
        """
        :type color: str
        :rtype: str
        """
        ret = '#'
        def subtract(s1, s2):
            return abs(int(s1, 16)-int(s2, 16))
        di = {'0':['00','11'], '1':['00','11','22'], '2':['11','22','33'],'3':['22', '44', '33'], '4':['33', '44', '55'], '5':['44', '55', '66'], '6':['55','66','77'], '7':['66','77','88'], '8':['77','88', '99'], '9':['88','99','aa'], 'a':['99','aa','bb'], 'b':['aa','bb','cc'], 'c':['bb','cc','dd'], 'd':['cc','dd','ee'], 'e':['dd','ee','ff'],'f':['ee','ff']}
        for i in range(1,len(color),2):
            # print(color[i:i+2])
            mi = float('inf')
            part = ''
            for j in di[color[i]]:
                su = subtract(color[i:i+2],j)
                if su < mi:
                    part = j
                    mi = su
                # print(j, su, mi, part)
            ret += part
        return ret

For every pair of characters we will just check if their nearest shorthand characters have min sum, and keep on repeating this till we reach the end of the string

Time Complexity: O(1)

Space Complexity: O(1)

Approach 2: Use more advanced math

Since we're evaluating the decimal form of the hex pairs, it might be easier for us to find out which one of the nearest neighbours it is. It'll be either before or after the first pairwise character.

Using some quick math this math becomes evident

class Solution(object):
    def similarRGB(self, color):
        """
        :type color: str
        :rtype: str
        """
        def close(s):
            a,b = divmod(int(s, 16), 17)
            if b > 8: a += 1
            a = hex(a)[-1]
            return a + a
        return '#' + close(color[1:3]) + close(color[3:5]) + close(color[5:])

Time Complexity: O(1)

Space Complexity: O(1)

This solution is faster even thought the time complexity is the same because for each pair we were iterating through three neighbours to find the right value, but here it just takes one division to figure out the closest neighbour

Previous553. Optimal DivisionNext406. Queue Reconstruction by Height

Last updated 6 years ago