TIP102 Unit 6 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.
HAPPY CASE
Input: game1 = Node(2, Node(1))
Output: "Even"
Explanation: The pair (2, 1) results in a point for the Even team.
HAPPY CASE
Input: game2 = Node(2, Node(5, Node(4, Node(7, Node(20, Node(5))))))
Output: "Odd"
Explanation: The three pairs are (2, 5), (4, 7), (20, 5). The Odd team wins with 2 points.
EDGE CASE
Input: game3 = Node(4, Node(5, Node(2, Node(1))))
Output: "Tie"
Explanation: The two pairs are (4, 5) and (2, 1). Each team gets 1 point.
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 involving Pair Comparison, we want to consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
General Idea: We will traverse the linked list, comparing the values of each pair of nodes. We will keep track of the points for each team and determine the winner based on the accumulated points.
1) Initialize two counters: `odd_points` and `even_points`.
2) Traverse the linked list in pairs:
a) Compare the value of the `even`-indexed node with the value of the next `odd`-indexed node.
b) Update the respective counter based on which `node` has a higher value.
3) After the loop ends, compare `odd_points` and `even_points`:
a) If `odd_points > even_points`, return `"Odd"`.
b) If `even_points > odd_points`, return `"Even"`.
c) If points are tied, return `"Tie"`.
⚠️ Common Mistakes
Implement the code to solve the algorithm.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
# Function to determine the game result
def game_result(head):
odd_points = 0
even_points = 0
current = head
while current and current.next:
even_value = current.value
odd_value = current.next.value
if even_value > odd_value:
even_points += 1
elif odd_value > even_value:
odd_points += 1
# Move to the next pair
current = current.next.next
if odd_points > even_points:
return "Odd"
elif even_points > odd_points:
return "Even"
else:
return "Tie"
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
game1
, game2
, and game3
linked lists to verify that the function correctly calculates the game result.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 each node is visited exactly once.O(1)
because the algorithm uses a constant amount of extra space for counters.