TIP102 Unit 5 Session 2 Standard (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?
n
is greater than the length of the linked list?
n
is 0
?
HAPPY CASE
Input: head = Node("Daisy") -> Node("Mario") -> Node("Toad") -> Node("Yoshi"), n = 3
Output: ["Daisy", "Mario", "Toad"]
Explanation: The function returns the values of the first 3 nodes.
EDGE CASE
Input: head = Node("Daisy") -> Node("Mario"), n = 5
Output: ["Daisy", "Mario"]
Explanation: Since `n` is greater than the length of the linked list, the function returns the values of all nodes.
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: Traverse the linked list, collecting the values of the nodes until you reach n
nodes or the end of the list.
1) Initialize an empty list `result` to store the values.
2) Initialize a pointer `current` to the head of the linked list and a counter `count` to 0.
3) Traverse the linked list:
a) Append the value of the current node to the `result` list.
b) Move the pointer to the next node and increment the counter.
c) Stop if the counter reaches `n`.
4) Return the `result` list.
⚠️ Common Mistakes
n
is greater than the length of the linked list.n
is 0
.Implement the code to solve the algorithm.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
# For testing
def print_linked_list(head):
current = head
while current:
print(current.value, end=" -> " if current.next else "\n")
current = current.next
def top_n_finishers(head, n):
result = []
current = head
count = 0
while current and count < n:
result.append(current.value)
current = current.next
count += 1
return result
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
n
to ensure the function behaves correctly.Example:
head = Node("Daisy", Node("Mario", Node("Toad", Node("Yoshi"))))
# Test with n = 3
print(top_n_finishers(head, 3)) # Expected Output: ["Daisy", "Mario", "Toad"]
# Test with n = 5
print(top_n_finishers(head, 5)) # Expected Output: ["Daisy", "Mario", "Toad", "Yoshi"]
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
- Time Complexity: O(N) where N is the smaller of n or the length of the linked list.
- Space Complexity: O(N) for storing the output list of node values.