TIP102 Unit 5 Session 1 Advanced (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?
0.00
.HAPPY CASE
Input: A linked list with nodes "Carp" -> "Dace" -> "Cherry Salmon", fish_name = "Dace"
Output: 0.33
Explanation: The probability of catching "Dace" is 1/3, which is 0.33 when rounded down to the nearest hundredth.
EDGE CASE
Input: An empty linked list, fish_name = "Dace"
Output: 0.00
Explanation: There are no fish to catch, so the probability is 0.00.
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, count the occurrences of the given fish name, and calculate the probability by dividing the count by the total number of nodes.
1) Initialize a variable `total_count` to 0.
2) Initialize a variable `fish_count` to 0.
3) Set the current node to the head of the list.
4) While the current node is not None:
a) Increment `total_count`.
b) If the current node's fish name matches the given fish name, increment `fish_count`.
c) Move to the next node.
5) If `total_count` is 0, return 0.00.
6) Calculate the probability by dividing `fish_count` by `total_count`.
7) Round the probability to the nearest hundredth and return it.
⚠️ Common Mistakes
Implement the code to solve the algorithm.
class Node:
def __init__(self, fish_name, next=None):
self.fish_name = fish_name
self.next = next
# For testing
def print_linked_list(head):
current = head
while current:
print(current.fish_name, end=" -> " if current.next else "\n")
current = current.next
def fish_chances(head, fish_name):
current = head
total_count = 0
fish_count = 0
while current:
total_count += 1
if current.fish_name == fish_name:
fish_count += 1
current = current.next
if total_count == 0:
return 0.00
probability = fish_count / total_count
return round(probability, 2)
# Example Usage:
fish_list = Node("Carp", Node("Dace", Node("Cherry Salmon")))
print(fish_chances(fish_list, "Dace")) # Output: 0.33
print(fish_chances(fish_list, "Rainbow Trout")) # Output: 0.00
empty_list = None
print(fish_chances(empty_list, "Dace")) # Output: 0.00
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.