-
Notifications
You must be signed in to change notification settings - Fork 125
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add remove-nth-node-from-end-of-list solution
- Loading branch information
Showing
1 changed file
with
76 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
// 🚀 Optimized Approach: Two-Pointer Method (One-Pass) | ||
// ✅ Time Complexity: O(N), where N is the number of nodes | ||
// ✅ Space Complexity: O(1) | ||
|
||
/** | ||
* 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} n | ||
* @return {ListNode} | ||
*/ | ||
var removeNthFromEnd = function (head, n) { | ||
let dummy = new ListNode(0, head); | ||
let fast = dummy; | ||
let slow = dummy; | ||
|
||
for (let i = 0; i <= n; i++) { | ||
fast = fast.next; | ||
} | ||
|
||
while (fast) { | ||
fast = fast.next; | ||
slow = slow.next; | ||
} | ||
|
||
slow.next = slow.next.next; | ||
|
||
return dummy.next; | ||
}; | ||
|
||
// ✅ Time Complexity: O(N), where N is the number of nodes | ||
// ✅ Space Complexity: O(1) | ||
|
||
/** | ||
* 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} n | ||
* @return {ListNode} | ||
*/ | ||
// var removeNthFromEnd = function (head, n) { | ||
// let length = 0; | ||
|
||
// let node = head; | ||
|
||
// // Compute the length of the linked list | ||
// while (node) { | ||
// length += 1; | ||
// node = node.next; | ||
// } | ||
|
||
// // Create a dummy node pointing to head (helps handle edge cases) | ||
// let dummy = new ListNode(0, head); | ||
// node = dummy; | ||
|
||
// // Move to the node just before the one to be removed | ||
// for (let i = 0; i < length - n; i++) { | ||
// node = node.next; | ||
// } | ||
|
||
// // Remove the nth node from the end by updating the next pointer | ||
// node.next = node.next.next; | ||
|
||
// // Return the modified linked list (excluding the dummy node) | ||
// return dummy.next; | ||
// }; |