Algorithms Problem-Solving


Algorithms Problem-Solving

Corey
Welcome to our problem-solving session. The idea is to bridge two kinds of work in an algorithms course: lectures introduce foundational data structures and algorithms, while problem sets ask you to apply them in less familiar ways. These sessions model how to approach that applied work, and they’re meant to complement—not replace—interactive recitations.

Maria
So the focus isn’t just getting an answer. It’s showing how to reason your way toward one: identify useful facts, break a problem into manageable steps, and explain the algorithm clearly.

Corey
Exactly. Let’s begin with asymptotic growth. In the first question, we’re given groups of functions and asked to order them from slowest-growing to fastest-growing. If two functions grow at the same asymptotic rate, they belong together in a set rather than being arbitrarily placed in separate positions.

Maria
The simple example makes that convention clear: among root n, n, and n plus root n, root n grows slowest. The other two are both order n, so they should be grouped as asymptotically equivalent.

Corey
Right. A common strategy is to simplify each expression into familiar pieces. In one group, several functions have an n factor, so we can compare the factors attached to n. A logarithmic factor grows more slowly than a positive-degree polynomial factor, which lets us rank those functions without comparing every expression from scratch.

Maria
And the broader rule is useful well beyond that one question: for positive exponents, logarithms raised to a fixed power grow more slowly than positive-degree polynomial functions. Exponential growth, in turn, eventually outruns polynomial growth.

Corey
That gives the order for the first group as f1, f5, f2, f3, and then f4. The important part isn’t memorizing those labels; it’s recognizing which term dominates and using familiar growth-rate comparisons to justify each step.

Maria
There’s also a formal way to compare two functions: take their ratio and examine its limit as n grows. If the ratio grows without bound, the numerator grows faster; if the ratio approaches zero, the denominator grows faster; and if it approaches a positive constant, the functions are asymptotically equivalent.

Corey
Sometimes the ratio is awkward to simplify directly, so taking the logarithm of the ratio can make the limit easier to analyze. The session also mentions little-o notation: it describes strict asymptotic separation, unlike big-O, which allows equality in growth rate.

Maria
The next group introduces binomial coefficients. The expression n choose k counts the ways to select k objects from n, and its factorial form is n factorial divided by k factorial times n-minus-k factorial.

Corey
One way to remember that formula is to start with all n factorial orderings of the objects, then divide out the reorderings within the chosen group and within the unchosen group. That gives the two factorials in the denominator.

Maria
But factorials can be hard to compare directly with other functions. Stirling’s approximation helps: n factorial is approximately the square root of 2 pi n, multiplied by n over e raised to the n. It gives a very accurate approximation for large n.

Corey
And if all we need is a coarser growth-rate description, taking the logarithm of Stirling’s approximation shows that the logarithm of n factorial is theta of n log n. That’s a useful way to recognize factorial growth in later analyses.

Maria
For n choose 3, we can use the factorial definition and cancel: n factorial over 3 factorial times n-minus-3 factorial becomes n times n-minus-1 times n-minus-2, divided by 6. Its leading term is n cubed, so the binomial coefficient is asymptotically equivalent to a cubic polynomial.

Corey
The more involved example is n choose n over 2. Rewrite it as n factorial divided by the square of n-over-2 factorial, then apply Stirling’s approximation to the numerator and denominator.

Maria
After simplifying, the dominant behavior is 2 to the n divided by the square root of n. Constants such as the factors involving pi don’t affect the theta classification, so we describe it as theta of 2 to the n over root n.

Corey
That polynomial denominator matters. This function grows more slowly than 2 to the n, because it has been divided by a growing factor, but it still grows faster than the polynomial-sized functions in the group.

Maria
Putting the comparisons together, the ordering is the pair f2 and f5, which are asymptotically equivalent, then f3, then f1, and finally f4. For the last comparison, the key idea is that a term involving n raised to the n grows faster than one involving 2 raised to the n.

Corey
The general lesson is to transform unfamiliar expressions into forms you know how to compare. Factorials, binomial coefficients, logarithms, polynomials, and exponentials can look unrelated at first, but algebra and asymptotic approximations reveal their relative growth.

Maria
Now let’s switch from comparing functions to treating a data structure as a black box. A black box gives us a defined set of operations and their costs, but we don’t rely on—or even need to know—its internal implementation.

Corey
Here, the structure stores a sequence: items have an order, with a first item, a last item, and positions in between. That interface is different from its implementation. An array or a linked list could both implement a sequence, but the interface itself doesn’t specify either one.

Maria
The available operations are insert first, insert last, delete first, and delete last. Each takes constant time, and a delete operation returns the item it removed. Our job is to build higher-level operations using only those tools.

Corey
First, swap the ends. Delete the first item and the last item, saving both in temporary variables. Then insert the old last item at the front and the old first item at the back.

Maria
That takes four constant-time operations, so the total time is constant. And when you write an algorithm for a person to read, explain what the variables represent and what each step does. Pseudocode can help, but unclear code-like notation isn’t a substitute for a clear description.

Corey
The next operation, shift_left by k, moves the first k items to the end while keeping their order. For example, you can repeatedly delete the first item and insert it at the back, doing that k times. Each repetition takes constant time, so the total is order k.

Maria
You can also describe it recursively. If k is zero, there’s nothing to move. Otherwise, move the first item to the back, then solve the same problem for k minus one.

Corey
That recursive view is useful because each call handles a smaller instance and only does a constant amount of work. It’s often easier to reason about one step and then rely on the smaller call than to keep a long sequence of operations in your head.

Maria
The next problem asks us to combine the strengths of two familiar structures. A dynamic array supports constant-time indexing and amortized constant-time insertion or removal at the back, but operations at the front are inefficient because items may need to shift.

Corey
A linked list has the opposite trade-off in this discussion: it can support operations at both ends in constant time, but reaching an item by its position may take linear time because we have to follow pointers through the list.

Maria
The goal is a structure with worst-case constant-time indexing and amortized constant-time insertions and removals at both ends. Before discussing how to build it, let’s clarify amortized time.

Corey
An individual operation may sometimes be expensive. Amortized analysis asks what the total cost is across a sequence of operations. If n operations take total time at most proportional to n, then the average cost across that sequence is constant—even if a few operations took much longer than the others.

Maria
That’s different from average-case analysis, which averages over possible inputs and their likelihoods. Amortized analysis is about the costs of a sequence of operations on a data structure.

Corey
One approach is to extend the dynamic-array idea directly. Keep extra unused capacity on both sides of the stored sequence. Then insertions at either end can use that space without immediately rebuilding the array.

Maria
When the structure does need to resize, copying takes linear time. But if we resize only after a linear number of updates, we can spread that rebuilding cost across those updates. That’s the charging intuition behind amortized constant time.

Corey
Deletions create another issue: if we never shrink the array, it might retain a huge amount of unused space after many items have been removed. So we also want to resize down when the structure becomes sufficiently underused.

Maria
But shrinking at the wrong threshold can make the structure resize back and forth after just a few updates. To avoid that, leave a linear amount of spare capacity after resizing. Then a linear number of insertions or deletions is needed before another expensive rebuild is necessary.

Corey
That gives one design: a dynamic array with space reserved on both ends, plus resizing policies that keep rebuilding far enough apart. There’s also a way to use an ordinary dynamic array as a black box instead of implementing that whole design ourselves.

Maria
Divide the sequence into two portions, each stored in its own dynamic array. Store one portion in forward order and treat the other as reversed. Then operations at the two outside ends correspond to operations at the back of one array or the other.

Corey
You do need to keep track of where the portions are and translate sequence positions into the right array positions. That takes index arithmetic, but the indexing remains constant time.

Maria
There’s an important boundary case: one of the two arrays might become empty after repeated operations at one end. At that point, an operation at that end can’t be handled by its empty array.

Corey
So when one side becomes empty, rebuild the representation: take the remaining items, divide them between two arrays, and restore the invariant that both sides have room for operations. That rebuild is expensive, but it follows a linear number of updates, so the amortized analysis applies.

Maria
The final problem is about a singly linked list with 2n nodes. We want to reverse the last n nodes in place, without creating new list nodes or using a non-constant amount of extra storage.

Corey
Start by finding the nth node, which ends the first half. Since the list gives us a head pointer and each node’s next pointer, we can walk through the list to reach that node.

Maria
Then reverse the next pointers in the second half. The key is to keep track of the node we’re currently changing, the previous node, and the next node. Save the next node before changing the current pointer, or you could lose access to the rest of the list.

Corey
For each node in that second half, point its next field backward to the previous node. Then advance the previous and current references. Repeating that process reverses the links without changing the items or allocating new nodes.

Maria
Once the reversal is finished, reconnect the halves. Point the last node of the first half to the new head of the reversed portion, and make the new last node’s next pointer null.

Corey
That’s the whole strategy: find the midpoint, reverse the second half’s pointers, and clean up the endpoints. It takes linear time to walk through the list and reverses the nodes in place using only a constant number of temporary references.

Maria
And testing matters, too. The example checks whether the first half stays in order and the last half appears in reverse order. Running the provided tests—and then the code checker—helps catch mistakes in pointer updates and endpoint handling.

Corey
Across all four problems, the recurring habits are the same: use the interface you’re given, transform expressions into familiar forms, split a complex task into explicit steps, and account for the cost of every operation.

Maria
And explain your reasoning as well as your answer. When you can say what each step preserves, what it changes, and why the time bound follows, you’re doing more than solving one problem—you’re building a method you can reuse.

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