This exercise is intended as practice with a complex traversal of a 1D array. Explore Finding the minimum/maximum before trying this exercise.

Although it features material tested on the AP CS A FR section, this exercise is not intended to simulate an AP style free response question and should not be used as part of a practice test or for practicing timing.

The Java files below include skeleton code for the method and a JUnit 5 tester for the method. See Running JUnit 5 tests.

Runs.java
RunsWithConsecutiveTest.java

runLengthIncreasing method

/**
 * Returns true if and only if the length of each
 * run in arr is strictly longer than all previous runs
 */
public static boolean runLengthIncreasing(int[] arr)

runLengthIncreasing explanation

A run is defined as 2 or more consecutive elements with the same value.

Method runLengthIncreasing returns true if and only if the length of each run in its parameter arr is strictly longer than the longest of all previous runs, when arr is traversed from left to right.

Each element that is not part of a run is ignored.

Method runLengthIncreasing returns true if arr does not contain a run. An array with length less than 2 cannot contain a run.

runLengthIncreasing examples

int[] arr = {
    1, 2, 3,
    5, 5, 5,          // length 3
    4,
    3, 3, 3, 3, 3,    // length 5
    4,
    6, 6, 6, 6, 6, 6, // length 6
    9, 3};

System.out.println(Runs.runLengthIncreasing(arr)); // prints true


arr = new int[] {1, 2, 3}; // no run

System.out.println(Runs.runLengthIncreasing(arr)); // prints true


arr = new int[] {1, 2, 3, 4, 4, 4, 1, 2}; // only 1 run

System.out.println(Runs.runLengthIncreasing(arr)); // prints true


arr = new int[] {5, 5, 5, 5}; // only 1 run

System.out.println(Runs.runLengthIncreasing(arr)); // prints true


arr = new int[] {
    1, 2, 3, 5, 4, 3,
    6, 6, 6, 6,       // length 4
    4,
    9, 9, 9, 9, 9,    // length 5
    4,
    7, 7, 7, 7, 7, 7, // length 6
    9, 3};

System.out.println(Runs.runLengthIncreasing(arr)); // prints true


arr = new int[] {
    1, 2, 3,
    5, 5, 5, 5,
    4,
    5,
    4, 3,
    5, 5, 5, 5, 5,
    4,
    5, 5, 5, 5, 5, 5,
    9, 3};

System.out.println(Runs.runLengthIncreasing(arr)); // prints true


arr = new int[] {4, 3, 5, 3, 5, 3};

System.out.println(Runs.runLengthIncreasing(arr)); // prints true


arr = new int[] {
    1, 2, 3,
    5, 5, 5, 5, // length 4
    4,
    3, 3, 3,    // length 3 is not > 4
    4,
    5, 5, 5, 5, 5, 5,
    9, 3};

System.out.println(Runs.runLengthIncreasing(arr)); // prints false


arr = new int[] {
    1, 2, 3,
    5, 5, 5, 5, // length 4
    4,
    3, 3, 3, 3, // length 4 is not > 4
    4,
    5, 5, 5, 5, 5, 5,
    9, 3};

System.out.println(Runs.runLengthIncreasing(arr)); // prints false

Solution & comments

See the Run length increasing solution or review it with AP CS Tutor Brandon Horn.

Comment on Run length increasing exercise