Grokking 75: Top Coding Interview Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Reverse Nodes in k-Group (hard)
Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Problem Statement

Given the head of a linked list, reverse each k node of the list at a time and return the modified list.

Here, k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k, the remaining nodes at the end should stay as they are.

Note: You can only change the nodes themselves, not the values inside them.

Examples

  1. Example 1:

    • Input: head = [1, 2, 3, 4, 5, 6], k = 3
    • Expected Output: [3, 2, 1, 6, 5, 4]
    • Justification: The list is reversed in groups of three. First group [1, 2, 3] becomes [3, 2, 1] and the second group [4, 5, 6] becomes [6, 5, 4].
  2. Example 2:

    • Input: head = [1, 2, 3, 4, 5], k = 2
    • Expected Output: [2, 1, 4, 3, 5]
    • Justification: The list is reversed in groups of two. First group [1, 2] becomes [2, 1] and the second group [3, 4] becomes [4, 3]. The last node [5] remains unchanged.
  3. Example 3:

    • Input: head = [1, 2, 3, 4, 5, 6, 7], k = 4
    • Expected Output: [4, 3, 2, 1, 5, 6, 7]
    • Justification: The list is reversed in groups of four. First group [1, 2, 3, 4] becomes [4, 3, 2, 1]. The remaining nodes [5, 6, 7] are left as they are because their count is less than k.

Constraints:

  • The number of nodes in the list is n.
  • 1 <= k <= n <= 5000
  • 0 <= Node.val <= 1000

Try it yourself

Try solving this question here:

Python3
Python3

. . . .

.....

.....

.....

Like the course? Get enrolled and start learning!

Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible