Data Structures and Algorithms

A program with O(n²) time complexity takes 0.5 seconds for 1,000 data items. About how long will it take for 4,000 items?

  1. A2 seconds
  2. B8 seconds
  3. C32 seconds
Show answer and explanation

Answer: B. 8 seconds

With O(n²), the running time is proportional to the square of the data size, so four times the data takes 4² = 16 times as long: 0.5 s × 16 = 8 s. 2 seconds would be the result for O(n), which is proportional to the data size, and 32 seconds for O(n³), which grows with the cube (4³ = 64 times). In practice it can be even slower, for example once the data no longer fits in the cache.

  • A. That would be the case for O(n), which grows in proportion to the data size; with O(n²) the growth is squared.
  • B. Correct. Four times the data takes 4² = 16 times as long: 0.5 × 16 = 8 seconds.
  • C. This is the value for O(n³), which grows 4³ = 64 times.
Practice this topic Back to topic

Related calculators

Books on Data Structures and Algorithms Ad

As an Amazon Associate I earn from qualifying purchases.

More Data Structures and Algorithms questions

  1. A linear search compares the elements of an array of 100 distinct values one by one from the front to find a target. If the target is always in the array and is equally likely to be at any position, what is the average number of comparisons?
  2. Compared with an array, which is a correct description of a linked list (a list in which each element holds a pointer to the next element)?
  3. On an empty stack, the operations push 1, push 2, pop, push 3, push 4, pop, pop are performed in this order. In what order are the values removed by pop?
  4. Elements A, B and C are added to an empty queue in this order. Then one element is removed, D is added and one is removed, and E is added and one is removed. In what order are the elements removed?
  5. The expression “3 4 + 2 * 5 −” in reverse Polish notation (postfix notation) is evaluated by pushing each number onto a stack and, for each operator, popping two values, computing the result and pushing it back. What is the result? The left operand of an operator is the value that was pushed earlier.