1. Home
  2. Explore
  3. Computer Science
  4. 6.006 Problem Session

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

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)T(n) = aT(n/b) + f(n)T(n)=aT(n/b)+f(n), where:

  • a≥1a \ge 1a≥1: The number of subproblems.

  • b>1b > 1b>1: The factor by which the input size is reduced in each subproblem.

  • f(n)f(n)f(n): The cost of the work done outside the recursive calls (e.g., merging results).

The theorem has three cases, comparing f(n)f(n)f(n) with nlog⁡ban^{\log_b a}nlogb​a:

  1. Case 1: Work at leaves dominates

    • If f(n)=O(nlog⁡ba−ϵ)f(n) = O(n^{\log_b a - \epsilon})f(n)=O(nlogb​a−ϵ) for some constant ϵ>0\epsilon > 0ϵ>0.

    • Then T(n)=Θ(nlog⁡ba)T(n) = \Theta(n^{\log_b a})T(n)=Θ(nlogb​a).

    • Intuition: The cost of traversing the recursion tree (the "split" and "combine" steps) is greater than the work done at each node.

  2. Case 2: Work is balanced across levels

    • If f(n)=Θ(nlog⁡balog⁡kn)f(n) = \Theta(n^{\log_b a} \log^k n)f(n)=Θ(nlogb​alogkn) for some constant k≥0k \ge 0k≥0.

    • Then T(n)=Θ(nlog⁡balog⁡k+1n)T(n) = \Theta(n^{\log_b a} \log^{k+1} n)T(n)=Θ(nlogb​alogk+1n).

    • Intuition: The work at each level of the recursion tree is roughly the same.

  3. Case 3: Work at root dominates

    • If f(n)=Ω(nlog⁡ba+ϵ)f(n) = \Omega(n^{\log_b a + \epsilon})f(n)=Ω(nlogb​a+ϵ) for some constant ϵ>0\epsilon > 0ϵ>0.

    • AND af(n/b)≤cf(n)af(n/b) \le cf(n)af(n/b)≤cf(n) for some constant c<1c < 1c<1 (the "regularity condition").

    • Then T(n)=Θ(f(n))T(n) = \Theta(f(n))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)T(n) = 2T(n/2) + O(\sqrt{n})T(n)=2T(n/2)+O(n​).

🎯 Master Theorem Application

  1. Identify parameters:

    • a=2a = 2a=2

    • b=2b = 2b=2

    • f(n)=O(n)=O(n1/2)f(n) = O(\sqrt{n}) = O(n^{1/2})f(n)=O(n​)=O(n1/2)

  2. Calculate nlog⁡ban^{\log_b a}nlogb​a:

    • nlog⁡22=n1=nn^{\log_2 2} = n^1 = nnlog2​2=n1=n

  3. Compare f(n)f(n)f(n) with nlog⁡ban^{\log_b a}nlogb​a:

    • We have f(n)=O(n1/2)f(n) = O(n^{1/2})f(n)=O(n1/2).

    • We need to compare n1/2n^{1/2}n1/2 with n1n^1n1.

    • Since n1/2=O(n1−1/2)n^{1/2} = O(n^{1 - 1/2})n1/2=O(n1−1/2), we can set ϵ=1/2\epsilon = 1/2ϵ=1/2.

    • This matches Case 1 of the Master Theorem: f(n)=O(nlog⁡ba−ϵ)f(n) = O(n^{\log_b a - \epsilon})f(n)=O(nlogb​a−ϵ).

  4. Conclusion:

    • T(n)=Θ(nlog⁡ba)=Θ(n1)=Θ(n)T(n) = \Theta(n^{\log_b a}) = \Theta(n^1) = \Theta(n)T(n)=Θ(nlogb​a)=Θ(n1)=Θ(n).

🌲 Recursion Tree Analysis

A recursion tree visually represents the work done at each level of a recursive algorithm.

  1. Levels and Work:

    • Root (Level 0): Work done is O(n)O(\sqrt{n})O(n​). It makes two calls to T(n/2)T(n/2)T(n/2).

    • Level 1: Each of the 2 nodes does O(n/2)O(\sqrt{n/2})O(n/2​) work. Total work: 2×O(n/2)=O(2n)2 \times O(\sqrt{n/2}) = O(\sqrt{2n})2×O(n/2​)=O(2n​).

    • Level lll: There are 2l2^l2l nodes. Each node processes input of size n/2ln/2^ln/2l, doing O(n/2l)O(\sqrt{n/2^l})O(n/2l​) work.

      • Total work at level lll: 2l×O(n/2l)=O(2ln2l)=O(2l/2n)2^l \times O(\sqrt{n/2^l}) = O(2^l \frac{\sqrt{n}}{\sqrt{2^l}}) = O(2^{l/2} \sqrt{n})2l×O(n/2l​)=O(2l2l​n​​)=O(2l/2n​).

  2. 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: log⁡2n\log_2 nlog2​n levels (from l=0l=0l=0 to l=log⁡2n−1l=\log_2 n - 1l=log2​n−1).

  3. 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\sqrt{n}n​:

      T(n)=O(n∑l=0log⁡2n−1(2)l)T(n) = O(\sqrt{n} \sum_{l=0}^{\log_2 n - 1} (\sqrt{2})^l)T(n)=O(n​∑l=0log2​n−1​(2​)l)
    • This is a geometric series with ratio 2\sqrt{2}2​. The sum is approximately (2)log⁡2n=(21/2)log⁡2n=(2log⁡2n)1/2=n1/2=n(\sqrt{2})^{\log_2 n} = (2^{1/2})^{\log_2 n} = (2^{\log_2 n})^{1/2} = n^{1/2} = \sqrt{n}(2​)log2​n=(21/2)log2​n=(2log2​n)1/2=n1/2=n​.

    • So, T(n)=O(n⋅n)=O(n)T(n) = O(\sqrt{n} \cdot \sqrt{n}) = O(n)T(n)=O(n​⋅n​)=O(n).

This matches the result from the Master Theorem, confirming T(n)=Θ(n)T(n) = \Theta(n)T(n)=Θ(n).


💡 Example 1B: Master Theorem with Different Branching Factors

Consider the recurrence T(n)=8T(n/4)+O(nn)T(n) = 8T(n/4) + O(n\sqrt{n})T(n)=8T(n/4)+O(nn​).

🎯 Master Theorem Application

  1. Identify parameters:

    • a=8a = 8a=8

    • b=4b = 4b=4

    • f(n)=O(nn)=O(n3/2)f(n) = O(n\sqrt{n}) = O(n^{3/2})f(n)=O(nn​)=O(n3/2)

  2. Calculate nlog⁡ban^{\log_b a}nlogb​a:

    • nlog⁡48n^{\log_4 8}nlog4​8. Since 4x=8  ⟹  (22)x=23  ⟹  2x=3  ⟹  x=3/24^x = 8 \implies (2^2)^x = 2^3 \implies 2x = 3 \implies x = 3/24x=8⟹(22)x=23⟹2x=3⟹x=3/2.

    • So, nlog⁡48=n3/2n^{\log_4 8} = n^{3/2}nlog4​8=n3/2.

  3. Compare f(n)f(n)f(n) with nlog⁡ban^{\log_b a}nlogb​a:

    • We have f(n)=O(n3/2)f(n) = O(n^{3/2})f(n)=O(n3/2).

    • We also calculated nlog⁡ba=n3/2n^{\log_b a} = n^{3/2}nlogb​a=n3/2.

    • Since f(n)f(n)f(n) is big O of nlog⁡ban^{\log_b a}nlogb​a, and not necessarily Θ\ThetaΘ, this falls under Case 2 with k=0k=0k=0 (meaning log⁡0n=1\log^0 n = 1log0n=1).

    • Important: Because f(n)f(n)f(n) is O(n3/2)O(n^{3/2})O(n3/2) and not Θ(n3/2)\Theta(n^{3/2})Θ(n3/2), the resulting T(n)T(n)T(n) will also be OOO instead of Θ\ThetaΘ.

  4. Conclusion:

    • T(n)=O(nlog⁡balog⁡k+1n)=O(n3/2log⁡0+1n)=O(n3/2log⁡n)T(n) = O(n^{\log_b a} \log^{k+1} n) = O(n^{3/2} \log^{0+1} n) = O(n^{3/2} \log n)T(n)=O(nlogb​alogk+1n)=O(n3/2log0+1n)=O(n3/2logn).

