Greatest Node - codepath/compsci_guides GitHub Wiki
Unit 5 Session 2 (Click for link to problem statements)
TIP102 Unit 5 Session 2 Advanced (Click for link to problem statements)
Problem Highlights
- 💡 Difficulty: Easy
- ⏰ Time to complete: 5-10 mins
- 🛠️ Topics: Linked Lists, Finding Maximum
1: U-nderstand
Understand what the interviewer is asking for by using test cases and questions about the problem.
- Q: What happens if the linked list is empty?
- A: The function should return
None
.
- A: The function should return
- Q: What happens if all the values in the linked list are negative?
- A: The function should correctly identify the maximum value, even if it is negative.
HAPPY CASE
Input: head = Node(5) -> Node(6) -> Node(7) -> Node(8)
Output: 8
Explanation: The largest value in the linked list is 8.
EDGE CASE
Input: head = None
Output: None
Explanation: When the linked list is empty, the function returns None.
2: M-atch
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:
- Traversal of a linked list
- Comparison of node values to find the maximum
3: P-lan
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Traverse the linked list, comparing each node's value to find the maximum.
1) If the head is `None`, return `None`.
2) Initialize `max_val` to the value of the head node.
3) Traverse the linked list starting from the second node.
4) If the current node's value is greater than `max_val`, update `max_val`.
5) Continue until all nodes have been visited.
6) Return `max_val`.
⚠️ Common Mistakes
- Forgetting to handle the case where the linked list is empty.
- Not correctly updating the maximum value as you traverse the list.
4: I-mplement
Implement the code to solve the algorithm.
def find_max(head):
if not head:
return None
current = head
max_val = head.value
while current:
if current.value > max_val:
max_val = current.value
current = current.next
return max_val
5: R-eview
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
- Verify the maximum value returned matches the expected value for different linked lists.
Example:
head1 = Node(5, Node(6, Node(7, Node(8))))
print(find_max(head1)) # Expected Output: 8
head2 = Node(5, Node(8, Node(6, Node(7))))
print(find_max(head2)) # Expected Output: 8
6: E-valuate
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Time Complexity:
- O(N), where N is the number of nodes in the linked list. We traverse the entire list to find the maximum value.
Space Complexity:
- O(1), since we only use a constant amount of extra space for variables (max_val, current). This solution is efficient for finding the maximum value in a linked list with minimal space usage.