Unit 5 Session 2 (Click for link to problem statements)
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?
None
?
0
.1
.HAPPY CASE
Input: node = Node("Rainbow Road") in a list where the full sequence is "Yoshi Falls <-> Moo Moo Farm <-> Rainbow Road <-> DK Mountain"
Output: 4
Explanation: The function calculates the length of the entire doubly linked list.
EDGE CASE
Input: node = None
Output: 0
Explanation: When the node is `None`, the function returns `0`.
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 length problems, we want to consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Traverse the list from the given node to find the head, then traverse the entire list from head to tail to count the number of nodes.
1) If the node is `None`, return `0`.
2) Initialize a pointer `start` to the given node.
3) Traverse backwards using the `prev` pointers to find the head of the list.
4) Initialize a counter `length` to `0`.
5) Traverse the list from the head using the `next` pointers, incrementing `length` for each node.
6) Return the value of `length`.
⚠️ Common Mistakes
None
.Implement the code to solve the algorithm.
def get_length(node):
if node is None:
return 0
# Find the start of the list
start = node
while start.prev:
start = start.prev
# Traverse from start to end, counting nodes
length = 0
current = start
while current:
length += 1
current = current.next
return length
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Example:
yoshi_falls = Node("Yoshi Falls")
moo_moo_farm = Node("Moo Moo Farm")
rainbow_road = Node("Rainbow Road")
dk_mountain = Node("DK Mountain")
yoshi_falls.next = moo_moo_farm
moo_moo_farm.next = rainbow_road
rainbow_road.next = dk_mountain
dk_mountain.prev = rainbow_road
rainbow_road.prev = moo_moo_farm
moo_moo_farm.prev = yoshi_falls
# List: Yoshi Falls <-> Moo Moo Farm <-> Rainbow Road <-> DK Mountain
print(get_length(rainbow_road)) # Expected Output: 4
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 list, as we need to traverse the entire list.
- Space Complexity: O(1) because we are only using a constant amount of extra space for the pointers.