Skip to content

Bug Report for reverse-nodes-in-k-group #5560

@cyperpant

Description

@cyperpant

Bug Report for https://neetcode.io/problems/reverse-nodes-in-k-group

The following Python solution was accepted in NeetCode, but LeetCode rightfully returned Wrong Answer.

The testcase is head = [1,3,6,5,6,5,8,4,8,2], k = 7.

class Solution:
    def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        cur = head
        sublist: ListNode = []
        is_new_head_found = False
        while True:
            if not cur and len(sublist) != k:
                return head
            if len(sublist) < k:
                if len(sublist) == k - 1 and not is_new_head_found:
                    is_new_head_found = True
                    head = cur
                sublist.append(cur)
                if len(sublist) < k:
                    cur = cur.next
                    continue
            counter = 0
            peek = cur
            while counter < k:
                if peek is None:
                    peek = cur
                counter += 1
                peek = peek.next
            cur = cur.next
            prev = peek or cur
            for node in sublist:
                node.next = prev
                prev = node
            sublist = []

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions