Informal Run-Time Analysis

Help Questions

AP Computer Science A › Informal Run-Time Analysis

Questions 1 - 10
1

A student counts how many pairs of different values appear in an int[] of size $n$.


public static int countDifferentPairs(int[] data) {

    int count = 0;

    for (int i = 0; i < data.length; i++) {

        for (int j = i + 1; j < data.length; j++) {

            if (data<u>i</u> != data<u>j</u>) {

                count++;

            }

        }

    }

    return count;

}

What is the run-time complexity of the algorithm in the code snippet?

$O(n)$

$O(\log n)$

$O(1)$

$O(n^2)$

Explanation

This question tests AP Computer Science A skills in informal run-time analysis, focusing on nested loops that examine pairs. Informal run-time analysis involves recognizing common algorithmic patterns and their associated complexities. The countDifferentPairs method uses nested loops where the outer loop runs n times and the inner loop runs approximately n/2 times on average, examining all unique pairs of elements. Choice B is correct because the total number of pairs examined is n(n-1)/2, which simplifies to O(n²) complexity. Choice A (O(n)) is incorrect because it fails to account for the nested structure - a single loop would only allow examining each element once, not all pairs. To help students: Draw diagrams showing which pairs are examined for small arrays. Explain that examining all pairs of n items inherently requires O(n²) operations.

2

A recursive method counts how many times a number can be halved before reaching 1, for input size $n$.


public static int halveCount(int n) {

    if (n <= 1) {

        return 0;

    } else {

        return 1 + halveCount(n / 2);

    }

}

What is the run-time complexity of the algorithm in the code snippet?

$O(1)$

$O(\log n)$

$O(n^2)$

$O(n)$

Explanation

This question tests AP Computer Science A skills in informal run-time analysis, focusing on recursive algorithms with logarithmic complexity. Informal run-time analysis of recursive methods requires examining how the problem size changes with each recursive call and counting the total number of calls. In the provided code, each recursive call divides n by 2, continuing until n reaches 1, which happens after approximately log₂(n) divisions. Choice C is correct because halving the input at each step creates a logarithmic relationship - doubling the input size adds only one more recursive call, characteristic of O(log n) complexity. Choice A (O(n)) is incorrect because it would require the recursion depth to be proportional to n, but here we're dividing by 2 each time, not subtracting 1. To help students: Trace through specific values like n=8 (3 calls) and n=16 (4 calls) to see the logarithmic pattern. Connect this to binary search and other divide-and-conquer algorithms that exhibit similar O(log n) behavior.

3

A student uses the recursive method below to compute Fibonacci numbers for input $n$. Which of the following best describes the algorithm's time complexity?


public static int fib(int n) {

    if (n <= 1) {

        return n;

    }

    return fib(n - 1) + fib(n - 2);

}

O(log n)

$O(2^n$)

O(n)

O(1)

Explanation

This question tests AP Computer Science A skills in informal run-time analysis, focusing on selection and iteration. Informal run-time analysis involves estimating an algorithm's efficiency by examining its structure, such as loops and conditionals, to determine its Big O complexity. This recursive Fibonacci implementation makes two recursive calls for each non-base case, creating a binary tree of calls where the number of nodes approximately doubles at each level, resulting in exponential growth. Choice C is correct because the recursion tree has approximately 2ⁿ nodes (more precisely, about 1.618ⁿ due to overlapping subproblems), making the time complexity O(2ⁿ). Choice A (O(n)) is incorrect because it would only apply to an iterative or memoized solution that computes each Fibonacci number once, not this naive recursive approach. To help students: Draw recursion trees for small values of n, highlight repeated calculations (like fib(2) being computed multiple times), and contrast with dynamic programming solutions to show how memoization reduces exponential to linear complexity.

4

A simple selection sort is used to sort $n$ product prices, regardless of current ordering.


public static void selectionSort(int[] prices) {

    for (int i = 0; i < prices.length - 1; i++) {

        int minIndex = i;

        for (int j = i + 1; j < prices.length; j++) {

            if (prices<u>j</u> < prices<u>minIndex</u>) {

                minIndex = j;

            }

        }

        int temp = prices<u>i</u>;

        prices<u>i</u> = prices<u>minIndex</u>;

        prices<u>minIndex</u> = temp;

    }

}

