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?
markdown
Input: 1 -> 2 -> 3 -> 4
Output: 3 -> 4
HAPPY CASE
Input: head = [1,2,3,4,5]
Output: [3,4,5]
Explanation: The middle node of the list is node 3.
Input: head = [1,2,3,4,5,6]
Output: [4,5,6]
Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.
EDGE CASE
Input: head = [1]
Output: [1]
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: Every time we move slow pointer once, we move fast pointer twice. Once fast pointer reaches the end, the slow pointer is pointing at the middle node.
1) Initialize slow and fast pointer at head node
2) While fast pointer and fast.next pointer exist
a) Move slow pointer forward once
b) Move fast pointer forward twice
3) Return slow pointer
⚠️ Common Mistakes
Implement the code to solve the algorithm.
class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
# Initialize slow and fast pointer at head node
slow = fast = head
# While fast pointer and fast.next pointer exist
while fast and fast.next:
# Move slow pointer forward once
slow = slow.next
# Move fast pointer forward twice
fast = fast.next.next
# Return slow pointer
return slow
class Solution {
public ListNode middleNode(ListNode head) {
// Initialize slow and fast pointer at head node
ListNode slow = head, fast = head;
// While fast pointer and fast.next pointer exist
while (fast != null && fast.next != null) {
// Move slow pointer forward once
slow = slow.next;
// Move fast pointer forward twice
fast = fast.next.next;
}
// Return slow pointer
return slow;
}
}
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 half the nodes in the linked list.O(1)
because we only need two pointers for memory.