File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed
Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change @@ -1382,4 +1382,40 @@ while (current != null) {
13821382
13831383return prev;
13841384}
1385+ ```
1386+
1387+ ### 2 - 11 ) Linked List Components
1388+
1389+ ```java
1390+ // java
1391+ // LC 817
1392+ // V1
1393+ // IDEA: set, linkedlist (gpt)
1394+ public int numComponents_1(ListNode head, int [] nums) {
1395+ // Convert nums array to a HashSet for O(1) lookups
1396+ Set<Integer > numsSet = new HashSet<> ();
1397+ for (int num : nums) {
1398+ numsSet. add(num);
1399+ }
1400+
1401+ int count = 0 ;
1402+ boolean inComponent = false ;
1403+
1404+ // Traverse the linked list
1405+ while (head != null ) {
1406+ if (numsSet. contains(head. val)) {
1407+ // Start a new component if not already in one
1408+ if (! inComponent) {
1409+ count++ ;
1410+ inComponent = true ;
1411+ }
1412+ } else {
1413+ // End the current component
1414+ inComponent = false ;
1415+ }
1416+ head = head. next;
1417+ }
1418+
1419+ return count;
1420+ }
13851421```
You can’t perform that action at this time.
0 commit comments