What is the run-time complexity of the algorithm in the code snippet?

$O(\log n)$

$O(n^2)$

$O(1)$

$O(n)$

Explanation

This question tests AP Computer Science A skills in informal run-time analysis, focusing on selection sort's nested loop structure. Informal run-time analysis involves recognizing standard sorting algorithms and their characteristic complexity patterns based on their implementation structure. In the provided selection sort code, the outer loop runs n-1 times, and for each iteration i, the inner loop searches through the remaining n-i elements to find the minimum, resulting in approximately n²/2 comparisons total. Choice C is correct because despite the decreasing inner loop iterations, the nested structure still yields O(n²) complexity, as the sum 1+2+...+(n-1) equals n(n-1)/2, which is quadratic. Choice B (O(log n)) is incorrect because logarithmic complexity requires dividing the problem size repeatedly, but selection sort examines every remaining element in each pass. To help students: Trace through small arrays to see how selection sort always makes the same number of comparisons regardless of initial ordering. Emphasize that both selection sort and bubble sort have O(n²) complexity due to their nested loop structures.

5

A recursive method counts down from $n$ by repeatedly halving, stopping at 1.


public static int countHalves(int n) {

    if (n <= 1) {

        return 1;

    } else {

        return 1 + countHalves(n / 2);

    }

}

Which of the following best describes the algorithm's time complexity?

$O(1)$

$O(n)$

$O(n^2)$

$O(\log n)$

Explanation

This question tests AP Computer Science A skills in informal run-time analysis, focusing on recursive algorithms with exponential reduction. Informal run-time analysis of recursive methods requires understanding how the problem size changes with each recursive call. The countHalves method repeatedly divides n by 2 until reaching the base case, making approximately log₂(n) recursive calls. Choice C is correct because halving the input at each step is the hallmark of logarithmic complexity - doubling n only adds one more recursive call. Choice A (O(n)) is incorrect because it would require the recursion depth to be proportional to n, but here we're dividing by 2, not subtracting 1. To help students: Trace the execution for powers of 2 (n=8, 16, 32) to see the pattern. Connect this to binary search and other divide-and-conquer algorithms.

6

A student uses the recursive Java method below to compute a value from an input $n$. Which of the following best describes the algorithm's time complexity?


public static int sumToN(int n) {

    if (n <= 0) {

        return 0;

    }

    return n + sumToN(n - 1);

}

```​

O(n)

$O(n^2$)

O(log n)

O(1)

Explanation

This question tests AP Computer Science A skills in informal run-time analysis, focusing on selection and iteration. Informal run-time analysis involves estimating an algorithm's efficiency by examining its structure, such as loops and conditionals, to determine its Big O complexity. The recursive method makes exactly n recursive calls (from n down to 0), with each call performing a constant amount of work (one addition and one recursive call). Choice A is correct because the recursion depth is n, and each level does O(1) work, resulting in O(n) total time complexity - essentially equivalent to a loop from 1 to n. Choice D (O(n²)) is incorrect because there's no nested iteration or multiple recursive calls per level that would create quadratic behavior. To help students: Draw recursion trees to visualize the call stack, relate recursive solutions to their iterative equivalents, and emphasize that single recursive calls typically maintain the same complexity as the recursion depth.

7

A game computes a score by summing all values in a $n \times n$ int matrix.


public static int sumGrid(int[][] grid) {

    int sum = 0;

    for (int r = 0; r < grid.length; r++) {

        for (int c = 0; c < grid<u>r</u>.length; c++) {

            if (grid<u>r</u><u>c</u> > 0) {

                sum += grid<u>r</u><u>c</u>;

            }

        }

    }

    return sum;

}

Identify the most significant factor affecting the run-time of this algorithm.

Two nested loops over $n$ rows and $n$ columns

The if-statement makes it constant time overall

Only the number of positive values matters, not $n$

Extra memory used by sum makes it $O(n)$ time

Explanation

This question tests AP Computer Science A skills in informal run-time analysis, focusing on identifying dominant factors in algorithm complexity. Informal run-time analysis requires recognizing which structural elements most significantly impact performance. The sumGrid method contains nested loops that iterate through all n² elements of the matrix, with the if-statement inside being a constant-time operation. Choice A is correct because the two nested loops over n rows and n columns create O(n²) complexity - every element must be visited regardless of its value. Choice B is incorrect because the if-statement doesn't reduce the number of elements examined; it only determines whether to add each value. To help students: Emphasize that conditional statements inside loops don't change the loop's iteration count. Practice identifying the primary loop structure as the dominant factor in complexity analysis.

8

A game computes total points from a $rows \times cols$ grid of tiles, where $rows=cols=n$.


public static int totalPoints(int[][] board) {

    int sum = 0;

    for (int r = 0; r < board.length; r++) {

        for (int c = 0; c < board<u>0</u>.length; c++) {

            if (board<u>r</u><u>c</u> > 0) {

                sum += board<u>r</u><u>c</u>;

            }

        }

    }

    return sum;

}

Which of the following best describes the algorithm's time complexity?

$O(n^2)$

$O(n)$

$O(n \log n)$

$O(1)$

Explanation

This question tests AP Computer Science A skills in informal run-time analysis, focusing on 2D array traversal with nested loops. Informal run-time analysis requires understanding how multiple dimensions affect complexity, particularly when processing grid-like data structures. In the provided code, the outer loop iterates through n rows, and the inner loop iterates through n columns (since rows=cols=n), resulting in n×n = n² total cell visits. Choice B is correct because visiting every cell in an n×n grid requires O(n²) operations, as each of the n² cells must be examined exactly once to compute the sum. Choice A (O(n)) is incorrect because it would only account for processing a single row or column, not the entire 2D grid, missing the multiplicative effect of the nested loops. To help students: Visualize small grids (like 3×3 or 4×4) and count the total cells to see the quadratic relationship. Explain that for square matrices, the complexity is based on the total number of elements, which is n².

9

A program performs a selection sort on an int[] of size $n$.


public static void selectionSort(int[] nums) {

    for (int i = 0; i < nums.length - 1; i++) {

        int minIndex = i;

        for (int j = i + 1; j < nums.length; j++) {

            if (nums<u>j</u> < nums<u>minIndex</u>) {

                minIndex = j;

            }

        }

        int temp = nums<u>i</u>;

        nums<u>i</u> = nums<u>minIndex</u>;

        nums<u>minIndex</u> = temp;

    }

}

What is the run-time complexity of the algorithm in the code snippet?

$O(1)$

$O(n^2)$

$O(\log n)$

$O(n)$

Explanation

This question tests AP Computer Science A skills in informal run-time analysis, focusing on selection sort implementation. Informal run-time analysis requires understanding how nested loops in sorting algorithms contribute to complexity. The selection sort uses two nested loops: the outer loop runs n-1 times to place each element, and the inner loop finds the minimum among remaining elements, performing approximately n²/2 comparisons total. Choice B is correct because the nested loop structure results in O(n²) complexity - for each position, we scan all remaining elements to find the minimum. Choice A (O(n)) is incorrect because finding the minimum of unsorted elements requires examining all of them, preventing linear complexity. To help students: Trace through the algorithm with a small array, counting comparisons. Compare selection sort with bubble sort to show both have O(n²) complexity despite different approaches.

10

A program checks whether any two values in an int[] of size $n$ add to a target.


public static boolean hasPairSum(int[] nums, int target) {

    for (int i = 0; i < nums.length; i++) {

        for (int j = i + 1; j < nums.length; j++) {

            if (nums<u>i</u> + nums<u>j</u> == target) {

                return true;

            }

        }

    }

    return false;

}

Which of the following best describes the algorithm's time complexity?

$O(1)$

$O(n)$

$O(n^2)$

$O(\log n)$

Explanation

This question tests AP Computer Science A skills in informal run-time analysis, focusing on algorithms that check all pairs. Informal run-time analysis requires recognizing that examining all pairs of elements has quadratic complexity. The hasPairSum method uses nested loops where each element is paired with every subsequent element, checking approximately n²/2 pairs in the worst case. Choice B is correct because despite the early return on success, the worst-case scenario (no valid pair) requires checking all possible pairs, resulting in O(n²) complexity. Choice A (O(n)) is incorrect because a single pass cannot check all possible pairs - you need nested iteration. To help students: Explain that early termination affects average case but not worst-case complexity. Use small examples to count the exact number of pairs checked.

Page 1 of 2