🌲 Recursion Tree Analysis

  1. Levels and Work:

    • Root (Level 0): Work O(n3/2)O(n^{3/2})O(n3/2). It makes 8 calls to T(n/4)T(n/4)T(n/4).

    • Level lll: There are 8l8^l8l nodes. Each node processes input of size n/4ln/4^ln/4l, doing O((n/4l)3/2)O((n/4^l)^{3/2})O((n/4l)3/2) work.

      • Total work at level lll: 8l×O((n/4l)3/2)=O(8l⋅n3/2⋅(1/4l)3/2)8^l \times O((n/4^l)^{3/2}) = O(8^l \cdot n^{3/2} \cdot (1/4^l)^{3/2})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)= O(8^l \cdot n^{3/2} \cdot (1/4^{3/2})^l) = O(8^l \cdot n^{3/2} \cdot (1/8)^l) = O(n^{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)O(n^{3/2})O(n3/2). This is characteristic of Master Theorem Case 2.

  2. Tree Depth:

    • The problem size reduces by a factor of 4 at each level.

    • Depth of the tree: log⁡4n\log_4 nlog4​n levels.

  3. 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)O(n^{3/2})O(n3/2) and there are log⁡4n\log_4 nlog4​n levels:

      T(n)=O(n3/2⋅log⁡4n)T(n) = O(n^{3/2} \cdot \log_4 n)T(n)=O(n3/2⋅log4​n)
    • Since the base of the logarithm only affects the constant factor, we write:

      T(n)=O(n3/2log⁡n)T(n) = O(n^{3/2} \log n)T(n)=O(n3/2logn)

This matches the result from the Master Theorem, confirming T(n)=O(n3/2log⁡n)T(n) = O(n^{3/2} \log n)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 kkk. 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(log⁡k)O(\log k)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:

  1. Phase 1: Finding an Upper Bound (Exponential Search)

    • Start at planet index 111.

    • Repeatedly double the search range by visiting planets at indices 20,21,22,…,2m2^0, 2^1, 2^2, \dots, 2^m20,21,22,…,2m.

    • At each planet 2m2^m2m, query the oracle: Is the target planet kkk on a planet with an index smaller than 2m2^m2m?

    • Stop when we find a planet 2m2^m2m such that k≤2mk \le 2^mk≤2m.

    • At this point, we know that 2m−1<k≤2m2^{m-1} < k \le 2^m2m−1<k≤2m. We have successfully bounded the search space.

    • Time Complexity: This phase involves visiting m+1m+1m+1 planets. Since 2m−1<k≤2m2^{m-1} < k \le 2^m2m−1<k≤2m, we know that m≈log⁡2km \approx \log_2 km≈log2​k. Therefore, this phase takes O(log⁡k)O(\log k)O(logk) time.

  2. Phase 2: Binary Search

    • Now that we have a lower bound (2m−12^{m-1}2m−1) and an upper bound (2m2^m2m) for kkk, 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−12^m - 2^{m-1} = 2^{m-1}2m−2m−1=2m−1 also takes O(log⁡(2m−1))=O(m−1)=O(log⁡k)O(\log(2^{m-1})) = O(m-1) = O(\log k)O(log(2m−1))=O(m−1)=O(logk) time.

The total time complexity is O(log⁡k)+O(log⁡k)=O(log⁡k)O(\log k) + O(\log k) = O(\log k)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)O(1)O(1)

  • Import Image (add on top): O(N)O(N)O(N)

  • Display (all IDs in order): O(N)O(N)O(N)

  • Move Below (move image X below image Y): O(log⁡N)O(\log N)O(logN)

🤔 Initial Thoughts & Challenges

  • A simple linked list can handle Import (add to head) and Display in O(1)O(1)O(1) and O(N)O(N)O(N) respectively, but Move Below would require O(N)O(N)O(N) to find X and Y.

  • A sorted array (or balanced binary search tree) could find X and Y in O(log⁡N)O(\log N)O(logN) but Import would be O(N)O(N)O(N) (or O(log⁡N)O(\log N)O(logN) for a BST), and Move Below (reordering) would be O(N)O(N)O(N) because it involves shifting elements.

The key challenge is the Move Below operation's O(log⁡N)O(\log N)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:

  1. Doubly Linked List: Stores the images in their visual display order. Each node contains an image ID. This allows for O(1)O(1)O(1) insertion/deletion once the nodes are found.

  2. 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

  1. Make Empty Document:

    • Initialize an empty doubly linked list and an empty sorted array (or BST).

    • Time Complexity: O(1)O(1)O(1).

  2. 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)O(1)O(1).

      • Sorted array insertion: O(N)O(N)O(N) (due to shifting elements).

      • Balanced BST insertion: O(log⁡N)O(\log N)O(logN).

      • The problem states O(N)O(N)O(N) for Import, so a sorted array is acceptable here.

  3. Display:

    • Traverse the doubly linked list from head to tail, printing each image ID.

    • Time Complexity: O(N)O(N)O(N).

  4. 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(log⁡N)O(\log N)O(logN) (for sorted array via binary search, or BST lookup).

    • Step 2: Update Doubly Linked List:

      • Remove node_X from its current position in the doubly linked list. This involves updating the next and prev pointers of its neighbors.

      • Insert node_X immediately after node_Y in the doubly linked list. This also involves updating next and prev pointers.

      • The pointers stored in the sorted array/BST remain valid because they point to specific nodes, not positions.

      • Time Complexity: O(1)O(1)O(1) (constant number of pointer manipulations).

    • Total Time Complexity: O(log⁡N)+O(1)=O(log⁡N)O(\log N) + O(1) = O(\log N)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 HiH_iHi​.

  • HiH_iHi​ falls.

  • Any house HjH_jHj​ (where j>ij > ij>i) also falls if HjH_jHj​ has fewer bricks than HiH_iHi​ (bricks(Hj)<bricks(Hi)bricks(H_j) < bricks(H_i)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)O(N^2)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)O(N)O(N) or O(Nlog⁡N)O(N \log N)O(NlogN) solution.


🌟 Part B: "Special" Houses - Mostly Sorted Array

A house is "special" if:

  1. It has no easterly neighbor (it's the rightmost house).

  2. OR its adjacent easterly neighbor has at least as many bricks (bricks(Hi+1)≥bricks(Hi)bricks(H_{i+1}) \ge bricks(H_i)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, 4 is increasing.

  • The 4 to 2 transition is where the "non-special" house might be (the 4 is special because 4 >= 2 is false, but 2 < 4 is true, so 4 is not special, but 2 is special because 2 < 3).

  • The sequence 2, 3, 4, 5 is increasing.

This means we can find the "boundary" where the sorted order breaks in O(N)O(N)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

  1. 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 HiH_iHi​ in this segment, the damage is always 1.

    • This part of the damage array can be filled in O(N)O(N)O(N) time.

  2. Houses to the Left of the "Dip" (e.g., A[0...k-1]):

    • If the wolf blows on house HiH_iHi​ 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 HiH_iHi​.

    • Crucially, the A[k...N-1] segment is also sorted.

✌️ Two-Finger Algorithm for O(N)O(N)O(N) Damage Calculation

To count houses in A[k...N-1] that are smaller than HiH_iHi​ (for i<ki < ki<k) in O(N)O(N)O(N) time, we use a two-pointer (two-finger) approach:

  • Initialize a pointer j to k (the start of the right-hand sorted segment).

  • Iterate with pointer i from 0 to k-1 (the left-hand sorted segment).

  • For each H_i:

    • Advance j to the right as long as bricks(H_j) < bricks(H_i) and j < N.

    • The number of houses in A[k...N-1] that HiH_iHi​ blows down is j - k.

    • The total damage for H_i is 1 + (j - k).

  • Since both i and j only advance forward, the total work for this phase is O(N)O(N)O(N).

Total Time Complexity for Part B: O(N)O(N)O(N) (to find the dip) + O(N)O(N)O(N) (to fill right segment) + O(N)O(N)O(N) (two-finger algorithm for left segment) = O(N)O(N)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(Nlog⁡N)O(N \log N)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]A[i]A[i], we need to count how many A[j]A[j]A[j] exist such that j>ij > ij>i and A[j]<A[i]A[j] < A[i]A[j]<A[i].

A standard way to count inversions in O(Nlog⁡N)O(N \log N)O(NlogN) time is to use a modified Merge Sort.

Merge Sort Modification

  1. Divide: Split the array into two halves.

  2. 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.

  3. Combine (Merge): This is where the magic happens. When merging two sorted halves (left L and right R), we can count the "cross-inversions" (elements in L that are greater than elements in R).

    • While merging, if an element from R (R[j]) is taken before an element from L (L[i]), it means R[j] is smaller than L[i] and all remaining elements in L from L[i] onwards. This is how typical inversion counting works.

    • For this specific problem, we need to count elements in R that are smaller than elements in L.

    • When we take an element L[i] and there are x elements remaining in R that are smaller than L[i], we increment the damage count for L[i] by x. 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] and R[j]:

    • If L[i] <= R[j]: We take L[i]. At this point, all elements from R that have already been merged were smaller than L[i]. The count of such elements from the right subarray (for the original position of L[i]) is added to damage[original_index(L[i])].

    • If L[i] > R[j]: We take R[j]. This R[j] is an element that is smaller than L[i] (and all subsequent elements in L from i onwards). This R[j] would be counted as "blown over" by L[i] if L[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)O(N)O(N) work at each level of recursion and has log⁡N\log NlogN levels, resulting in an overall O(Nlog⁡N)O(N \log N)O(NlogN) time complexity.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent