Skip to content

Commit

Permalink
completes assignment 1
Browse files Browse the repository at this point in the history
  • Loading branch information
Rohafzal committed Nov 16, 2024
1 parent a19d1cd commit d28e1e8
Showing 1 changed file with 160 additions and 28 deletions.
188 changes: 160 additions & 28 deletions 02_activities/assignments/assignment_1.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,19 @@
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 5,
"metadata": {},
"outputs": [],
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n"
]
}
],
"source": [
"print((hash('your first name') % 3) + 1)"
"print((hash('Roha') % 3) + 1)"
]
},
{
Expand Down Expand Up @@ -193,28 +201,34 @@
]
},
{
"cell_type": "code",
"execution_count": null,
"cell_type": "markdown",
"metadata": {},
"outputs": [],
"source": [
"# Your answer here"
"# Answer\n",
"\n",
"The problem is to determine if a binary tree contains duplicate values. Starting from the root, we need to traverse the tree and check for duplicate values. If duplicates exist, return the value of the duplicate closest to the root (i.e., the first duplicate encountered during a level-order traversal). If there are no duplicates in the tree, return -1."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"- In this .ipynb file, there are examples that illustrate how the code should work (the examples provided above). Create 2 new examples for the question you have been assigned, that demonstrate you understand the problem. For question 1 and 2, you don't need to create the tree demonstration, just the input and output.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"cell_type": "markdown",
"metadata": {},
"outputs": [],
"source": [
"# Your answer here"
"# Answer\n",
"\n",
"Example 1: \n",
"input : [1, 7, 8, 9, 9, 12, 7, 12]\n",
"output: 9\n",
"\n",
"Example 2: [2, 4, 6, 9, 0, 2]\n",
"output: -1"
]
},
{
Expand All @@ -227,11 +241,77 @@
},
{
"cell_type": "code",
"execution_count": null,
"execution_count": 18,
"metadata": {},
"outputs": [],
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"First Duplicate: 10\n"
]
}
],
"source": [
"# Your answer here"
"# Definition for a binary tree node.\n",
"class TreeNode(object):\n",
" def __init__(self, val=0, left=None, right=None):\n",
" self.val = val\n",
" self.left = left\n",
" self.right = right\n",
"\n",
"def is_duplicate(root: TreeNode) -> int:\n",
" \"\"\"\n",
" Finds the first duplicate value in a binary tree using BFS.\n",
" :param root: Root node of the binary tree\n",
" :return: The first duplicate value or -1 if no duplicates exist\n",
" \"\"\"\n",
" if not root:\n",
" return -1 # No duplicates in an empty tree\n",
"\n",
" from collections import deque\n",
"\n",
" # BFS queue and set to track seen values\n",
" queue = deque([root])\n",
" seen = set()\n",
"\n",
" while queue:\n",
" node = queue.popleft()\n",
"\n",
" # Check for duplicates\n",
" if node.val in seen:\n",
" return node.val\n",
" seen.add(node.val)\n",
"\n",
" # Add left and right children to the queue\n",
" if node.left:\n",
" queue.append(node.left)\n",
" if node.right:\n",
" queue.append(node.right)\n",
"\n",
" return -1 # No duplicates found\n",
"\n",
"# Manually construct a binary tree (no helper function)\n",
"# Example Tree: [1, 10, 2, 3, 10, 12, 12]\n",
"root = TreeNode(1)\n",
"node1 = TreeNode(10)\n",
"node2 = TreeNode(2)\n",
"node3 = TreeNode(3)\n",
"node4 = TreeNode(10) # Duplicate\n",
"node5 = TreeNode(12)\n",
"node6 = TreeNode(12) # Duplicate\n",
"\n",
"# Connect the nodes\n",
"root.left = node1\n",
"root.right = node2\n",
"node1.left = node3\n",
"node1.right = node4\n",
"node2.left = node5\n",
"node2.right = node6\n",
"\n",
"# Test the is_duplicate function\n",
"result = is_duplicate(root)\n",
"print(\"First Duplicate:\", result)\n"
]
},
{
Expand All @@ -243,12 +323,14 @@
]
},
{
"cell_type": "code",
"execution_count": null,
"cell_type": "markdown",
"metadata": {},
"outputs": [],
"source": [
"# Your answer here"
"# Answer\n",
"\n",
"This solution efficiently detects the first duplicate in a binary tree using Breadth-First Search (BFS) and a set for tracking seen values. BFS traverses the tree level by level, ensuring that the first duplicate closest to the root is found. Each node is processed once, and its value is checked against the seen set in O(1) time. If a duplicate is detected, it is returned immediately; otherwise, its children are added to the queue for further processing.\n",
"\n",
"The algorithm handles edge cases, such as empty trees or trees without duplicates, by returning -1"
]
},
{
Expand All @@ -260,12 +342,28 @@
]
},
{
"cell_type": "code",
"execution_count": null,
"cell_type": "markdown",
"metadata": {},
"outputs": [],
"source": [
"# Your answer here"
"# Answer\n",
"\n",
"Time Complexity:\n",
"Tree Traversal: Each node is visited exactly once during the BFS traversal. For n nodes, the traversal takes O(n).\n",
"\n",
"Set Operations: Checking membership and adding elements to the seen set are O(1) on average.\n",
"\n",
"Queue Operations: Enqueuing and dequeuing nodes are O(1) operations.\n",
"\n",
"Overall Time Complexity: O(n)\n",
"\n",
"Space Complexity:\n",
"Tree Storage: The tree itself is stored in memory, requiring O(n) space for nn nodes.\n",
"\n",
"BFS Queue: At most, the queue holds all nodes of the largest level (width of the tree). For a balanced binary tree, the maximum width is O(n/2), so the queue size is O(n) in the worst case.\n",
"\n",
"Seen Set: The set stores at most nn unique values, requiring O(n) space in the worst case.\n",
"\n",
"Overall Space Complexity: O(n)"
]
},
{
Expand All @@ -277,12 +375,46 @@
]
},
{
"cell_type": "code",
"execution_count": null,
"cell_type": "markdown",
"metadata": {},
"outputs": [],
"source": [
"# Your answer here"
"# Answer\n",
"\n",
"In this solution, we use Breadth-First Search (BFS) to find the first duplicate value in a binary tree, and we introduce a helper function to dynamically construct the binary tree from a level-order input array. This helper function makes it easier to test the algorithm with various inputs.\n",
"Steps to Implement\n",
"\n",
"1. Helper Function: Tree Construction The helper function takes a level-order input list (e.g., [1, 10, 2, 3, 10, 12, 12]) and builds the binary tree dynamically.\n",
"It uses a queue to track parent nodes and assigns left and right children in a level-order manner.\n",
"For each element in the input: If the value is not None, create a new TreeNode and assign it as the left or right child of the current parent node.\n",
"Enqueue the newly created child node for further processing.\n",
"\n",
"2. BFS for Duplicate Detection\n",
"\n",
"Once the tree is constructed, we use BFS to find the first duplicate value in the binary tree:\n",
"Initialize a queue with the root node.\n",
"Use a set to track the values of nodes already visited.\n",
"For each node:\n",
"Check if its value exists in the set: If yes, return the value (this is the first duplicate found). Otherwise, add the value to the set.\n",
"Add its left and right children (if they exist) to the queue for further processing.\n",
"If the entire tree is traversed and no duplicate is found, return -1.\n",
"\n",
"Why Use This Alternative?\n",
"Dynamic Tree Construction:\n",
"The helper function allows the binary tree to be built dynamically from level-order input, making the solution flexible and testable for various inputs.\n",
"\n",
"Efficiency:\n",
"BFS ensures the first duplicate closest to the root is found in O(n) time.\n",
"The set-based duplicate check is efficient with O(1) average-time complexity.\n",
"It has a space complexity of O(n)\n",
"\n",
"Scalability: This approach works for any binary tree size and structure, as the helper function can handle dynamic input.\n",
"\n",
"Summary of Steps for a Classmate\n",
"\n",
"Write a helper function to dynamically build a binary tree from a level-order input array.\n",
"Use BFS to traverse the tree level by level.\n",
"Track visited node values in a set.\n",
"Return the first duplicate value encountered or -1 if no duplicate exists.\n"
]
},
{
Expand Down Expand Up @@ -330,7 +462,7 @@
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"display_name": "dsi_participant",
"language": "python",
"name": "python3"
},
Expand All @@ -344,7 +476,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.7"
"version": "3.9.15"
}
},
"nbformat": 4,
Expand Down

0 comments on commit d28e1e8

Please sign in to comment.