HackerRank – Compare two linked lists Solution in JavaScript

Compare two linked lists 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.

Problem Statement

You’re given the pointer to the head nodes of two linked lists. Compare the data in the nodes of the linked lists to check if they are equal. If all data attributes are equal and the lists are the same length, return 1. Otherwise, return 0.

Read full details and access the challenge on Compare two linked lists | HackerRank

Solution

function CompareLists(llist1, llist2) {
    while (llist1 || llist2) {
        if (llist1?.data !== llist2?.data) return 0;
        llist1 = llist1.next;
        llist2 = llist2.next;
    }
    return 1;
}

Time Complexity : O(n)

Space Complexity : O(1)

We can check whether the 2 linked lists are equal or not by traversing through both lists at the same time with a while loop and checking if the nodes are the same in each iteration.

First, we use a while loop that will continue as long as either list still has a node to traverse.

In each iteration, we compare both nodes to check if they are unequal. If they are, we return 0 meaning they’re not the same.

We use optional chaining (?.) in case of one of the nodes being undefined, otherwise there may be an error.

If the nodes are equal, we’ll keep traversing and finally return 1 meaning the linked lists are equal.

We’re using a while loop and no extra data structure so we have O(n) time and O(1) space complexity.

Conclusion

That’s how you can solve the Compare two linked lists Challenge in HackerRank.

For me personally, I learned how to traverse two lists at once and using optional chaining to avoid errors.

Overall, it is a good challenge to improve our understanding on linked lists.

If you have another 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 in JavaScript for the upcoming posts!

See you next post!

Leave a Comment