Learn AP Comp Sci

Problem of the Day

Wednesday, April 22, 2026


Problem:

Consider the following code which uses a String variable value.

for (int i = 0; i < value.length() - 1; i++)
for (int j = i + 1; j < value.length(); j++)
System.out.println(value.substring(i, i+1) + value.substring(j, j+1));

What is the Big-O performance of this code?

  1. O(n), linear
  2. O(n log n), log linear
  3. O(n2 - 2n + 1, quadratic
  4. O(n2), quadratic

Show solution:

The correct answer is d. If the length of value is n, each of the nested loops runs n - 1 times. As a result, the code executes (n - 1)(n - 1) times, or n2 - 2n + 1 times. Big-O reduces this calculation to the single term with the highest value, which is the n2 term. Thus, the Big-O performance is O(n2).