Tom and Jerry - codepath/compsci_guides GitHub Wiki
Unit 5 Session 1 (Click for link to problem statements)
TIP102 Unit 5 Session 1 Standard (Click for link to problem statements)
Problem Highlights
- 💡 Difficulty: Easy
- ⏰ Time to complete: 5-10 mins
- 🛠️ Topics: Linked Lists, Pointers, Node Class
1: U-nderstand
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?
- What is the task?
- Create a simple linked list where a node representing "Tom" points to a node representing "Jerry".
HAPPY CASE
Input: Node("Tom") -> Node("Jerry")
Output:
Tom
<__main__.Node object at 0x...>
Jerry
Jerry
None
Explanation: The "Tom" node points to the "Jerry" node, and "Jerry" is the last node in the list, so its `next` is `None`.
EDGE CASE
Input: Node("Tom") -> None
Output:
Tom
None
Explanation: If "Tom" has no next node, its `next` should be `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:
- Use a
Node
class to represent each element in the list. - Link nodes by setting the
next
attribute to point to the next node in the sequence.
3: P-lan
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Create two nodes, one for "Tom" and one for "Jerry", and link them by setting the next
attribute of "Tom" to point to "Jerry".
1) Create a node `cat` with the value "Tom".
2) Create another node `mouse` with the value "Jerry".
3) Set `cat.next` to point to `mouse`.
4) Test the linked list by printing the values and references.
⚠️ Common Mistakes
- Forgetting to link the nodes properly by setting the
next
attribute. - Not handling the case where the linked list ends with
None
.
4: I-mplement
Implement the code to solve the algorithm.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
# Create the linked list nodes
cat = Node("Tom")
mouse = Node("Jerry")
# Link the nodes
cat.next = mouse
5: R-eview
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Trace through your code with the following input:
- cat = Node("Tom")
- mouse = Node("Jerry")
- Verify that cat.next correctly points to mouse and mouse.next is None.
6: E-valuate
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
- Time Complexity: O(1) for creating and linking nodes since each operation is constant time.
- Space Complexity: O(1) as we are only creating and storing two nodes.