15 · Linked Lists

#25 Reverse Nodes in k-Group

Hardsolve on LeetCode ↗

frequently reported atMicrosoftAmazonGoogleMeta

the problem

In plain words

Given the head of a linked list and an integer k, reverse the nodes k at a time and return the new head. If fewer than k nodes are left at the end, leave them in their original order. Only the links may change, not the values.

in head = [1,2,3,4,5], k = 2

out [2,1,4,3,5]

in head = [1,2,3,4,5], k = 3

out [3,2,1,4,5]

  • 1 ≤ k ≤ n ≤ 5000
  • 0 ≤ Node.val ≤ 1000
  • Follow-up: O(1) extra memory

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #92
      Reverse Linked List II
      Mediumin Linked Lists
    2. #206
      Reverse Linked List
      Easyin Linked Lists
    3. #24
      Swap Nodes in Pairs
      Mediumin Recursion