6.006 Problem Session
📝 Problem Session 2: Algorithms & Data Structures
This session covers fundamental algorithm analysis techniques and introduces efficient data structures for common problems. We'll explore recurrence relations, master theorem, and specialized data structures like linked lists augmented with pointers.
🌳 Solving Recurrences with Master Theorem & Recursion Trees
Solving recurrence relations is a core skill in algorithm analysis, helping to determine the time complexity of recursive algorithms. The Master Theorem provides a straightforward way to solve many common recurrences.
🔨 Master Theorem: The Sledgehammer Approach
The Master Theorem applies to recurrences of the form T(n)=aT(n/b)+f(n), where:
a≥1: The number of subproblems.
b>1: The factor by which the input size is reduced in each subproblem.
f(n): The cost of the work done outside the recursive calls (e.g., merging results).
The theorem has three cases, comparing f(n) with nlogba:
Case 1: Work at leaves dominates
If f(n)=O(nlogba−ϵ) for some constant ϵ>0.
Then T(n)=Θ(nlogba).
Intuition: The cost of traversing the recursion tree (the "split" and "combine" steps) is greater than the work done at each node.
Case 2: Work is balanced across levels
If f(n)=Θ(nlogbalogkn) for some constant k≥0.
Then T(n)=Θ(nlogbalogk+1n).
Intuition: The work at each level of the recursion tree is roughly the same.
Case 3: Work at root dominates
If f(n)=Ω(nlogba+ϵ) for some constant ϵ>0.
AND af(n/b)≤cf(n) for some constant c<1 (the "regularity condition").
Then T(n)=Θ(f(n)).
Intuition: The work done at the root of the recursion tree (or the top levels) is significantly more than the work done in the subproblems.
💡 Example 1A: Applying Master Theorem and Recursion Tree
Let's analyze the recurrence T(n)=2T(n/2)+O(n).
🎯 Master Theorem Application
Identify parameters:
a=2
b=2
f(n)=O(n)=O(n1/2)
Calculate nlogba:
nlog22=n1=n
Compare f(n) with nlogba:
We have f(n)=O(n1/2).
We need to compare n1/2 with n1.
Since n1/2=O(n1−1/2), we can set ϵ=1/2.
This matches Case 1 of the Master Theorem: f(n)=O(nlogba−ϵ).
Conclusion:
T(n)=Θ(nlogba)=Θ(n1)=Θ(n).
🌲 Recursion Tree Analysis
A recursion tree visually represents the work done at each level of a recursive algorithm.
Levels and Work:
Root (Level 0): Work done is O(n). It makes two calls to T(n/2).
Level 1: Each of the 2 nodes does O(n/2) work. Total work: 2×O(n/2)=O(2n).
Level l: There are 2l nodes. Each node processes input of size n/2l, doing O(n/2l) work.
Total work at level l: 2l×O(n/2l)=O(2l2ln)=O(2l/2n).
Tree Depth:
The problem size reduces by a factor of 2 at each level.
The recursion stops when the input size is 1.
Depth of the tree: log2n levels (from l=0 to l=log2n−1).
Total Work Calculation:
Sum the work at each level: $$T(n) = \sum_{l=0}^{\log_2 n - 1} O(2^{l/2} \sqrt{n})$$
Factor out n:
T(n)=O(n∑l=0log2n−1(2)l)This is a geometric series with ratio 2. The sum is approximately (2)log2n=(21/2)log2n=(2log2n)1/2=n1/2=n.
So, T(n)=O(n⋅n)=O(n).
This matches the result from the Master Theorem, confirming T(n)=Θ(n).
💡 Example 1B: Master Theorem with Different Branching Factors
Consider the recurrence T(n)=8T(n/4)+O(nn).
🎯 Master Theorem Application
Identify parameters:
a=8
b=4
f(n)=O(nn)=O(n3/2)
Calculate nlogba:
nlog48. Since 4x=8⟹(22)x=23⟹2x=3⟹x=3/2.
So, nlog48=n3/2.
Compare f(n) with nlogba:
We have f(n)=O(n3/2).
We also calculated nlogba=n3/2.
Since f(n) is big O of nlogba, and not necessarily Θ, this falls under Case 2 with k=0 (meaning log0n=1).
Important: Because f(n) is O(n3/2) and not Θ(n3/2), the resulting T(n) will also be O instead of Θ.
Conclusion:
T(n)=O(nlogbalogk+1n)=O(n3/2log0+1n)=O(n3/2logn).
🌲 Recursion Tree Analysis
Levels and Work:
Root (Level 0): Work O(n3/2). It makes 8 calls to T(n/4).
Level l: There are 8l nodes. Each node processes input of size n/4l, doing O((n/4l)3/2) work.
Total work at level l: 8l×O((n/4l)3/2)=O(8l⋅n3/2⋅(1/4l)3/2)
=O(8l⋅n3/2⋅(1/43/2)l)=O(8l⋅n3/2⋅(1/8)l)=O(n3/2).
Observation: The work done at each level is constant, O(n3/2). This is characteristic of Master Theorem Case 2.
Tree Depth:
The problem size reduces by a factor of 4 at each level.
Depth of the tree: log4n levels.
Total Work Calculation:
Sum the work at each level: $$T(n) = \sum_{l=0}^{\log_4 n - 1} O(n^{3/2})$$
Since the work at each level is O(n3/2) and there are log4n levels:
T(n)=O(n3/2⋅log4n)Since the base of the logarithm only affects the constant factor, we write:
T(n)=O(n3/2logn)
This matches the result from the Master Theorem, confirming T(n)=O(n3/2logn).
🔍 Searching in Unbounded Spaces: Infinity Stones Problem
This problem describes finding a "stone" on a planet with an unknown, potentially infinite, index k. We can only query an oracle on a planet to determine if the target planet's index is greater or smaller than the current planet's index. The goal is to find the planet in O(logk) time.
🛑 The Challenge of Unboundedness
Standard binary search requires a known upper bound. With an infinite number of planets, we don't have this upper bound.
🚀 Two-Phase Approach: Exponential Search & Binary Search
The solution involves two phases:
Phase 1: Finding an Upper Bound (Exponential Search)
Start at planet index 1.
Repeatedly double the search range by visiting planets at indices 20,21,22,…,2m.
At each planet 2m, query the oracle: Is the target planet k on a planet with an index smaller than 2m?
Stop when we find a planet 2m such that k≤2m.
At this point, we know that 2m−1<k≤2m. We have successfully bounded the search space.
Time Complexity: This phase involves visiting m+1 planets. Since 2m−1<k≤2m, we know that m≈log2k. Therefore, this phase takes O(logk) time.
Phase 2: Binary Search
Now that we have a lower bound (2m−1) and an upper bound (2m) for k, we can perform a standard binary search within this finite range.
Time Complexity: A binary search on a range of size 2m−2m−1=2m−1 also takes O(log(2m−1))=O(m−1)=O(logk) time.
The total time complexity is O(logk)+O(logk)=O(logk), as required.
🖼️ Image Editing Software: Data Structures for Layers
This problem requires designing a data structure for an image editing application that manages layers of images. The operations and their required time complexities are:
Make Empty Document: O(1)
Import Image (add on top): O(N)
Display (all IDs in order): O(N)
Move Below (move image X below image Y): O(logN)
🤔 Initial Thoughts & Challenges
A simple linked list can handle
Import(add to head) andDisplayin O(1) and O(N) respectively, butMove Belowwould require O(N) to find X and Y.A sorted array (or balanced binary search tree) could find X and Y in O(logN) but
Importwould be O(N) (or O(logN) for a BST), andMove Below(reordering) would be O(N) because it involves shifting elements.
The key challenge is the Move Below operation's O(logN) requirement, which implies quick lookup of elements by their ID and efficient reordering of the sequence.
💡 Hybrid Data Structure: Doubly Linked List + Sorted Array with Pointers
The solution combines the strengths of two data structures:
Doubly Linked List: Stores the images in their visual display order. Each node contains an image ID. This allows for O(1) insertion/deletion once the nodes are found.
Sorted Array (or Balanced BST): Stores the image IDs in sorted order. Crucially, each entry in this sorted array (or BST node) will also store a pointer to its corresponding node in the doubly linked list.
🛠️ Operation Implementation
Make Empty Document:
Initialize an empty doubly linked list and an empty sorted array (or BST).
Time Complexity: O(1).
Import Image (add X on top):
Create a new node for X in the doubly linked list and insert it at the head (top layer).
Insert X's ID into the sorted array (or BST). When inserting, store a pointer from the array/BST entry to the newly created linked list node.
Time Complexity:
Doubly linked list insertion: O(1).
Sorted array insertion: O(N) (due to shifting elements).
Balanced BST insertion: O(logN).
The problem states O(N) for
Import, so a sorted array is acceptable here.
Display:
Traverse the doubly linked list from head to tail, printing each image ID.
Time Complexity: O(N).
Move Below (move image X below image Y):
Step 1: Find X and Y:
Use the sorted array (or BST) to find the entries for ID X and ID Y.
Retrieve the pointers to their respective nodes (
node_X,node_Y) in the doubly linked list.Time Complexity: O(logN) (for sorted array via binary search, or BST lookup).
Step 2: Update Doubly Linked List:
Remove
node_Xfrom its current position in the doubly linked list. This involves updating thenextandprevpointers of its neighbors.Insert
node_Ximmediately afternode_Yin the doubly linked list. This also involves updatingnextandprevpointers.The pointers stored in the sorted array/BST remain valid because they point to specific nodes, not positions.
Time Complexity: O(1) (constant number of pointer manipulations).
Total Time Complexity: O(logN)+O(1)=O(logN).
This hybrid structure efficiently meets all the specified time complexity requirements.
🐺 Brick Blowing: Damage Calculation
This problem describes a wolf blowing down houses with varying brick counts. The wolf blows only to the east. When a house is blown, it also knocks down any houses to its east that have fewer bricks. We need to calculate the total damage (number of houses blown) for each house if the wolf blows on it.
🏠 Problem Setup & Example
Houses are in a row, each with a brick count.
Wolf blows on house Hi.
Hi falls.
Any house Hj (where j>i) also falls if Hj has fewer bricks than Hi (bricks(Hj)<bricks(Hi)).
Example: House brick counts: [34, 57, 70, 19, 48, 2]
Blow on 34:
34 falls.
Looking right: 57 (>34), 70 (>34), **19 (<34)**, 48 (>34), 2 (<34).
Total damage: 1 (self) + 2 (19, 2) = 3 houses.
Blow on 57:
57 falls.
Looking right: 70 (>57), 19 (<57), 48 (<57), 2 (<57).
Total damage: 1 (self) + 3 (19, 48, 2) = 4 houses.
Blow on 70:
70 falls.
Looking right: 19 (<70), 48 (<70), 2 (<70).
Total damage: 1 (self) + 3 (19, 48, 2) = 4 houses.
The goal is to compute this damage value for every house. A naive O(N2) approach would be to iterate through each house and then iterate through all houses to its right. We aim for a more efficient O(N) or O(NlogN) solution.
🌟 Part B: "Special" Houses - Mostly Sorted Array
A house is "special" if:
It has no easterly neighbor (it's the rightmost house).
OR its adjacent easterly neighbor has at least as many bricks (bricks(Hi+1)≥bricks(Hi)).
The problem states that all but one house is special. This implies a specific structure: the array of brick counts is monotonically increasing up to a certain point, then it potentially decreases for one house, and then resumes monotonically increasing. In simpler terms, the array is sorted except for one "dip" or "peak."
Example: [1, 2, 3, 4, 2, 3, 4, 5]
The sequence
1, 2, 3, 4is increasing.The
4to2transition is where the "non-special" house might be (the4is special because4 >= 2is false, but2 < 4is true, so4is not special, but2is special because2 < 3).The sequence
2, 3, 4, 5is increasing.
This means we can find the "boundary" where the sorted order breaks in O(N) time by simply scanning. Let's say the array is A[0...k-1] (increasing) and A[k...N-1] (increasing). The non-special house is the one before the first decrease.
🎯 Damage Calculation with "Special" Structure
Houses to the Right of the "Dip" (e.g.,
A[k...N-1]):If the wolf blows on any house in this increasing segment, it can only knock down itself.
Why? Because to its right, all houses have more bricks (or equal, but the rule is "fewer bricks").
So, for any house Hi in this segment, the damage is always 1.
This part of the damage array can be filled in O(N) time.
Houses to the Left of the "Dip" (e.g.,
A[0...k-1]):If the wolf blows on house Hi in this segment, it can only knock down houses to its right.
Houses to its immediate right (within
A[0...k-1]) will have more bricks, so they won't fall.The only houses that can fall are those in the
A[k...N-1]segment that are smaller than Hi.Crucially, the
A[k...N-1]segment is also sorted.
✌️ Two-Finger Algorithm for O(N) Damage Calculation
To count houses in A[k...N-1] that are smaller than Hi (for i<k) in O(N) time, we use a two-pointer (two-finger) approach:
Initialize a pointer
jtok(the start of the right-hand sorted segment).Iterate with pointer
ifrom0tok-1(the left-hand sorted segment).For each
H_i:Advance
jto the right as long asbricks(H_j) < bricks(H_i)andj < N.The number of houses in
A[k...N-1]that Hi blows down isj - k.The total damage for
H_iis1 + (j - k).
Since both
iandjonly advance forward, the total work for this phase is O(N).
Total Time Complexity for Part B: O(N) (to find the dip) + O(N) (to fill right segment) + O(N) (two-finger algorithm for left segment) = O(N).
🌪️ Part C: General Case - Arbitrary Brick Counts
This part extends the problem to an arbitrary sequence of brick counts, without the "special house" assumption. We still need to compute the damage for each house in O(NlogN) time.
💡 Insight: Counting Inversions (Modified)
This problem is a variation of counting "inversions" or "smaller elements to the right." For each element A[i], we need to count how many A[j] exist such that j>i and A[j]<A[i].
A standard way to count inversions in O(NlogN) time is to use a modified Merge Sort.
Merge Sort Modification
Divide: Split the array into two halves.
Conquer: Recursively solve for the left and right halves. Each recursive call will return a sorted subarray and the counts of inversions within its own half.
Combine (Merge): This is where the magic happens. When merging two sorted halves (left
Land rightR), we can count the "cross-inversions" (elements inLthat are greater than elements inR).While merging, if an element from
R(R[j]) is taken before an element fromL(L[i]), it meansR[j]is smaller thanL[i]and all remaining elements inLfromL[i]onwards. This is how typical inversion counting works.For this specific problem, we need to count elements in
Rthat are smaller than elements inL.When we take an element
L[i]and there arexelements remaining inRthat are smaller thanL[i], we increment the damage count forL[i]byx. This requires a slight modification to the standard merge step.
Detailed Merge Step Modification for Damage Calculation:
During the merge process, when we compare
L[i]andR[j]:If
L[i] <= R[j]: We takeL[i]. At this point, all elements fromRthat have already been merged were smaller thanL[i]. The count of such elements from the right subarray (for the original position ofL[i]) is added todamage[original_index(L[i])].If
L[i] > R[j]: We takeR[j]. ThisR[j]is an element that is smaller thanL[i](and all subsequent elements inLfromionwards). ThisR[j]would be counted as "blown over" byL[i]ifL[i]were the blowing house.
This specific counting logic needs careful implementation during the merge phase. Each L[i] would have its damage count updated based on how many elements from R it is greater than.
Time Complexity: The modified Merge Sort still performs O(N) work at each level of recursion and has logN levels, resulting in an overall O(NlogN) time complexity.

Ask anything
We've read this whole study set, so questions about it get the best answers.