Reverse first k nodes of a linked list
Filed under Paytm
Free read 2 of 3Verify how to handle lists shorter than k (reverse all remaining nodes).
The question
Given the head of a linked list and an integer k, reverse the first k nodes of the linked list. If there are fewer than k nodes left, reverse all remaining nodes.
Constraints
- The number of nodes in the list is in the range [1, 5000].
- 0 <= Node.val <= 1000
- 1 <= k <= 5000
Examples
- Input
- head = [1, 2, 3, 4, 5], k = 3
- Output
- [3, 2, 1, 4, 5]
- Why
- The first 3 nodes are reversed, leaving the remaining nodes 4 and 5 untouched.
Approach
Verify how to handle lists shorter than k (reverse all remaining nodes).
Collect node values into an array, reverse the first k elements, and rebuild or rewrite the linked list values.
Iterate through the first k nodes while standardly reversing pointers, keeping track of the original head and the next starting node.
Empty list, single node list, or k larger than the list size.
Solution
O(k) time, O(1) space
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseKNodes(self, head: ListNode, k: int) -> ListNode:
prev, curr = None, head
count = 0
while curr and count < k:
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
count += 1
if head:
head.next = curr
return prev
Tips
- What they are testing: Test when k is greater than list length, k equals 1, and k equals list length.
- Common mistake: Failing to correctly reconnect the newly reversed portion to the rest of the list.
Related Paytm questions
Collected from public candidate posts and coding forums. Updated Nov 2026.