Each day I solve several coding challenges and puzzles from Codr's ranked mode. The goal is to reach genius rank, along the way I explain how I solve them. You do not need any programming background to get started, and you will learn a ton of new and interesting things as you go.
function sort(str) {
return str
.split('')
.sort()
.join('');
}
function anagrams(strs) {
const HT = {};
for (let i = 0; i < strs.length; i++) {
const str = strs[i];
const key = sort(str);
if (!HT[key])
HT[key] = [str];
else
HT[key].push(str);
}
return Object.values(HT);
}
let arr = [
'201',
'021',
'012',
'120',
'121',
'010'
]
let A = anagrams(arr);
A = A.length
// A = ? (number)
This looks like a quite interesting challenge, I'm excited to figure it out. The challenge requests us to solve A
's value, which is the length of the output from the function anagrams
, so its output is an array, keep this in mind:
return Object.values(HT);
Let's start from the beginning, with the function sort
. It takes a string as argument; it splits the string into individual characters as array; then sorts the array in ascending order; finally it joins the sorted array back to a single string and returns it. Here's some pseudo-code that illustrates how this works:
str = '201'
str.split('') --> ['2', '0', '1']
.sort() --> ['0', '1', '2']
.join('') --> '012'
Next is the function anagrams
which takes a single argument strs
, which is an array of strings (declared as arr
below). The function starts with making a new empty object HT
; then it loops over each string str
from this array. It creates a key
variable with value as the output from the function:
key = sort(str)
Next if checks if HT
doesn't have the key entry key
, if so it sets a new key-value entry, where the value is an array with str
as sole value. But if it already has the key, it pushes the str
to the array.
Basically all the values from arr
that contain 0, 1 and 2 will all become 012
thanks to the function sort
; these are the first 4 strings. The 5th string 121
will result in 112
, and the last string 010
becomes 001
. With this information we can figure out how HT
object will look like:
HT = {
'012': [...], // length: 4
'112': [...], // length: 1
'001': [...], // length: 1
}
Finally the function returns Object.values(HT)
. This basically takes all the values of HT
as an array and returns it; the return value will look like this:
[[...], [...], [...]]
So it's just an array that contains three arrays. Now finally A = output.length
, which is 3:
By solving these challenges you train yourself to be a better programmer. You'll learn newer and better ways of analyzing, debugging and improving code. As a result you'll be more productive and valuable in business. Get started and become a certified Codr today at https://nevolin.be/codr/
Top comments (0)