-
Notifications
You must be signed in to change notification settings - Fork 0
/
linkedListConnectedComponents.js
61 lines (49 loc) · 1.33 KB
/
linkedListConnectedComponents.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
/*
Reverse a linked list
Given a linked list and a subset of values, output the number of components
that are either isolated in the subset or grouped in the subset
EXAMPLE
Input:(0-> 1 -> 2 -> 3 -> 4 -> 5 -> null) G=[0,1,3]
Output: 2
Input: linked list and value subset
Output: number of connected components
Constraints: optimize
Edge Case:
Time Complexity: O(n) - we traverse the list
Space Complexity: O(g) - create a hashmap the size of array
Optimized version:
Time Complexity:
Space Complexity:
source:
https://leetcode.com/problems/linked-list-components/
*/
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @param {number[]} G
* @return {number}
*/
var numComponents = function (head, G) {
let hash = {};
let output = 0;
G.forEach((val) => (hash[val] = true));
//traverse th whole list one time checking if value is in hashtable
// if it is, traverse until next val isn't in table
// increment output and continue checking for other components
while (head) {
if (hash[head.val]) {
while (head && hash[head.val]) {
head = head.next;
}
output++;
}
head ? (head = head.next) : (head = null);
}
return output;
};