Data Structures and Algorithms

For an array of n elements, what is the time complexity of comparing every pair of distinct elements exactly once (a double loop that compares element i with every element after it, advancing i one step at a time)?

  1. AO(n)
  2. BO(n log n)
  3. CO(n²)
Show answer and explanation

Answer: C. O(n²)

The number of pairs compared is (n−1) + (n−2) + … + 1 = n(n−1)/2: 45 for n = 10 and 499,500 for n = 1000. Big-O notation only describes how the count grows as n gets large, so the factor of 1/2 and the lower-order term are dropped, giving O(n²). Doubling n roughly quadruples the count. O(n) is the complexity of looking at each element once, and O(n log n) is that of algorithms such as merge sort that repeatedly split the data in half.

  • A. Looking at each element once would be O(n), but here each element is compared with all of the remaining ones.
  • B. This is the complexity of algorithms such as merge sort that repeatedly halve the data, which is smaller than comparing all pairs.
  • C. Correct. There are n(n−1)/2 comparisons, which grows in proportion to n².
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 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?
  2. 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?
  3. 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)?
  4. 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?
  5. 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?