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.
In this challenge we need to figure out A
's value, which is the output of an unknown function LGC
that takes an array of numbers as single argument.
From the first line we notice that this function is only interested in unique numbers (no duplicates), because it converts the array into a set:
nums = new Set(nums)
Then it iterates over each item in the set using the forEach
method, where x
is the number.
It checks if nums
contains x-1
, if it doesn't then it sets y=x+1
. Next there's a while loop that iterates as long as nums
contains y
, it then increments y
by 1. Finally it sets max
:
max = Math.max(max, y-x)
You can solve this problem in two ways, either you work it out on paper/spreadsheet for each number. This is a doable method because you only need to iterate 6 numbers, so it'll only take you a minute or two.
But what if this array contained 50 random numbers, then you'll need a smarter approach. The trick is to figure out what this algorithm is doing first.
Here are a few things that I notice: we have variables x
and y
, where x
remains static, but y
is being incremented by 1. It looks like x
is a starting point and y
the end point.
Then we have the line:
max = Math.max(max, y-x)
This keeps track of the max distance from x
to y
across all numbers of nums
. Notice that the while-loop's condition is to increase y
by 1 as long as nums
contains y
. Apparently this algorithm is designed to find the max length/distance of consecutive numbers in nums
.
Example: nums = [1,2,6,7,8,9]
The largest length of consecutive numbers is 4 (6 -> 9
).
Back to our challenge, the max length is 2, the only longest consecutive sequence is 1 -> 2
.
Notice that this algorithm doesn't require the input array (nums) to be sorted, because if it was sorted the algorithm could've been written differently and simpler.
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. Join me on the Road to Genius and upgrade your programming skills, at https://nevolin.be/codr/
Top comments (0)