HackerRank – Print in Reverse Solution in JavaScript

Print in Reverse 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

Given a pointer to the head of a singly-linked list, print each data value from the reversed list. If the given list is empty, do not print anything.

Read full details and access the challenge on Print in Reverse | HackerRank

Intuitive Solution

function reversePrint(llist) {
    let reversed = [];
    while (llist) {
        reversed.unshift(llist.data);
        llist = llist.next;
    }
    reversed.forEach(data => {
        console.log(data);
    })
}

Time Complexity : O(n)

Space Complexity : O(n)

The first solution that I can think of is storing the linked list into an array with unshift so we can have a reversed order. Then, we loop through the reversed array and print all the data.

We’re using loops and an array so we have O(n) time and O(n) space complexity.

Well, we can further optimize this code into O(1) space.

Optimized Solution

function reversePrint(llist) {
    if (llist) {
        reversePrint(llist.next);
        console.log(llist.data);        
    }
}

Time Complexity : O(n)

Space Complexity : O(1)

In this optimized solution, we’ll be using recursion to go to the end of the linked list and then print the data.

The way this works is recursion will go to the last node and execute the functions in reverse for you. So, you can print the linked list in reverse

We’re traversing through the linked list once and we use no extra data structure, so we have O(n) time and O(1) space complexity.

Conclusion

That’s how you can solve and optimize the Print in Reverse Challenge in HackerRank.

This is a good practice for linked lists and to learn how to optimize your code.

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