Skip to content

Commit aaeea9a

Browse files
committed
chore(doc): is palindrome comment
1 parent d81c5d3 commit aaeea9a

File tree

1 file changed

+15
-0
lines changed
  • datastructures/linked_lists/doubly_linked_list

1 file changed

+15
-0
lines changed

datastructures/linked_lists/doubly_linked_list/__init__.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -494,6 +494,21 @@ def alternate_split(self) -> tuple:
494494
return first, second
495495

496496
def is_palindrome(self) -> bool:
497+
"""
498+
Uses two pointer approach to check if this is a palindrome linked list. Since this is a doubly linked list, each
499+
node knows about the previous node in the linked list. Therefore, it is possible to do this in 2 passes. First
500+
two pointers are initialized and set to the head node, then the last pointer is traversed until it reaches the
501+
last node in the doubly linked list. This results in an O(n) computation task, where n is the number of nodes.
502+
503+
Second, the second pass compares the first pointer to the last pointer as long as we don't reach the middle,then
504+
we can check the data item at each pointer. if they do not match, then we return false, if they do, the first
505+
pointer moves 1 position, while the last pointer moves in the opposite direction using the previous pointer.
506+
This continues until the two pointers reach the middle.
507+
508+
Space Complexity results in O(1) as no extra space is required other than reference to the pointers in the list.
509+
Time is O(n) as the algorithm has to traverse the linked list to set the last pointer to the end of the linked
510+
list.
511+
"""
497512
if self.head:
498513
# A LinkedList with 1 Node is a Palindrome
499514
if not self.head.next:

0 commit comments

Comments
 (0)