Unique Bytes
This week, my practice interview problem was as follows:
Given an array of a billion bytes, count each occurance of each unique byte.
I know what I needed to do first: plan out the code, step by step!
1. Create an empty hash. This is what we’ll use to store the count of each unique byte.
2. Iterate through the array. In my case, I will be using a for
loop.
3. If the element exists in our hash, increment the value (count). Else, store the element has a key in our hash, and set its value to 1.
Let’s see how this looks written out:
function uniqueByte(bytes) { const byteCount = {} for (let i = 0; i < bytes.length; i++) { if (byteCount[bytes[i]]) { byteCount[bytes[i]]++ } else { byteCount[bytes[i]] = 1 } } return byteCount}
…and once we call the function:
uniqueByte([1, 0, 0, 1, 1, 0])// { 0: 3, 1: 3 }
The output is as expected!
In my case, I initially returned byteCount
in the wrong bracket — it was in the scope of the for
loop. The person who kindly interviewed me gave me something to think about:
Some interviewers are more lenient than others about the smaller things, because it’s an easy fix. As long as you get the general idea of how to execute a function and clearly communicate how you did it, you’ll be in good hands. Others are a bit more particular. Regardless of whoever interviews you, if your code fails, don’t forget to check your brackets!
For those who use VS Code, check out this Bracket Pair Colorizer extension. It’s a life saver!