Reverse Nodes in K-Group
- 2 min read
- LC-Hard
- Linked List
Solution
- Listen bro don't even try to memorize this problem
- It's intuitive as fuck, only thing is that the pointers are annoying to move around.
- But you can do it! You solved it on your own!!
- The code is ugly as phuck but the NeetCode video was so bad you had to do it yourself
| Time | Space | Explanation |
|---|
O(i don't even know) | O() | |
def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
dummy = ListNode(0, head)
def get_kth_node(node, n):
if node is None:
return None, None
cur = node
while n:
n -= 1
node = node.next
if node is None: # Group where length is less than k
return None, None
return node, node.next
def reverse(node):
prev, curr = None, node
while curr:
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
return prev
prev_tail, prev_prev_tail = None, None
first = True
while True:
kth, next_head = get_kth_node(head, k - 1)
if kth is None and next_head is None:
prev_tail.next = head
break
kth.next = None
prev_prev_tail = prev_tail
prev_tail = head
new_reversed_head = reverse(head)
if first:
dummy.next = new_reversed_head
first = False
else:
prev_prev_tail.next = new_reversed_head
head = next_head
return dummy.next