TIP102 Unit 5 Session 2 Advanced (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
- Established a set (2-3) of test cases to verify their own solution later.
- Established a set (1-2) of edge cases to verify their solution handles complexities.
- Have fully understood the problem and have no clarifying questions.
- Have you verified any Time/Space Constraints for this problem?
True
since an empty list is symmetric.True
since a single element is symmetric.HAPPY CASE
Input: head = Node("Bitterling") -> Node("Crawfish") -> Node("Bitterling")
Output: True
Explanation: The linked list reads the same forwards and backwards.
EDGE CASE
Input: head = Node("Bitterling") -> Node("Carp") -> Node("Koi")
Output: False
Explanation: The linked list does not read the same forwards and backwards.
Match what this problem looks like to known categories of problems, e.g. Linked List or Dynamic Programming, and strategies or patterns in those categories.
For Linked List palindrome problems, we want to consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Use the two-pointer technique to find the middle of the list, reverse the second half, and then compare it with the first half.
1) Use the two-pointer technique to find the middle of the linked list.
2) Reverse the second half of the linked list.
3) Compare the first half and the reversed second half node by node.
4) If all corresponding nodes match, return `True`; otherwise, return `False`.
Implement the code to solve the algorithm.
class Node:
def __init__(self, value=None, next=None):
self.value = value
self.next = next
def is_symmetric(head):
if head is None or head.next is None:
return True # A list with 0 or 1 element is symmetric
# Find the middle of the list
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
# Reverse the second half of the list
prev = None
while slow:
next_node = slow.next
slow.next = prev
prev = slow
slow = next_node
# Compare the first half and the reversed second half
left, right = head, prev
while right: # Only need to compare till the end of the second half
if left.value != right.value:
return False
left = left.next
right = right.next
return True
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Example:
head = Node("Bitterling", Node("Crawfish", Node("Bitterling")))
print(is_symmetric(head)) # Expected Output: True
head = Node("Bitterling", Node("Carp", Node("Koi")))
print(is_symmetric(head)) # Expected Output: False
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Time Complexity:
Space Complexity: