1. Home
  2. Explore
  3. Computer Science
  4. Algorithms Problem-Solving

Study methods

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

Algorithms Problem-Solving

Algorithm Design, Asymptotic Analysis, and Sequence Data Structures

Comparing Asymptotic Growth

When several functions describe running times or resource requirements, they can be ordered by how quickly they grow as the input size nnn becomes large. The comparison focuses on asymptotic behavior: constant factors and lower-order terms usually do not affect the final ordering.

Common growth relationships

  • For any positive constants aaa and bbb, logarithmic powers grow more slowly than positive polynomial powers:

    (log⁡n)a=o(nb).(\log n)^a = o(n^b).(logn)a=o(nb).
  • A polynomial grows more slowly than an exponential function with base greater than 111.

  • An exponential function such as 2n2^n2n grows more slowly than nnn^nnn.

  • Multiplying or dividing by a polynomial factor can change the asymptotic ordering of functions that otherwise have the same exponential factor. For example:

    2nn=o(2n).\frac{2^n}{\sqrt{n}} = o(2^n).n​2n​=o(2n).

Here, f(n)=o(g(n))f(n)=o(g(n))f(n)=o(g(n)) means that fff grows strictly more slowly than ggg: the ratio f(n)/g(n)f(n)/g(n)f(n)/g(n) approaches 000 as nnn grows. By contrast, f(n)=Θ(g(n))f(n)=\Theta(g(n))f(n)=Θ(g(n)) means that the functions grow at the same asymptotic rate up to constant factors.

Grouping asymptotically equivalent functions

A function-ordering problem may contain two or more functions that are asymptotically equivalent. Such functions should be grouped together rather than given an arbitrary strict order.

For example, the functions n\sqrt{n}n​, nnn, and n+nn+\sqrt{n}n+n​ are ordered as follows:

  • n\sqrt{n}n​ grows more slowly than nnn.

  • n+n=Θ(n)n+\sqrt{n}=\Theta(n)n+n​=Θ(n), because the added n\sqrt{n}n​ term is lower order.

  • Thus, n\sqrt{n}n​ comes first, while nnn and n+nn+\sqrt{n}n+n​ belong in the same asymptotic group.

Using ratios and limits

A useful way to compare two functions fff and ggg is to examine their ratio as nnn approaches infinity:

  • If f(n)/g(n)→0f(n)/g(n)\to 0f(n)/g(n)→0, then fff grows more slowly than ggg.

  • If f(n)/g(n)→∞f(n)/g(n)\to\inftyf(n)/g(n)→∞, then fff grows more quickly than ggg.

  • If the ratio approaches a positive finite constant, the functions have the same asymptotic growth rate.

Taking the logarithm of a ratio can make a difficult limit easier to evaluate, especially when the functions contain products, powers, or factorials.


Factorials and Binomial Coefficients

The binomial coefficient

The binomial coefficient (nk)\binom{n}{k}(kn​) counts the number of ways to choose kkk items from a collection of nnn items, without regard to order. Its formula is

(nk)=n!k!(n−k)!.\binom{n}{k}=\frac{n!}{k!(n-k)!}.(kn​)=k!(n−k)!n!​.

This formula can be understood by starting with the n!n!n! possible orderings of all nnn items. The order of the selected kkk items and the unselected n−kn-kn−k items does not matter, so the total is divided by k!k!k! and (n−k)!(n-k)!(n−k)!.

A fixed, small choice such as k=3k=3k=3 gives a polynomial:

(n3)=n(n−1)(n−2)6=Θ(n3).\binom{n}{3} =\frac{n(n-1)(n-2)}{6} =\Theta(n^3).(3n​)=6n(n−1)(n−2)​=Θ(n3).

The leading term determines the asymptotic growth because the lower-degree terms and constant denominator do not change the order.

Stirling’s approximation

For large nnn, a factorial can be approximated using Stirling’s formula:

n!∼2πn(ne)n.n! \sim \sqrt{2\pi n}\left(\frac{n}{e}\right)^n.n!∼2πn​(en​)n.

The symbol ∼\sim∼ indicates that the ratio of the two sides approaches 111 as nnn grows. In particular, taking logarithms shows that

log⁡(n!)=Θ(nlog⁡n).\log(n!)=\Theta(n\log n).log(n!)=Θ(nlogn).

This is a useful transformation: a factorial, which is difficult to compare directly with other functions, has logarithm of order nlog⁡nn\log nnlogn.

The central binomial coefficient

For an even number of items, the number of ways to choose half of them is

