10. Reverse Linked List
easyAsked at SquarespaceReverse a singly linked list in place; Squarespace uses it as a fundamentals check before harder block-ordering problems.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given the head of a singly linked list, reverse the list and return the new head. Solve it both iteratively and recursively if asked.
Constraints
0 <= number of nodes <= 5000-5000 <= Node.val <= 5000
Examples
Example 1
head=[1,2,3,4,5][5,4,3,2,1]Example 2
head=[][]Approaches
1. Stack rebuild
Push all nodes onto a stack then re-link them in pop order.
- Time
- O(n)
- Space
- O(n)
const s=[]; let n=head; while(n){ s.push(n); n=n.next; }
const dummy={next:null}; let cur=dummy;
while(s.length){ cur.next=s.pop(); cur=cur.next; }
cur.next=null; return dummy.next;Tradeoff:
2. Three-pointer in-place reverse
Walk once, flipping each next pointer as you go using prev/cur/next pointers. Constant memory.
- Time
- O(n)
- Space
- O(1)
function reverseList(head) {
let prev = null, cur = head;
while (cur) {
const next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
}Tradeoff:
Squarespace-specific tips
Squarespace evaluators want clean pointer juggling and a note that the same in-place flip powers their template section reordering when a user drags a block.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Reverse Linked List and other Squarespace interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →