234. Palindrome Linked List

Easy

Problem:

Given the head of a singly linked list, return true if it is a palindrome or false otherwise.

Input: head = [1,2,2,1] 
Output: true

https://leetcode.com/problems/palindrome-linked-list/arrow-up-right

What to learn:

List pop(index)

  • The pop() method takes a single argument (index) and returns the item present at the given index. This item is also removed from the list.

  • The argument passed to the method is optional. If not passed, the default index -1 is passed as an argument (index of the last item).

  • If the index passed to the method is not in range, it throws IndexError: pop index out of range exception.

Runner

circle-check
  • Generally, the fast runner (pointer) skips two steps while the slow runner (pointer) moves one step at a time.

  • When the fast runner reaches the end of the linked list, the slow runner will be pointing exactly to the midpoint of the linked list.

  • This method of finding the midpoint allows us to compare values, attempt reversals, and do much more from that point onwards.

Therefore, this technique is essential and widely used in problems related to linked lists.

Solution:

To determine whether it is a palindrome, a data structure that can extract from both the front and the back is needed.

List

The linked list input is converted into a Python list for the solution.

Deque

The list constructed as a dynamic array is not a suitable data type for fetching the first item. This is because if you take out the first value, all the values shift by one place, resulting in a time complexity of O(n)O(n).

Python's Deque is a doubly linked list structure that can extract from both directions with a time complexity of O(1)O(1).

Runner

Last updated