Skip to content

Commit d8e322b

Browse files
committed
Linked-List-Component Solution added
1 parent 593480f commit d8e322b

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
2+
3+
4+
/**PROBLEM
5+
* You are given the head of a linked list containing unique integer values and an integer array nums
6+
*that is a subset of the linked list values.
7+
8+
*Return the number of connected components in nums where two values are connected if
9+
*they appear consecutively in the linked list.
10+
*/
11+
12+
// SAMPLE I/O
13+
// Input: head = [0,1,2,3], nums = [0,1,3]
14+
// Output: 2
15+
// Explanation: 0 and 1 are connected, so [0, 1] and [3] are the two connected components.
16+
17+
// Approach
18+
/**
19+
* Creating a HashMap to store all the values of nums[]
20+
* Iterating list and if current node(head) we check if the hashmap contains the value]
21+
* if yes the we increment the ans by one and setting the flag to false
22+
*
23+
*
24+
*
25+
* Time Complexity: O(N)
26+
* Space Complexity : O(N)
27+
*/
28+
29+
30+
/**
31+
* Definition for singly-linked list.
32+
* public class ListNode {
33+
* int val;
34+
* ListNode next;
35+
* ListNode() {}
36+
* ListNode(int val) { this.val = val; }
37+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
38+
* }
39+
*/
40+
class Solution {
41+
public int numComponents(ListNode head, int[] nums) {
42+
// Create a HashMap to store the values from nums as keys and their indices as values
43+
HashMap<Integer, Integer> hm = new HashMap<>();
44+
for (int i = 0; i < nums.length; i++) {
45+
hm.put(nums[i], i);
46+
}
47+
48+
boolean flag = true; // Flag to track if a connected component is found
49+
int ans = 0; // Variable to store the number of connected components
50+
51+
// Traverse the linked list
52+
while (head != null) {
53+
// Check if the current node's value is present in the HashMap
54+
while (head != null && hm.containsKey(head.val)) {
55+
head = head.next; // Move to the next node
56+
57+
// If this is the start of a new connected component, increment the answer
58+
if (flag) {
59+
ans += 1;
60+
flag = false;
61+
}
62+
}
63+
flag = true; // Reset the flag
64+
65+
if (head != null) {
66+
head = head.next; // Move to the next node
67+
}
68+
}
69+
70+
return ans;
71+
}
72+
}

0 commit comments

Comments
 (0)