HackerRank – Delete a Node Solution in JavaScript

Delete a Node is a coding challenge with easy difficulty in the HackerRank data structures category. In this blog post, we’ll discuss how we can solve it in JavaScript in O(n) time and O(1) space complexity.

Problem Statement

Delete the node at a given position in a linked list and return a reference to the head node. The head is at position 0. The list may be empty after you delete the node. In that case, return a null value.

Read full details and access the challenge on Delete a Node | HackerRank

Solution

function deleteNode(llist, position) {
    if (position === 0) return llist = llist.next;
    let head = llist, currPos = 0, prev;
    while (head) {
        if (currPos === position) {
            prev.next = head.next;
        }
        prev = head;
        head = head.next;
        currPos++;
    }
    return llist;
}

Time Complexity : O(n)

Space Complexity : O(1)

We can solve this challenge by first checking if the node we have to delete is at the head or 0 position. If it is, we just assign the next node as the head node and return it.

If it’s not, we traverse through the linked list until we reach the intended position and delete the node. We delete the node by skipping that node. Just assign the next node as the previous node’s next node to skip the current node.

And don’t forget to return the original head node.

We have a while loop and no extra data structure in this solution, so we have O(n) time and O(1) space complexity.

Conclusion

That’s how you can solve the Delete a Node Challenge in HackerRank.

This is a good practice to improve your basics on linked lists in JavaScript.

If you have an approach different from mine, please do comment below!

Check out the rest of my blog for more helpful contents on Data Structures and Algorithms in JavaScript! We’ll also discuss more HackerRank solutions using JavaScript in this blog!

See you next post!

Leave a Comment