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

Palindrome Linked List

LeetCode 234 · ಸುಲಭ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

Middle → reverse second half → compare.

ಸುಲಭLinked ListTwo PointersStackRecursion
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

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

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

Intuition

Find the middle with slow/fast pointers, reverse the second half, and compare it against the first half node by node. Reverse it back afterwards to leave the list unchanged.

Approach

  1. 1

    Slow/fast to find the middle.

  2. 2

    Reverse from slow to the end.

  3. 3

    Walk both halves comparing values.

  4. 4

    Reverse the second half back.

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

Reverse second halfPythonO(n) time · O(1) space
class Solution:
    def reverseList(self, temp):
        prev = None
        while temp is not None:
            front = temp.next
            temp.next = prev
            prev = temp
            temp = front
        return prev

    def isPalindrome(self, head):
        if head is None:
            return False
        slow = head
        fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        p1 = head
        slow = self.reverseList(slow)
        p2 = slow
        is_palindrome = True
        while p1 is not None and p2 is not None:
            if p1.val != p2.val:
                is_palindrome = False
            p1 = p1.next
            p2 = p2.next
        slow = self.reverseList(slow)
        return is_palindrome
ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

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

Palindrome Linked List ಹಿಂದಿನ intuition ಏನು?

Find the middle with slow/fast pointers, reverse the second half, and compare it against the first half node by node. Reverse it back afterwards to leave the list unchanged.

Palindrome Linked List (LeetCode 234) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?

1. Slow/fast to find the middle. 2. Reverse from slow to the end. 3. Walk both halves comparing values. 4. Reverse the second half back.

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

Time: O(n). Space: O(1). (Accepted approach: Reverse second half.)

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

Restoring the list is good practice — callers may reuse it.