Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 148 · Sorting

Sort List

LeetCode 148 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

Split at the middle, sort halves, merge.

ಮಧ್ಯಮLinked ListTwo PointersDivide and ConquerSortingMerge Sort
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು Sort List (LeetCode 148) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Sorting ಪ್ಯಾಟರ್ನ್‌ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.

ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್‌ನಲ್ಲಿದೆ.

Intuition

Merge sort fits linked lists perfectly: split at the middle with slow/fast pointers, sort each half recursively, and merge the two sorted halves with the two-list merge.

Approach

  1. 1

    Base case: empty or single node.

  2. 2

    getMid splits the list in two.

  3. 3

    Recursively sort both halves.

  4. 4

    Merge them.

ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ

Top-down merge sortPythonO(n log n) time
class Solution:
    def mergeTwoLists(self, list1, list2):
        dummy = ListNode(-1)
        temp = dummy
        while list1 is not None and list2 is not None:
            if list1.val <= list2.val:
                temp.next = list1
                temp = temp.next
                list1 = list1.next
            else:
                temp.next = list2
                temp = temp.next
                list2 = list2.next
        while list1 is not None:
            temp.next = list1
            temp = temp.next
            list1 = list1.next
        while list2 is not None:
            temp.next = list2
            temp = temp.next
            list2 = list2.next
        return dummy.next

    def getMid(self, head):
        slow = head
        midprev = None
        fast = head
        while fast and fast.next:
            midprev = slow
            slow = slow.next
            fast = fast.next.next
        midprev.next = None  # break right part
        return slow

    def sortList(self, head):
        if not head or not head.next:
            return head
        mid = self.getMid(head)
        left = self.sortList(head)
        right = self.sortList(mid)
        return self.mergeTwoLists(left, right)
ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

Sort List — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು

Sort List ಹಿಂದಿನ intuition ಏನು?

Merge sort fits linked lists perfectly: split at the middle with slow/fast pointers, sort each half recursively, and merge the two sorted halves with the two-list merge.

Sort List (LeetCode 148) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?

1. Base case: empty or single node. 2. getMid splits the list in two. 3. Recursively sort both halves. 4. Merge them.

Sort List ನ time ಮತ್ತು space complexity ಎಷ್ಟು?

Time: O(n log n). Space: O(log n) recursion. (Accepted approach: Top-down merge sort.)

Sort List ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?

Cut the list at the middle (midPrev.next = None) or the recursion never ends.