MCPcopy Create free account
hub / github.com/betomoedano/JavaScript-Coding-Interview-Questions / largestRange

Function largestRange

arrays/largest-range.js:3–34  ·  view source on GitHub ↗
(array)

Source from the content-addressed store, hash-verified

1// time O(n)
2// space O(n)
3function largestRange(array) {
4 const dic = {};
5 let bestRange = [];
6 let longesLenght = 0;
7
8 for (const num of array) {
9 dic[num] = true;
10 }
11
12 for (const num of array) {
13 if (!dic[num]) continue;
14 dic[num] = false;
15 let currentLenght = 1;
16 let left = num - 1;
17 let right = num + 1;
18 while (left in dic) {
19 dic[left] = false;
20 currentLenght++;
21 left--;
22 }
23 while (right in dic) {
24 dic[right] = false;
25 currentLenght++;
26 right++;
27 }
28 if (currentLenght > longesLenght) {
29 longesLenght = currentLenght;
30 bestRange = [left + 1, right - 1];
31 }
32 }
33 return bestRange;
34}
35
36const array = [1, 11, 3, 0, 15, 5, 2, 4, 10, 7, 12, 6];
37

Callers 1

largest-range.jsFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected