Unit 10 Session 1 (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.
HAPPY CASE
Input: head = [1, 2, 3, 4, 5]
Output: [5, 4, 3, 2, 1]
Explanation: The list is reversed to become [5, 4, 3, 2, 1].
HAPPY CASE
Input: head = [1]
Output: [1]
Explanation: The list has only one node, so the reversed list is the same.
EDGE CASE
Input: head = []
Output: None
Explanation: The list is empty, so the reversed list is also None.
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, we want to consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Iterate through the linked list and reverse the pointers at each node. Use three pointers to track the previous, current, and next nodes.
1. Initialize previous to None (this will be the new head of the reversed list).
2. Initialize current to head (start with the head of the original list).
3. While current is not None:
a. Store the next node in a temporary variable next_node.
b. Reverse the current node's pointer by setting current.next to previous.
c. Move the previous pointer to the current node.
d. Move the current pointer to the next_node.
4. Return previous (this will be the new head of the reversed list).
Implement the code to solve the algorithm.
def reverse(head):
previous = None # This will eventually become the new head of the reversed list
current = head # Start with the head of the original list
while current:
next_node = current.next # Temporarily store the next node
current.next = previous # Reverse the current node's pointer
previous = current # Move pointers one position forward
current = next_node # Continue to next node
return previous # At the end, 'previous' will be the new head of the reversed list
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
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 we need to traverse all nodes in the list.O(1)
because we only use a constant amount of extra space.