(nn/2)=n!((n/2)!)2.\binom{n}{n/2} =\frac{n!}{\left((n/2)!\right)^2}.(n/2n​)=((n/2)!)2n!​.

Applying Stirling’s approximation to the numerator and denominator and simplifying gives

(nn/2)=Θ(2nn).\binom{n}{n/2}=\Theta\left(\frac{2^n}{\sqrt{n}}\right).(n/2n​)=Θ(n​2n​).

The exponential factor 2n2^n2n dominates the broad growth rate, but the polynomial divisor n\sqrt{n}n​ still matters when comparing it with 2n2^n2n:

2nn=o(2n).\frac{2^n}{\sqrt{n}}=o(2^n).n​2n​=o(2n).

Thus, a polynomial factor can distinguish two functions even when they share the same exponential component.


Abstract Interfaces and Black-Box Data Structures

An algorithm can be designed around a data structure’s interface without knowing how the structure is implemented. This is a form of abstraction: an algorithm relies on the operations the interface promises, rather than on internal details.

A sequence interface stores items in an extrinsic order. The order comes from their positions in the sequence, not from the values of the items. A sequence therefore has a first item, a second item, and a last item.

Different implementations can support the same interface:

  • An array stores items in contiguous memory.

  • A linked list stores items in nodes connected by pointers.

If a problem supplies a sequence structure with constant-time operations for inserting and deleting at both ends, an algorithm can use those operations without assuming the structure is an array or a linked list. A delete operation that returns the deleted item is especially useful because it lets the algorithm transfer items from one end to the other.


Building Operations from Sequence Primitives

Swapping the first and last items

Suppose a sequence supports constant-time insertion and deletion at both ends, and deleting an item returns its value. To swap the endpoints:

  1. Delete the first item and save it as x1x_1x1​.

  2. Delete the last item and save it as x2x_2x2​.

  3. Insert x2x_2x2​ at the front.

  4. Insert x1x_1x1​ at the back.

The first and last values exchange positions, while the middle of the sequence remains unchanged. The algorithm uses four constant-time operations, so its running time is Θ(1)\Theta(1)Θ(1). If the sequence has fewer than two items, the operation can simply do nothing.

Shifting the first kkk items to the back

A left shift by kkk positions moves the first kkk items to the end in their original order. After the shift, the original (k+1)(k+1)(k+1)-st item becomes first, and the original kkk-th item becomes last.

An iterative method repeats the following operation kkk times:

  1. Delete the first item.

  2. Insert it at the back.

This takes Θ(k)\Theta(k)Θ(k) time because each iteration uses a constant number of constant-time operations.

A recursive version uses the same idea:

  • Base case: If k=0k=0k=0, no change is needed.

  • Recursive step: Move the first item to the back, then shift the first k−1k-1k−1 items.

The recursion reduces the problem size by one each time. Its correctness follows by induction: the base case performs the requested shift for k=0k=0k=0, and if the recursive call correctly shifts k−1k-1k−1 items, moving one item first and then performing that call correctly shifts kkk items. The running time is Θ(k)\Theta(k)Θ(k), with Θ(k)\Theta(k)Θ(k) recursive calls.

Recursive descriptions can make an algorithm easier to reason about because each step handles a constant amount of work and delegates a smaller instance of the same problem.


Dynamic Arrays and Amortized Analysis

Why dynamic arrays are efficient at one end

A dynamic array keeps items in a contiguous block of memory and can provide worst-case constant-time indexing. It usually reserves extra capacity beyond the number of stored items, allowing items to be appended without immediately allocating a larger block.

When capacity is exhausted, the array must be rebuilt in a larger block and its items copied over. That particular insertion may take linear time. However, if capacity grows geometrically, such expensive rebuilds are separated by many inexpensive insertions. Across a long sequence of operations, the total time for appending is linear in the number of operations, so appending is amortized constant time.

What amortized time means

An operation has amortized cost O(1)O(1)O(1) when a sequence of mmm such operations takes O(m)O(m)O(m) total time, even if individual operations sometimes take much longer.

For example, a dynamic-array append may occasionally require copying many items. Amortized analysis accounts for the cost across a sequence of appends rather than requiring every single append to be constant time.

This differs from average-case analysis:

  • Amortized analysis concerns the total cost of a sequence of operations on a data structure, regardless of which particular operation is expensive.

  • Average-case analysis averages over a distribution of possible inputs.

A charging argument explains why dynamic-array operations are amortized constant time: the frequent cheap operations can be viewed as paying in advance for the occasional expensive rebuild. Geometric growth ensures that enough cheap operations occur between rebuilds.

