Data structures and algorithms

Exercise solutions: Complexity, part A

Here are suggested solutions to the exercises about complexity, part A.

Core exercises (part A)

A1. Asymptotic time complexity

  1. Linear, O(n): do a linear search over the array.
  2. Logarithmic, O(log n): use binary search.
  3. Constant, O(1): increase the length of the array by one and add the element to the end.
  4. Linear, O(n): in the worst case, the element needs to be inserted at the front, requiring all other elements to move one step further.

A2. Asymptotic complexities of code fragments

A3. Complexity of sorting algorithms

A4. Checking for duplicates

In a sorted array, duplicate elements appear in right after one another. So to check for duplicates, it suffices for 0 ≤ i < n–1, to check if a[i] equals a[i+1].

A5. Print elements from two sorted arrays

Here is a rough sketch of the program:

  1. Call the arrays a and b.
  2. Initialize indices i for a and j for b.
  3. Loop until one of the indices i and j reaches the end of its array:
    • if a[i] is equal to b[j], then print it and increase both i and j,
    • otherwise, increase the index of the array with the lower element.

We leave the details of actually turning it into a working program as an exercise for you! Regarding the two questions:

A6. Deletion from a dynamic array

See the lecture slides for Stacks & Queues.

A7. Asymptotic complexities of code fragments