-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArrListLen.js
62 lines (56 loc) · 1.88 KB
/
ArrListLen.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// A non-empty zero-indexed array A consisting of N integers is given.
// Array A represents a linked list. A list is constructed from this array as follows:
// the first node (the head) is located at index 0;
// the value of a node located at index K is A[K];
// if the value of a node is −1 then it is the last node of the list;
// otherwise, the successor of a node located at index K is located at index
// A[K] (you can assume that A[K] is a valid index, that is 0 ≤ A[K] < N).
// For example, for array A such that:
// A[0] = 1
// A[1] = 4
// A[2] = -1
// A[3] = 3
// A[4] = 2
// the following list is constructed:
// the first node (the head) is located at index 0 and has a value of 1;
// the second node is located at index 1 and has a value of 4;
// the third node is located at index 4 and
// the fourth node is located at index 2 and has a value of −1.
// Write a function:
// def solution(a)
// that, given a non-empty zero-indexed array A consisting
// of N integers, returns the length of the list constructed from A in the above manner.
// For example, given array A such that:
// A[0] = 1
// A[1] = 4
// A[2] = -1
// A[3] = 3
// A[4] = 2
// the function should return 4, as explained in the
// example above.
// Assume that:
// N is an integer within the range
// [1..200,000];
// each element of array A is an integer
// within the range [−1..N−1];
// it will always be possible to construct
// the list and its length will be finite.
// In your solution, focus on correctness. The
// performance of your solution will not be the focus of
// the assessment.
function solution(a){
value = a[0];
sum = 1;
while (value != -1) {
if (a[value] == null ) break ;
sum += 1;
value = a[value];
}
console.log("The length of the list is : " + sum);
return sum;
}
A = [1,4,-1,3,2]; // 4
// A = [-1,4,-1,3,2]; // 1
// A = [2,-1,1,0,0,0]; // 3
// A = [5,2,-1]; // 1
solution(A);