You’re interviewing for a backend or data engineering role at a FAANG-level company. The interviewer describes a real product scenario:
A large-scale data pipeline stores a sequence of events in a singly linked list. For performance and batching reasons, the platform processes events in fixed-size chunks.
As part of a transformation step, the system must reverse the order of nodes within each chunk of size k (to simulate reverse chronological batching, rollback grouping, or chunk-based reprocessing). However, if the remaining nodes are fewer than k, they must remain in their original order to preserve data integrity.
This is a common practice coding problem for DSA question might ask in Google, Amazon, Netflix, Meta, Apple, Microsoft, Uber, and Bloomberg interviews.
Your Task
Given the head of a singly linked list and an integer k, reverse the nodes of the list k at a time and return the modified list.
Rules:
- Only nodes in complete groups of size
k are reversed - If the number of nodes left is less than
k, leave them as is - You must not change node values, only pointers
Input Format
head: the head node of a singly linked listk: an integer representing group size
Each node is defined as:
ListNode { int val; ListNode next; }
Output Format
- Return the head of the modified linked list
Examples
Example 1:
Input: head = [1,2,3,4,5]
k = 2
Output: [2,1,4,3,5]
Example 2:
Input: head = [1,2,3,4,5]
k = 3
Output: [3,2,1,4,5]
Example 3:
Input: head = [1,2,3,4,5,6]
k = 3
Output: [3,2,1,6,5,4]