HackerRank – Insert a node at the head of a linked list JavaScript Solution

Insert a node at the head of a linked list 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(1) time and O(1) space complexity.

Problem Statement

Given a pointer to the head of a linked list, insert a new node before the head. The next value in the new node should point to head and the data value should be replaced with a given value. Return a reference to the new head of the list. The head pointer given may be null meaning that the initial list is empty.

Read full details and access the challenge on Insert a node at the head of a linked list | HackerRank

Solution

function insertNodeAtHead(head, data) {
    let newNode = new SinglyLinkedListNode(data);
    if (!head) {
        head = newNode;
    } else {
        let temp = head;
        head = newNode;
        head.next = temp;
    }
    return head;
}

Time Complexity : O(1)

Space Complexity : O(1)

For this challenge, we’re just adding a node a the start of the linked list if it’s not empty.

First, we initialize the new node.

Then, we check if it’s empty. If it is, we just assign the new node as the head.

If it’s not empty, we also assign the new node as the head, but we assign the old head as the new node’s next value.

Then we return head.

We have no loops and no extra array in this solution, so we have O(1) time and O(1) space complexity.

Conclusion

That’s how you can solve the Insert a node at the head of a linked list Challenge in HackerRank.

This is a good practice to solidify your basics on linked lists.

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