Leetcode 25: Reverse nodes in k-group

This problem is similar to reverse a linked list but we wrap that in a loop so we do it repeatedly while there are k nodes ahead. We also need to wire the previous k sequence end with the the current new start.

Beware of a test case (list:[1], k:2) where k being bigger than number of nodes in list despite the problem description saying that wouldn’t happen.

A more efficient way is to not count ahead but instead undo the final reversal if we reach the end before we process k nodes. Maybe I’ll try that another time. Count ahead solution seemed simpler to code.

This entry was posted in programming and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *