Insert a Node at the Tail 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(n) time and O(1) space complexity.
Problem Statement
You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node of the linked list formed after inserting this new node. The given head pointer may be null, meaning that the initial list is empty.
Read full details and access the challenge on Insert a Node at the Tail of a Linked List | HackerRank
Solution
function insertNodeAtTail(head, data) {
let newNode = new SinglyLinkedListNode(data);
if (head === null) {
head = newNode;
} else {
let current = head;
while (current.next) {
current = current.next;
}
current.next = newNode;
}
return head;
}
Time Complexity : O(n)
Space Complexity : O(1)
This is a standard method that a linked list should have.
First, we initialize the data that is to be added as a new node.
If the linked list is empty (head === null
), we assign the new node as head.
If it isn’t, we traverse to the end of the linked list and add it as the last node.
Finally, we return the head variable.
We’re traversing through the linked list once so we have O(n) time and since we stored no extra space, we have O(1) space complexity.
Conclusion
That’s how you can solve the Insert a Node at the Tail of a Linked List Challenge in HackerRank.
This is a must know if you’re learning data structure and serve as a good practice.
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!