TIP102 Unit 6 Session 1 Advanced (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
HAPPY CASE
Input: experiment_results1 = Node(1, Node(2, Node(3, Node(4, Node(5)))))
Output: 1 -> 3 -> 5 -> 2 -> 4
Explanation: All nodes in odd positions are grouped before nodes in even positions.
HAPPY CASE
Input: experiment_results2 = Node(2, Node(1, Node(3, Node(5, Node(6, Node(4, Node(7)))))))
Output: 2 -> 3 -> 6 -> 7 -> 1 -> 5 -> 4
Explanation: All nodes in odd positions are grouped before nodes in even positions.
EDGE CASE
Input: exp_results = Node(1)
Output: 1
Explanation: A single-node list remains unchanged.
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 problems involving Reorganization, we want to consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
General Idea: We will use two pointers, one for odd positions and one for even positions. As we traverse the list, we will rearrange the links to separate the odd and even nodes. Finally, we will link the last odd node to the head of the even list.
1) If the list is empty or has only one node, return the list as is.
2) Initialize two pointers, `odd` and `even`, pointing to the first and second nodes, respectively.
3) Traverse the list:
a) Link the current odd node to the next odd node.
b) Move the odd pointer to the next odd node.
c) Link the current even node to the next even node.
d) Move the even pointer to the next even node.
4) After the loop ends, link the last odd node to the head of the even list.
5) Return the head of the reorganized list.
⚠️ Common Mistakes
Implement the code to solve the algorithm.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def odd_even_experiments(exp_results):
if not exp_results or not exp_results.next:
return exp_results
odd = exp_results
even = exp_results.next
even_head = even # Save the head of the even list
while even and even.next:
odd.next = even.next # Link current odd node to the next odd node
odd = odd.next # Move odd pointer to the next odd node
even.next = odd.next # Link current even node to the next even node
even = even.next # Move even pointer to the next even node
odd.next = even_head # Link the last odd node to the head of the even list
return exp_results
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
experiment_results1
and experiment_results2
linked lists to verify that the function correctly rearranges the list.Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Assume N
represents the number of nodes in the linked list.
O(N)
because each node is visited exactly once.O(1)
because the algorithm uses a constant amount of extra space for pointers.