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.