Run this script
$ node index.js
All inputs are hard-coded in the following way:
/* index.js */
let nums = [100, 4, 200, 1, 3, 2];
console.log("Input = [" + nums + "]\n");
console.log("-----------------Result--------------------");
console.log("Output = " + longestConsecutiveLength(nums));
console.log("-------------------------------------------");
-
Return
0
if the given array is empty. -
Declare five variables,
map
,max
,start
,end
, andnum
, and set them{}
,0
,0
,0
, and0
, respectively. -
Use a for loop with index
i
and copy the value of the number with indexi
to thenum
. -
Check if the
num
property ofmap
object is defined or undefined. -
If undefined, 5-1. If
num - 1
property ofmap
object is defined, assignmap[num - 1].start
tostart
else assignnum
tostart
.5-2. If
num + 1
property ofmap
object is defined, assignmap[num + 1].end
toend
else assignnum
toend
.5-3. Assign
{start:num, end:num}
tonum
property ofmap
object.5-4. Assign
end
tomap[start].end
.5-5. Assign
start
tomap[end].start
.5-6. Assign max value of
end - start + 1
andmax
tomax
-
If defined, skip the current loop.
-
After the loop finishes, return the length of the longest consecutive elements array, which equals to
max
- Time complexity of the above algorithm is O(n) because we are iterating over the input array only once and n is the total number of elements in that array.
- Constant space is O(n), because we are using extra space.