Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 61 · Reversal

Rotate List

LeetCode 61 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

Ring, then cut after length − k % length nodes.

நடுத்தரம்Linked ListTwo Pointers
LeetCode இல் திற ↗

நான் Rotate List (LeetCode 61) ஐ இப்படித் தீர்த்தேன் — Reversal பேட்டர்னின் ஒரு நடுத்தரம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.

கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.

Intuition

Connect the tail to the head to make a ring, then break it at the right place: the new tail is length − (k mod length) steps from the head.

Approach

  1. 1

    Find the length and the tail; link tail → head.

  2. 2

    k %= length.

  3. 3

    Walk length − k − 1 steps to the new tail.

  4. 4

    New head = newTail.next; set newTail.next = None.

நான் எப்படித் தீர்த்தேன்

Make a ring and cutPythonO(n) time · O(1) space
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        if not head:
            return head
        def get_prev_node(node,k):
            k-=1
            while k!=0:
                node = node.next
                k-=1
            return node
        prev_node = None
        length = 1
        node = head
        #move till last node
        while node.next:
            length +=1
            node = node.next
        #make it circular
        node.next = head
        #5 nodes
        k = k%length
        prev_node = get_prev_node(head,length-k) #3
        head= prev_node.next
        prev_node.next=None
        return head
ஸ்டெப்-த்ரூ ஏற்றுகிறது…

Rotate List — அடிக்கடி கேட்கப்படும் கேள்விகள்

Rotate List பின்னாலுள்ள intuition என்ன?

Connect the tail to the head to make a ring, then break it at the right place: the new tail is length − (k mod length) steps from the head.

Rotate List (LeetCode 61) ஐ எப்படித் தீர்ப்பது?

1. Find the length and the tail; link tail → head. 2. k %= length. 3. Walk length − k − 1 steps to the new tail. 4. New head = newTail.next; set newTail.next = None.

Rotate List இன் time மற்றும் space complexity என்ன?

Time: O(n). Space: O(1). (Accepted approach: Make a ring and cut.)

Rotate List இல் பொதுவான தவறுகள் என்ன?

Empty list returns immediately. k can be far larger than the length.