Fun coding interview question:

How can you sort colors?
The initial approach might be to sort all potential R,G,B combinations, but that doesn't work

Similar colors are grouped together, but it isn't a smooth and unique solution
To keep results to a traditional 2-D sorted rainbow, we have to significantly limit our options

Out of RGB, one must be 255, one must be 0, and the other can vary between 0-254
(You probably want to make that limitation explicit

Unless the interviewee already has a good handle on color theory)
If you have access to a computer, let them play with a color picker to see if they can figure out the underlying dynamic

If not (or as a hint), this graph is very helpful
My initial approach was to use IF statements to narrow the range down to each 1/6th, then compare using the color value that's changing

You can improve that by narrowing down to 1/3rds - looking where green is maxed out, you can compare the sum of (blue - red) from two colors
You can even do that for each half (as long as the sign of the derivative doesn't change for each color)

Pick left or right based on whether Green < Blue

Then compare the two sums

Formula for Left is (Green - Red + Blue)

Formula for Right is (Red - Green - Blue)
Extra credit

RGB color space is a cube, and two of the corners are black and white

Rotate the cube along the (0,0,0) and (255,255,255) diagonal

Sort by how many degrees it takes to get Green and Blue back to 0 and 0
You can follow @tjrwriting.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled:

By continuing to use the site, you are consenting to the use of cookies as explained in our Cookie Policy to improve your experience.