Solving Leetcode Interviews in Seconds with AI: Palindrome Linked List
Introduction
In this blog post, we will explore how to solve the LeetCode problem "234" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
Given the head of a singly linked list, return true if it is a palindrome or false otherwise. Example 1: Input: head = [1,2,2,1] Output: true Example 2: Input: head = [1,2] Output: false Constraints: The number of nodes in the list is in the range [1, 105]. 0 <= Node.val <= 9 Follow up: Could you do it in O(n) time and O(1) space?
Explanation
Here's the approach to solve the palindrome linked list problem efficiently:
- Find the Middle: Locate the middle of the linked list using the fast and slow pointer approach.
- Reverse the Second Half: Reverse the linked list starting from the middle node.
Compare: Compare the first half of the original list with the reversed second half. If they are identical, the list is a palindrome.
Time Complexity: O(n), Space Complexity: O(1)
Code
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def isPalindrome(head: ListNode) -> bool:
"""
Checks if a singly linked list is a palindrome.
Args:
head: The head of the linked list.
Returns:
True if the linked list is a palindrome, False otherwise.
"""
if not head or not head.next:
return True
# Find the middle of the linked list
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
# Reverse the second half of the linked list
prev, curr = None, slow
while curr:
next_node = curr.next
curr.next = prev
prev = curr
curr = next_node
# Compare the first half and the reversed second half
left, right = head, prev
while right:
if left.val != right.val:
return False
left = left.next
right = right.next
return True