Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Reverse Linked List in K Groups

Medium Acceptance 60.00% Points 30.00

You are given the head of a singly linked list and an integer k. Your task is to reverse the nodes of the linked list in groups of size k and return the head of the modified list. If the remaining nodes are fewer than k, leave them unchanged.

Examples
Example 1

Example 1

Input: head = [1,2,3,4,5], k = 2

Output: [2,1,4,3,5]

Explanation: The nodes are reversed in groups of 2, while the last node remains unchanged.

Example 2

Example 2

Input: head = [1,2,3,4,5], k = 3

Output: [3,2,1,4,5]

Explanation: The first group of 3 nodes is reversed, and the remaining nodes are left unchanged.

Example 3

Example 3

Input: head = [1,2,3,4,5,6], k = 3

Output: [3,2,1,6,5,4]

Explanation: Each group of 3 nodes is reversed.

Hints
Hint 1
N/A
Constraints
  • 1 = Number of nodes = 105
  • -10? = Node.data = 10?
  • 1 = k = Number of nodes
Companies
Amazon Microsoft Apple Samsung Visa + 4 more
Topics
Linked List
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions