โ† Paytm questions

Reverse first k nodes of a linked list

Filed under Paytm

Free read 2 of 3

Verify 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

  1. Verify how to handle lists shorter than k (reverse all remaining nodes).

Solution

O(k) time, O(1) space

Python
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.