Skip to content

Assignment 1

Part I: Introductory Problems — Greedy Algorithms

Problem 1 — Nested Frames

Problem statement

You are given several picture frames, where frame \(i\) has dimensions \(a_i \times b_i\). Determine whether the frames can be ordered so that every frame fits strictly inside the next one. Each frame may be rotated by \(90^\circ\). Give an \(O(n\log n)\) algorithm.

Greedy
Solution

The basic condition for frame \(i\) to fit inside frame \(j\) is

\[ (a_i < a_j \land b_i < b_j) \lor (a_i < b_j \land b_i < a_j) \]

Sort the frames by perimeter or area in \(O(n\log n)\) time, then check the containment condition above for every consecutive pair.

To prove correctness, observe that if frame \(i\) fits strictly inside frame \(j\), then both its perimeter and its area are strictly smaller. Therefore, if a nesting order containing all frames exists, sorting by either quantity places every inner frame before every frame that contains it. Consequently, the sorted order itself must be a valid nesting order, which is verified by the consecutive-pair checks.

For every frame, define \(x_i=\min(a_i,b_i)\) and \(y_i=\max(a_i,b_i)\).

The previous condition is equivalent to: \(x_i < x_j \land y_i < y_j\).

Sort the frames lexicographically by \((x_i,y_i)\) and check every consecutive pair using the condition above. Using both coordinates as the sorting key also handles equal values of \(x_i\) correctly.

If every check succeeds, the answer is yes. The running time is \(O(n\log n)\).

Problem 2 — Maximum Set of Compatible Intervals

Problem statement

You are given time intervals \((s_i,f_i)\). Select the maximum possible number of compatible (non-overlapping) intervals, meaning that no two selected intervals overlap. Give a greedy \(O(n\log n)\) algorithm.

Problem 3 — Covering Intervals with Points

Problem statement

You are given several intervals on a line. Select the minimum number of points such that every interval contains at least one selected point. Give a greedy \(O(n\log n)\) algorithm, and prove that this optimum equals the optimum of the previous problem.

Solution - Zahra Amirbeigi

Problem 4 — Superincreasing Coins

Problem statement

We have coins with values

\[ c_1 < c_2 < \dots < c_n \]

such that, for every \(i \ge 2\), \(c_i\) is greater than the sum of all preceding coin values.

There is exactly one coin of each value.

Given a target value \(V\), determine whether a subset of the coins has total value exactly \(V\).

Give a greedy \(O(n)\) algorithm.

Greedy
Solution

Because every coin is worth more than all previous coins combined, if \(V\) is at least \(c_n\), coin \(n\) must be selected: all the other coins together are insufficient. If \(V<c_n\), coin \(n\) must not be selected. Thus the choice for the last coin is forced. Continue in the same way, scanning the coins from last to first.

Problem 5 — Removing \(k\) Digits

Problem statement

A number is given as a length-\(n\) digit string containing no zeroes. Delete exactly \(k\) digits so that the resulting number is as large as possible. Give an \(O(n)\) algorithm.

Hints
First solve the case $k=1$.

Instead of treating the string as a number, compare strings lexicographically. We want the lexicographically greatest result.

When does deleting a digit improve the string lexicographically?

When the next digit is larger. Work out separately what happens when the next digit is equal.

Which deletion gives the greatest improvement?

An improvement is more valuable the closer it occurs to the beginning of the string.

Therefore...

Delete the leftmost digit that is smaller than the digit immediately after it. If no such digit exists, delete the last digit.

Problem 6 — Fractional Knapsack

Problem statement

There are several items; item \(i\) has weight \(w_i\) and value \(v_i\). A knapsack has capacity \(W\), and fractions of items may be taken. Maximize the total value. Give a greedy \(O(n\log n)\) algorithm and run it on the following input:

\[ (w,v)= (10,60),(20,100),(30,120),\qquad W=50 \]
Hints
Suppose the items could be ordered...
From divisible items to unit items

Because fractions of items may be taken, an item of weight \(w_i\) and value \(v_i\) can effectively be split into \(w_i\) unit-weight items, each worth \(\frac{v_i}{w_i}\).

How do we solve this new problem?

We need to take \(W\) unit-weight items, so sort them by value and take the \(W\) most valuable ones.

How does this solve the original problem?

Define the value density of each item as \(value_i = \frac{v_i}{w_i}\). We should take as much as possible from items with greater value density.

Problem 7 — Forming a Triangle

Problem statement

You are given \(n\) line segments with positive lengths \(a_1, a_2, \dots, a_n\). Give an \(O(n\log n)\) algorithm that determines whether three distinct segments can form a triangle of positive area. Output one valid triple if it exists; otherwise report that none exists.

Solution - Negar Yarahmadi
Attachments

Problem 8 — Merging Numbers on a Board

Problem statement

Several numbers are written on a board. In each step, erase two numbers \(x\) and \(y\) and replace them with \(x+y\); the step costs \(x+y\). After \(n-1\) operations, only one number must remain. Give a greedy \(O(n\log n)\) algorithm minimizing the total cost, and run it on the following input:

\[ 5,\ 9,\ 12,\ 13,\ 16,\ 45 \]

Problem 9 — Prefix-Free Coding

Problem statement

We want to design a compression algorithm for a set of characters by assigning a binary string to each character such that:

  • no codeword is a prefix of another (the code is prefix-free), so the text can be decoded uniquely;
  • given the frequency of each character, the total number of bits needed to store the text is minimized.

More precisely, if character \(i\) has frequency \(f_i\) and its assigned codeword has length \(\ell_i\), minimize \(\sum_i f_i \ell_i\).

Hint: This problem is equivalent to the previous one.

Give a greedy \(O(n\log n)\) algorithm for constructing these codewords.

Problem 10 — Scheduling with Deadlines

Problem statement

There are \(n\) jobs. Job \(i\) takes exactly one unit of time, yields profit \(p_i\), and must finish by time \(d_i\) (Job Sequencing with Deadlines). Schedule a subset of the jobs to maximize total profit. Give a greedy \(O(n\log n)\) algorithm.

Solution - Maedeh Heydari

Problem 11 — Optimal Permutation of \(\sum a_i b_i\)

Problem statement

Two length-\(n\) sequences \(A\) and \(B\) are given. We may permute \(A\).

  • (a) Permute \(A\) to minimize \(\sum_{i=1}^{n} a_i b_i\).
  • (b) Permute \(A\) to maximize \(\sum_{i=1}^{n} a_i b_i\).

Give an \(O(n\log n)\) algorithm for each part.

Hints

For simplicity, assume \(B\) is sorted and only the order of \(A\) may be changed.

How does swapping $a_i$ and $a_j$ affect the objective?
\[ b_i \cdot (a_j - a_i) + b_j \cdot (a_i - a_j) = (b_i - b_j) \cdot (a_j - a_i)\]

Assume \(i>j\); then \(b_i \geq b_j\).

Under what conditions is this swap beneficial or harmful?

Problem 12 — Assigning Two Teams

Problem statement

There are \(n\) people. Person \(i\) has athletic ability \(a_i\) and academic ability \(b_i\). Assign exactly \(k\) people to the sports team and the remaining \(n-k\) to the academic team, maximizing the sum of abilities in the fields to which people are assigned.

Solution - Mahdi Mansouri

Problem 13 — Independent Set or Matching

Problem statement

Given a graph with \(n\) vertices and \(m\) edges, give an \(O(n+m)\) algorithm that finds one of the following:

  • an independent set with at least \(\frac{n}{3}\) vertices;
  • or a matching with at least \(\frac{n}{3}\) edges.

It is guaranteed that at least one of the two always exists.

Solution - Ilya Yazdani Varzi

Part I: Introductory Problems — Divide and Conquer

Problem 14 — Parametric Recurrence

Problem statement

Use a recursion tree to derive a tight bound for the following recurrence:

\[ T(n) = T(\alpha n) + T\bigl((1-\alpha)n\bigr) + cn \]

where \(\alpha \in (0,1)\) and \(c>0\) are constants. Explicitly discuss how the bound depends on \(\alpha\).

Problem 15 — Subarray with No Unique Element (Analysis)

Problem statement

An array \(A[1 \dots n]\) is given. Determine whether there is a nonempty contiguous subarray with no unique element—that is, every value appearing in the subarray occurs there at least twice. The following algorithm is proposed:

For a range \(A[l \dots r]\), check in time linear in its length whether some value occurs exactly once. If no such value exists, the range itself is valid. Otherwise, suppose \(A[i]\) occurs only once in \(A[l \dots r]\). No valid subarray can contain index \(i\), so recursively solve \(A[l \dots i-1]\) and \(A[i+1 \dots r]\). The current range returns “yes” if and only if at least one recursive call returns “yes.”

  • (a) Prove the algorithm correct.
  • (b) Analyze its worst-case running time.
  • (c) Give a family of inputs showing that the analysis in part (b) is tight.

Problem 16 — Union, Intersection, and Difference

Problem statement

Two sorted arrays \(A[1 \dots n]\) and \(B[1 \dots m]\) are given. Give an \(O(n+m)\) algorithm that computes each of the following sets in sorted order, with every value appearing only once in the output:

\[ A \cup B,\qquad A \cap B,\qquad A-B \]

Problem 17 — Largest and Second Largest

Problem statement

An array of \(n\) distinct numbers is given. Find its largest and second-largest elements using at most

\[ n+\lceil \log_2 n \rceil-2 \]

comparisons.

Solution - Yasaman Kavianpour

Problem 18 — The \(k\)-th Element of Two Sorted Arrays

Problem statement

Two sorted arrays

\[ A[1..n],\qquad B[1..m] \]

are given. Find the \(k\)-th element of their sorted union without constructing the entire merged array.

  • (a) Give a divide-and-conquer algorithm running in \(O(\log(n+m))\) time.
  • (b) Run your algorithm on the following input:
\[ A=[2,5,8,12,17],\qquad B=[1,3,9,10,20,25],\qquad k=7 \]
Solution - Ali Almasi
Attachments

Problem 19 — Maximum Subarray Sum

Problem statement

Given an array of integers, find the maximum sum of a contiguous subarray. Give a divide-and-conquer algorithm running in \(O(n\log n)\) time.

Problem 20 — Minimum and Maximum

Problem statement

Given an array, find its minimum and maximum using as few comparisons as possible. Give a divide-and-conquer algorithm, derive its comparison count, and compare it with the straightforward algorithm.

Solution - Saba Khanmohammadi Abhari

Problem 21 — Counting Inversions

Problem statement

A sequence \(A[1 \dots n]\) is given. Compute its number of inversions.

A pair of indices \((i,j)\) satisfying

\[ i<j \qquad \text{and} \qquad A[i]>A[j] \]

is called an inversion.

Give an \(O(n\log n)\) algorithm for counting the inversions.

Problem 22 — Applications of Inversions

Problem statement

Reduce each of the following problems to counting inversions.

  • (a) Given points in the plane, count pairs in which one point lies above and to the left of the other; that is,
\[ x_i < x_j, \qquad y_i > y_j. \]
  • (b) Given intervals \([l_i,r_i]\), count pairs in which one interval lies entirely inside the other; that is,
\[ l_i < l_j, \qquad r_j < r_i. \]
  • (c) Given a sequence of positive and negative numbers, count the contiguous ranges whose element sum is negative.
Solution - Sobhan Behzadipour

Problem 23 — Sorting with Adjacent Swaps

Problem statement

An unsorted sequence of numbers is given and may be sorted using only adjacent swaps. Reduce this problem to counting inversions and thereby determine the minimum number of adjacent swaps required.

Solution - Parsa Adlparvar
Attachments

Problem 24 — Counterfeit Coin

Problem statement

\(n\) apparently identical coins are given. Exactly one is counterfeit and lighter than the rest. A balance scale is available; each weighing reports that the left pan is lighter, the right pan is lighter, or the pans balance. Find the optimal worst-case number of weighings as a function of \(n\), give an algorithm attaining this bound, and prove the bound optimal—that is, show that no algorithm can always succeed with fewer weighings.

Solution - Seyed Mohammad Yasin Haji-Khalili

Problem 25 — Two Eggs

Problem statement

You have a building with \(n\) floors and exactly two eggs. There is an unknown threshold \(k\): an egg dropped from floor \(k\) or below does not break, while one dropped from above \(k\) does. More precisely, a drop from ground level never breaks an egg, while a drop from the roof (floor \(n+1\)) always does. A broken egg cannot be reused. Determine \(k\) while minimizing the worst-case number of drops. Find the optimal worst-case number of drops as a function of \(n\), give a strategy attaining this bound, and prove it optimal—that is, show that no strategy can always succeed with fewer drops.

Solution - Niki Rashidian

Part II: Advanced Problems — Greedy Algorithms

Problem 26 — Searching a Sorted Matrix

Problem statement

An \(n\times n\) matrix is given whose rows and columns are sorted in increasing order. Give a greedy \(O(n)\) algorithm that determines whether \(x\) occurs in the matrix, then run it on the sample input below:

\[ \begin{bmatrix} 1&4&7&11\\ 2&5&8&12\\ 3&6&9&16\\ 10&13&14&17 \end{bmatrix} \qquad,\qquad x=14 \]

Problem 27 — Scheduling with Durations, Deadlines, and Values

Problem statement

There are \(n\) jobs. Job \(i\) has processing time \(d_i\), deadline \(t_i\), and value \(u_i\). Given a target value \(U\), decide whether some subset of the jobs can be scheduled non-preemptively on one machine so that every selected job finishes by its deadline and their total value is at least \(U\).

Prove that this decision problem is NP-complete. In particular, prove membership in NP and give a polynomial-time reduction from 0–1 Knapsack; for the reduction, consider instances in which every job has the same deadline.

Problem 28 — Binary Matrix with Given Row and Column Sums

Problem statement

Construct an \(n\times n\) binary matrix having exactly \(R[i]\) ones in row \(i\) and exactly \(C[j]\) ones in column \(j\), or report that no such matrix exists. Give an \(O(n^2)\) algorithm.

Solution - Amir Mohammad Hamidi

Problem 29 — Kings on the Main Diagonal

Problem statement

An \(n\times n\) chessboard contains \(n\) kings on distinct squares. In one move, a king may be moved to a legal empty square. Find the minimum number of moves needed to occupy every square of the main diagonal, using an \(O(n\log n)\) algorithm.

Solution - Parsa Bashari

Problem 30 — Tower of Boxes

Problem statement

There are \(n\) boxes. Box \(i\) has weight \(a_i\) and load limit \(b_i\). Determine whether all \(n\) boxes can be stacked so that, for every box, the total weight above it does not exceed its load limit. You may choose the order. Give an \(O(n\log n)\) algorithm.

Problem 31 — Optimal Parenthesization

Problem statement

A sequence of \(2n\) numbers is given. Choose a valid parenthesis string of the same length, then select the sequence entries corresponding to opening parentheses. Maximize the sum of the selected numbers. Give an \(O(n\log n)\) algorithm.

Problem 32 — Interval Partitioning

Problem statement

A set of time intervals is given. Partition them into the minimum number of groups so no two intervals in the same group overlap. Give a greedy \(O(n\log n)\) algorithm.

Problem 33 — Fuel-Station Stops

Problem statement

Along a straight route, fuel stations lie at distances \(x_1 < x_2 < \dots < x_n\) from the origin, and the destination is at distance \(D\). A car starts with a full tank and can travel at most \(L\) distance units per tank. At each station where it stops, the tank is completely refilled. Give a greedy \(O(n)\) algorithm that finds the minimum number of stops needed to reach the destination, or reports that it is unreachable.

Problem 34 — Adjacent-Removal Game

Problem statement

A length-\(n\) sequence is given. In each step, choose two adjacent numbers, remove both, and score their absolute difference \(|x-y|\). Perform any number of operations to maximize the total score. Give an \(O(n\log n)\) algorithm.

  • (a) \(n\) is even.
  • (b) \(n\) is odd.

Part II: Advanced Problems — Divide and Conquer

Problem 35 — Finding the Median

Problem statement

An array \(A[1 \dots n]\) is given. Define its median as the middle element in sorted order: element \(\frac{n+1}{2}\) when \(n\) is odd, and element \(\frac{n}{2}\) when \(n\) is even. Give an \(O(n)\) algorithm for finding the median.

Solution - Fatemeh Parvizi

Problem 36 — Largest Uniform Block

Problem statement

An \(n\times n\) binary matrix \(M\) is given. A solid block is a submatrix of the form \(M[i \dots i'][j \dots j']\) whose entries are all equal. Give a divide-and-conquer algorithm running in \(O(n^2 \log n)\) time that finds the area of the largest solid block in \(M\).

Problem 37 — Closest Pair of Points

Problem statement

You are given \(n\) points in the plane. Find the distance between the closest pair of points. Give a divide-and-conquer algorithm running in \(O(n\log n)\) time.

Solution - Sobhan Aram

Problem 38 — Maximum Subarray with Bounded Length

Problem statement

An array of integers, which may be positive, negative, or zero, and an integer \(L\) are given. Find the maximum sum of a contiguous subarray whose length is at most \(L\). Give a divide-and-conquer algorithm.

Problem 39 — Subarray with No Unique Element

Problem statement

Given an array, determine whether it has a contiguous subarray with no unique element—that is, every value appearing in the subarray occurs there at least twice. Give an \(O(n\log n)\) algorithm.

Problem 40 — Tiling with L-Trominoes

Problem statement

A \(2^n\times 2^n\) board has exactly one blocked square. Tile all remaining squares with L-shaped trominoes, each covering exactly three squares, with no overlap. Such a tiling is guaranteed to exist. Give an algorithm that constructs one.

Solution - Parnia Dabbagh

Problem 41 — Average-Free Permutation

Problem statement

Construct a permutation of \(1\) through \(n\) such that, for every pair of indices \(i<j\), the average of \(A_i\) and \(A_j\) does not occur among the entries \(A_i,A_{i+1},\dots,A_j\).

Problem 42 — Entry Larger than Its Neighbors

Problem statement

An \(n\times m\) matrix with pairwise distinct entries is given. Find an entry larger than each of its edge-adjacent neighbors. Give an \(O(n\log m)\) algorithm.