Why shrinking matters

If items are removed but the array never shrinks, a program can retain a large amount of unused memory after its contents become small. A dynamic array may therefore rebuild into a smaller block once its occupancy falls sufficiently.

Shrinking needs a carefully chosen threshold and target capacity. If the array shrinks immediately after a small decrease and then grows immediately after a small increase, it can repeatedly rebuild. Leaving extra capacity after shrinking creates a buffer of operations before the next rebuild. This helps preserve amortized efficiency while keeping storage proportional to the number of items.


Supporting Operations at Both Ends

A standard dynamic array is efficient for operations at its back, but inserting or deleting at its front usually requires shifting many items. Two approaches can extend the dynamic-array idea to both ends.

One array with space at both ends

A single array can reserve unused space before the first item as well as after the last item. Items can then be added at either end while there is free capacity on that side.

When the free space runs out, the array can be rebuilt and the items repositioned so that there is again a linear amount of spare capacity on both ends. The rebuilding step may be linear, but it follows a linear number of endpoint operations, so its cost can be amortized across those operations.

The structure should also shrink when it holds far fewer items than its capacity. As with an ordinary dynamic array, shrinking should leave enough spare capacity to avoid repeated rebuilds.

Two dynamic arrays

Another approach uses two dynamic arrays:

  • One array stores a portion of the sequence in forward order.

  • The other stores the remaining portion in reverse order.

The two arrays together represent the whole sequence. Their orientations allow one end of each array to act as an endpoint of the overall sequence, so insertions and deletions at either end can use the efficient end operations of a dynamic array.

Indexing requires translating a sequence position into an array position, accounting for which half contains the item and whether that half is stored in reverse. The arithmetic adds implementation detail but does not change the asymptotic cost of indexing.

If one of the two arrays becomes empty, the representation must be rebalanced. The remaining items can be divided between two new arrays, restoring the invariant that both portions are represented. Such a rebuild takes linear time, but it is triggered only after a linear number of endpoint operations have shifted items into one side. Its cost can therefore be amortized across those operations.

Both approaches extend the dynamic-array strategy to obtain worst-case constant-time indexing and amortized constant-time insertion and deletion at both ends, while keeping storage proportional to the number of stored items.


Reversing the Second Half of a Singly Linked List

A singly linked list consists of nodes, each containing an item and a pointer to the next node. The list maintains a pointer to its head and a size. Unlike an array, a linked list does not provide constant-time access to an arbitrary indexed item; reaching a node requires following pointers from the head.

Consider a list with 2n2n2n nodes. The goal is to reverse the order of nodes n+1n+1n+1 through 2n2n2n in place, leaving the first nnn nodes in their original order. If no new nodes or nonconstant-size auxiliary structures are allowed, the algorithm can use only a constant number of temporary pointers.

Strategy

  1. Find the midpoint. Traverse from the head to node nnn. This node remains the tail of the unchanged first half.

  2. Reverse the second half. Starting at node n+1n+1n+1, reverse each node’s next pointer.

  3. Reconnect the list. Set the midpoint’s next pointer to the new head of the reversed half. The original node n+1n+1n+1 becomes the final node and must point to nothing.

During pointer reversal, three references are essential:

  • The current node being processed.

  • The previous node, which becomes the current node’s new successor.

  • The next node in the original list, saved before changing the current node’s pointer.

Saving the next node before overwriting a pointer prevents the rest of the list from becoming unreachable. After all nodes in the second half have been processed, the original successor order has been reversed, and reconnecting the midpoint restores one complete list.

Finding the midpoint and reversing the second half each take linear time, so the total running time is Θ(n)\Theta(n)Θ(n). Only a constant number of pointers are stored, giving Θ(1)\Theta(1)Θ(1) extra space. The nodes themselves are reused rather than copied or newly allocated.


General Problem-Solving Principles

  • Use only the operations guaranteed by an interface. An algorithm designed for an abstract sequence should not depend on whether the sequence is implemented as an array or a linked list.

  • Make the representation explicit when needed. For pointer-based structures, track which node each pointer refers to and what links must change.

  • Save information before modifying pointers. In a linked list, the next node should be saved before the current node’s link is overwritten.

  • Use base cases and smaller instances in recursive algorithms. A clear base case prevents infinite recursion, while a smaller recursive instance supports an inductive correctness argument.

  • Analyze total work for amortized operations. An occasional linear-time rebuild can coexist with amortized constant-time operations if enough cheap operations occur between rebuilds.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent