Overview
This lab covered two distinct topics. First, the Longest Common Prefix string problem: an initial hash-map/counting approach was considered and rejected in favour of an optimal approach that takes the first string as the initial prefix and shrinks it character-by-character against every other string. Second, an introduction to trees: the non-linear hierarchical data structure, its terminology (node, root, leaf, edge), the types of binary trees (binary, full, complete, perfect, skewed), and implementing a tree node in Python. Traversals (in-order, pre-order, post-order) and BFS/DFS were previewed and deferred to the next class.
Learning outcomes
- Solve the Longest Common Prefix problem by initializing the prefix to
strs[0]and shrinking it via column-wise character comparison against each remaining string. - Explain why splitting strings into characters beforehand is unnecessary, and handle case sensitivity by converting strings to lowercase.
- Describe the UTF-8/encoding concern for junk or machine-generated characters and how such data must be encoded/decoded.
- Define tree terminology: node, root, leaf node, edge, and parent-child relationships.
- Distinguish binary, full, complete, perfect and skewed binary trees, and apply the perfect-tree node formula.
- Write a Python
Nodeclass withdata,leftandrightattributes and construct a small tree by assignment.
Core concepts
Longest Common Prefix problem
Given an array of strings, the output is the longest prefix shared by all strings; if no string matches even a single letter, the expected output is the empty string. This is the LeetCode-style string problem that anchors the first half of the class. Example input used in class: flower, flow, flight — the common prefix is fl.
Initial hash-map / counting approach (rejected)
A hash-map / counting approach was considered and rejected as the solution strategy. The instructor flagged that they will touch on the hash-map approach again later (see Follow-ups).
Optimal approach: prefix shrinking
Take strs[0] (string zero, e.g. flower) as the initial prefix. Compare it character-by-character (column-wise) against every other string; on a mismatch, break and replace the prefix with prefix[0:i] (the part that matched so far). Because the prefix only gets shorter as more strings are processed, this is efficient. This is the core algorithm of the class and the basis of the dry run below.
Column-wise comparison vs. splitting
Comparing characters position by position across strings is sufficient; splitting strings into characters first is not necessary. The column-wise comparison works even for long strings/sentences (the constraint allows lengths up to 200, which covers sentences), and strings can be passed directly for processing.
Case sensitivity
F and f are not equal, so a comparison can fail purely due to case. Converting all strings to lowercase (e.g. s.lower() for s in strs) before comparing avoids this. This connects directly to the prefix-shrinking algorithm, where a case mismatch would incorrectly shrink the prefix.
Junk / machine-readable characters and encoding
Characters that are not human-readable (broken Unicode, byte-order issues) can appear when data comes from text files, PDFs, data correction, or machine-generated information. Such data must be encoded/decoded (e.g. into UTF-8) to be handled. This was raised by a student in the context of NLP/streaming and connects to the problem's constraint of English letters only.
Trees: non-linear hierarchical structure
A tree is a non-linear data structure used to organize data hierarchically; unlike an array where elements are arranged in a sequence, a tree organizes elements into parent-child relationships (e.g. 1 is a parent of 2, 2 is a parent of 4). A middle-layer node can be both a parent and a child. This begins the data-structure half of the class.
Tree terminology
- Node: a single element in the tree (e.g. 1, 2, 3).
- Root: the topmost node of the tree.
- Leaf node: a node with no children (the last nodes of the tree).
- Edge: mentioned as a tree concept (definition not elaborated). A tree with
nnodes hasn − 1edges: a tree is connected and acyclic, so every node except the root has exactly one incoming edge. - Height: the number of edges on the longest path from the root to a leaf. If height is counted in nodes instead of edges, the same tree has height
h + 1— always check the convention.
Types of binary trees
- Binary tree: each node can have at most two children, called the left child and right child. A node may have no children, only a left child, only a right child, or both — binary does not mean every node must have exactly two children. Example: node 20 with only a left child is a perfectly valid binary tree.
- Full binary tree: every node has either zero or two children; no node has exactly one child.
- Complete binary tree: every level is completely filled except the last level; nodes on the last level must be filled from left to right with no gaps. Important for binary heaps, commonly used to implement priority queues. A node's right child present while its left is absent (gap on the left) is invalid.
- Perfect binary tree: (1) every internal node has exactly two children, and (2) all leaf nodes are at the same depth.
- Skewed binary tree: each node has only one child; subdivided into left-skewed and right-skewed. It can behave like a linked list.
- Balanced binary tree: mentioned as coming from a different concept (binary search tree), where the height of the left minus the height of the right should be less than one; not counted among the four types covered here.
Array representation of a complete binary tree
A complete binary tree can be stored in an array. In a zero-indexed array, the left child of the node at index i is at 2i + 1, the right child at 2i + 2, and the parent at ⌊(i − 1)/2⌋. With a one-indexed array the classical formulas are left = 2i and right = 2i + 1; mixing the two indexing conventions is the classic off-by-one error.
Binary search tree and traversals
In a binary search tree, the inorder traversal (Left, Root, Right) visits the nodes in sorted order. Preorder is Root–Left–Right, postorder is Left–Right–Root, and level order is BFS by depth. For the same tree, preorder, inorder and postorder give three different sequences.
Python node class
class Node with a constructor (def __init__) taking self and data; self.data = data; left and right children initialized to None. The class is a blueprint for creating a tree node; __init__ runs whenever a new node is created. This is the implementation bridge from tree theory to code.
Traversals preview
Pre-order traversal was explained with the "three sticks" analogy — put sticks at each node (left, middle/position, right); for pre-order, go with the left stick and traverse till the end. On the example tree this yields 10, 20, 4, then 5, then 30, 6, 7 (as described). BFS/DFS are mostly used in graphs, for root-searching or path-finding problems; level order traversal is BFS-related. All of this is deferred to the next class.
Formulas and maths
- Loop condition for the character comparison:
i < len(prefix)andi < len(s)— both conditions must hold; if either fails, the loop stops. Used to bound the comparison so neither string is indexed out of range. - Mismatch check: if
prefix[i] != s[i], thenbreak. Used to stop comparing as soon as the prefix no longer matches. - Prefix update after each string:
prefix = prefix[0:i](i.e. characters up to indexi). Used to shrink the prefix to the part that matched so far. len("flower") = 6,len("flow") = 4— lengths used in the dry run to determine where the loop condition fails.- Constraint mentioned: string length can be up to 200 — used to argue column-wise comparison covers sentences without splitting.
- Total number of nodes in a perfect binary tree:
n = 2^{h+1} - 1, wherehis the height. Used to count nodes in a perfect binary tree. - Edges in a tree with
nnodes:n − 1. Used to relate node count to edge count. - Height in edges vs. height in nodes: a tree of height
h(edges) has heighth + 1when counted in nodes. Used to check the convention before applying height formulas. - Minimum height of a binary tree with
nnodes:⌈log₂(n + 1)⌉ − 1(in edges). Used to find the smallest possible height for a given node count. - Zero-indexed array layout of a complete binary tree: left child of index
iat2i + 1, right child at2i + 2, parent at⌊(i − 1)/2⌋. One-indexed: left =2i, right =2i + 1. Used to navigate a tree stored in an array. - Skewed tree height:
n - 1(number of nodes minus one); time to reach the last node:O(n). Used to show a skewed tree degenerates to linked-list behaviour. - Balanced binary tree condition (as stated): height of left minus height of right should be less than one. Used to define balance in a binary search tree context.
Worked examples
Dry run with prefix = "flower", s = "flow":
- i = 0: prefix[0] = f, s[0] = f → match
- i = 1: l vs l → match
- i = 2: o vs o → match
- i = 3: w vs w → match
- i = 4: check 4 < 6 (true) and 4 < 4 (false) → loop condition fails, loop stops
- Update: prefix = prefix[0:4] = flow
Next iteration with prefix = "flow", s = "flight":
- i = 0: f vs f → match
- i = 1: l vs l → match
- i = 2: o vs i → mismatch → break
- Update: prefix = prefix[0:2] = fl
- Final answer returned: fl
Case-sensitivity example: comparing flight with a string starting with capital F fails at the first character because capital F ≠ lowercase f; fix by converting all strings to lowercase first.
Perfect binary tree: depths 0, 1, 2 → height = 2. Applying the formula: 2^(2+1) − 1 = 2^3 − 1 = 7 total nodes.
Minimum height for 12 nodes: a perfect tree of height 3 holds 2^4 − 1 = 15 ≥ 12 nodes, while height 2 holds only 2^3 − 1 = 7 < 12, so the minimum height is 3 edges. Check with the formula: ⌈log₂(12 + 1)⌉ − 1 = ⌈3.70⌉ − 1 = 4 − 1 = 3.
Binary tree example: root 10 with children 20 and 30; node 20 has only a left child — still a valid binary tree.
Traversal example: root A with left child B and right child C, and B with children D and E. Preorder gives A, B, D, E, C — root, then the whole left subtree (B, D, E), then the right subtree (C). The same tree gives inorder B, D, A, E, C and postorder D, E, B, C, A.
BST insertion example: inserting 50, 30, 70, 20, 40, 60, 80 into an empty BST gives root 50 with left subtree 30 (children 20, 40) and right subtree 70 (children 60, 80). Postorder (Left–Right–Root) is 20, 40, 30, 60, 80, 70, 50; inorder is the sorted order 20, 30, 40, 50, 60, 70, 80.
Python construction walkthrough:
- root = Node(20) → constructor runs, self.data = 20, left and right are None.
- root.left = Node(10), root.right = Node(30) → 20 now has left child 10 and right child 30.
- root.left.left = Node(40), root.right.right = Node(50) → extends the tree further.
- Printing root.data, root.left, root.right shows the single node's contents initially.
Complete binary tree discussion: with nodes D, E, F filled left to right there is no gap; leaving a gap on the left (e.g. filling C's right while leaving something on the left unfilled) makes it invalid. A tree with nodes 5 and 6 at the same level but not satisfying the other conditions is not perfect; the instructor called such a case "partial" / "invalid as complete."
Test case 4 of the coding problem was reported failing for one student but passing for Satya.
Questions asked in class
Q (Anuja): Why not split the strings into characters beforehand instead of comparing column-wise? A: Splitting is not necessary. The column-wise character comparison works even for long strings/sentences (the constraint allows lengths up to 200, which covers sentences). Splitting is not required for processing — you can pass the strings directly.
Q: What about capital vs lowercase letters?
A: Capital F and lowercase f are not the same, so the comparison fails. You can convert the strings to lowercase (e.g. s.lower() for s in strs) before comparing.
Q: What about junk values / special characters in a sentence? A: Human-readable characters are fine; the concern is machine-language kind of characters. When data comes from a text file or PDF and is put into streaming, you may encounter such characters — you can check for them during processing or handle them beforehand. In data correction or machine-generated information, there can be broken Unicode (byte-order issues); such data must be encoded/decoded into UTF-8 characters. These are not normal characters. (The instructor noted they could share an example of such symbolic characters later.)
Q (Anuja, via instructor's paraphrase): The problem statement has a constraint that only English characters are used and a length is assigned, so the UTF-8 concern is valid. A: Yes, the point is valid; we have to work within that constraint. The instructor had already mentioned "English letters only" in the constraints and apologized if something was missed. He noted he doesn't have the constraint text at hand; one could convert to UTF-8 or decode to Latin characters if needed.
Q: Test case 4 is failing. A: It passes for Satya, so the instructor said he might have a mistake and would check on his end.
Q (on the node code): When you do root.left = Node(10), what gets assigned to left — is 10 assigned to left?
A: Node(10) creates an instance of the node class; the constructor passes 10 to self.data, and that object is assigned to the left attribute. Initially left/right are None; assigning Node(10) replaces None with the node object whose data is 10 and whose own left/right are None. The instructor walked through this step by step (with some back-and-forth) until the student said "got it."
Q (Vikas): Complete binary tree and full binary tree look the same, because in a complete binary tree any section also has 0 or 2 children? A: No — the complete tree example is only "partially complete"; the rule is that the last level must be filled left to right with no gaps. If you traverse left to right there should be no gap (e.g. D, E, F with no gap). If you leave a gap on the left and fill to the right, it is not complete.
Q: In full binary there are 0 or 2 nodes, and in perfect binary there are exactly 2 nodes and leaf nodes at the same depth; if I have 5 and 6 at the same level, why is it not perfect? A: Because the other conditions (every internal node exactly two children, all leaves at the same depth) must hold together; the instructor confirmed the student's understanding ("then I understood").
Q: Is a given tree partial/incomplete? A: It is invalid as a complete binary tree; "partial" is not a standard term here — the instructor said "partial you can say" but it is invalid as complete.
Q (from the morning class discussion): Are in-order/pre-order/post-order the BFS and depth-first algorithms you are going to cover? A: These concepts are mostly used in graphs; DFS and BFS are used for root-searching or path-finding problems. Traversals (in-order, pre-order, post-order, level order) and BFS/DFS will be introduced in the next class.
Q: Resource question. A: The instructor said he would search and send them, noted that in class you don't have to be diplomatic — just ask — and that educational resources are open/permissible. He mentioned following resources on Udemy and that CampusX is also good, though it focuses more on CNN-type topics.
Key takeaways
- Longest common prefix: initialize
prefix = strs[0], compare column-wise against each string, and on mismatch setprefix = prefix[0:i]; return the empty string if nothing matches. - The loop condition requires both
i < len(prefix)andi < len(s); if either fails, the loop stops. - The prefix only shrinks as strings are processed — it never grows.
- Dry run on
flower,flow,flight: afterflowthe prefix isflow; afterflightit isfl; final answerfl. - Splitting strings into characters is unnecessary; column-wise comparison handles strings up to length 200 (sentences included).
- Case matters:
F≠f; convert withs.lower()before comparing. - Broken Unicode / byte-order junk from files, PDFs or machine-generated data must be encoded/decoded (e.g. UTF-8).
- A tree with
nnodes hasn − 1edges; height is the number of edges on the longest root-to-leaf path (in nodes it ish + 1). - Minimum height of a binary tree with
nnodes is⌈log₂(n + 1)⌉ − 1; for 12 nodes that is 3. - A binary tree node has at most two children (left and right); a node with only a left child is still valid.
- Full = every node has 0 or 2 children; complete = all levels filled except the last, filled left to right with no gaps; perfect = every internal node has exactly 2 children and all leaves at the same depth.
- Perfect binary tree node count:
n = 2^{h+1} - 1; for height 2, n = 7. - In a zero-indexed array, the left child of index
iis2i + 1, the right is2i + 2, the parent is⌊(i − 1)/2⌋; one-indexed uses2iand2i + 1. - Preorder = Root–Left–Right, inorder = Left–Root–Right, postorder = Left–Right–Root, level order = BFS by depth; inorder of a BST gives sorted order.
- A skewed tree has height
n − 1and behaves like a linked list, withO(n)time to reach the last node. - In Python,
Node(10)creates an object whosedatais 10 and whose left/right areNone; assigning it toroot.leftreplacesNonewith that object.
Exam-style questions
1. Trace the optimal Longest Common Prefix algorithm on ["flower", "flow", "flight"], showing the prefix after each string.
Outline: prefix = flower; compare with flow — matches at i = 0..3, loop stops at i = 4 because 4 < 4 is false; prefix = prefix[0:4] = flow. Compare with flight — matches f, l, mismatches at i = 2 (o vs i), break; prefix = prefix[0:2] = fl. Return fl.
2. Why is splitting the strings into characters unnecessary, and what constraint makes column-wise comparison sufficient?
Outline: column-wise comparison indexes both strings at position i directly; the constraint allows string length up to 200, which covers sentences; strings can be passed directly for processing.
3. Distinguish full, complete and perfect binary trees, with one invalid example for each rule. Outline: full — every node has 0 or 2 children (a node with exactly one child violates it); complete — all levels filled except the last, filled left to right with no gaps (a right child present while the left is absent violates it); perfect — every internal node has exactly two children and all leaves at the same depth (nodes 5 and 6 at the same level without the other conditions is not perfect).
4. A perfect binary tree has height 2. How many nodes does it have? Show the formula.
Outline: n = 2^{h+1} − 1 with h = 2 → 2^3 − 1 = 7 nodes.
5. Write a Python Node class for a binary tree and construct a root 20 with left child 10 and right child 30. Explain what root.left = Node(10) assigns.
Outline: class Node with def __init__(self, data): self.data = data, self.left = None, self.right = None. Then root = Node(20), root.left = Node(10), root.right = Node(30). Node(10) creates an instance whose data is 10 and whose left/right are None; that object is assigned to root.left.
6. A tree has n nodes. How many edges does it have, and why?
Outline: n − 1 edges. A tree is connected and acyclic, so every node except the root has exactly one incoming edge.
7. What is the minimum possible height (in edges) of a binary tree with 12 nodes?
Outline: 3. A perfect tree of height 3 holds 2^4 − 1 = 15 ≥ 12 nodes, while height 2 holds only 2^3 − 1 = 7 < 12; the formula gives ⌈log₂(12 + 1)⌉ − 1 = 3.
8. Give the preorder, inorder and postorder traversals of the tree: A root, B left child of A, C right child of A, D and E children of B. Outline: preorder A, B, D, E, C (root, then whole left subtree, then right subtree); inorder B, D, A, E, C; postorder D, E, B, C, A.
9. In a complete binary tree stored in a zero-indexed array, where are the children and parent of the node at index i?
Outline: left child at 2i + 1, right child at 2i + 2, parent at ⌊(i − 1)/2⌋. With one-indexed arrays the classical formulas are left = 2i and right = 2i + 1; mixing conventions is the classic off-by-one error.
10. Insert 50, 30, 70, 20, 40, 60, 80 into an empty BST. Give the postorder traversal and the inorder traversal. Outline: postorder 20, 40, 30, 60, 80, 70, 50; inorder (Left, Root, Right) gives the sorted order 20, 30, 40, 50, 60, 70, 80.