Verityprep
Question Bank

AP® Computer Science A FRQ Practice: Free-Response Questions with Solutions

Work through AP Computer Science A free-response questions unit by unit, then check each answer against a worked solution.

Free · no sign-up Open questions need no account. Sign up or log in to open the rest.

Questions 291–300 of 329
  1. 291
  2. 292
  3. 293
  4. 294
  5. 295
  6. 296
  7. 297
  8. 298
  9. 299
  10. 300

Question 291

Free response Unit 4: Data Collections

A linguist is studying word usage in a corpus. Given an ArrayList<String> of the words that appear in a document (in order, with possible repetitions), the linguist wants the list of most common words in that document.

Write a static method mostFrequent that, given such a list, returns a new ArrayList<String> containing every word whose number of occurrences in words equals the maximum number of occurrences attained by any word. In the returned list:

  • each qualifying word appears exactly once, even if it occurs many times in words;
  • the qualifying words appear in the order of their first occurrence in words.

Two words are considered the same only if they are equal as strings (case-sensitive). The parameter words must not be modified. If words is empty, return an empty list.

Method Signature

public static ArrayList<String> mostFrequent(ArrayList<String> words)

Examples

Input words Returned list Explanation
["to","be","or","not","to","be"] ["to","be"] Both appear twice; "to" occurs first, then "be".
["red","blue","red","green","blue","red"] ["red"] Max count is 3 ("red"); "blue" has count 2.
["a","b","c","d"] ["a","b","c","d"] All words tie at count 1; order is preserved.
["Cat","cat","Cat"] ["Cat"] Case-sensitive: "Cat" has count 2, "cat" has count 1.
[] [] Empty input → empty output.
The answer and the full solution open in a window.

Question 292

Free response Unit 4: Data Collections

An image-processing routine applies a smoothing filter to a rectangular grid of integer pixel values. For each cell in the input grid, the smoothed grid contains the integer average (truncated toward zero, as with Java's int division) of that cell and its orthogonal neighbors — the cells directly above, below, to the left, and to the right, when they exist.

A corner cell therefore averages three values (itself and its two in-bounds orthogonal neighbors); an edge cell averages four; and an interior cell averages five. Diagonal neighbors are never included. The original grid must not be modified.

Write a static method gridSmooth that takes a rectangular 2-D array grid of non-negative integers (at least one row and one column; every row has the same length) and returns a new 2-D array of the same dimensions containing the smoothed values, as defined above.

Method Signature

public static int[][] gridSmooth(int[][] grid)

Example 1

Given the 3×4 grid on the left, the result is shown on the right. Each cell shows the full computation for reference.

Input gridReturned grid
{ { 4, 8, 12, 0 },
  { 2, 6, 3, 5 },
  { 10, 1, 7, 9 } }
{ { 4, 7, 5, 5 },
  { 5, 4, 6, 4 },
  { 4, 6, 5, 7 } }

For instance, the value at row 1, column 1 is \((6 + 8 + 2 + 3 + 1) / 5 = 20 / 5 = 4\) (itself, up, left, right, down — truncated). The value at row 0, column 0 is \((4 + 8 + 2) / 3 = 14 / 3 = 4\) (itself, right, down — truncated). The value at row 2, column 3 is \((9 + 5 + 7) / 3 = 21 / 3 = 7\).

Example 2

A 1×1 grid maps to itself: gridSmooth({{ 42 }}) returns {{ 42 }} (the sum is 42, divided by 1).

A 1×3 grid behaves as if every cell is on the top and bottom edge: gridSmooth({{ 3, 6, 9 }}) returns {{ 4, 6, 7 }}, since \((3+6)/2 = 4\), \((6+3+9)/3 = 6\), and \((9+6)/2 = 7\).

The answer and the full solution open in a window.

Question 293

Free response Unit 4: Data Collections

This question involves analyzing daily high temperatures recorded over a season. The partial class TempLog below stores the temperatures in a double array.

public class TempLog
{
    /** highs[k] is the recorded high temperature (in degrees Fahrenheit)
     * for day k, where 0 <= k < highs.length. highs is never null
     * and always contains at least one element. */
    private double[] highs;

    // Constructor not shown.

    /** Returns the number of days whose high temperature was
     * strictly greater than threshold, as described in part (a). */
    public int daysHotterThan(double threshold)
    {
        /* to be implemented in part (a) */
    }

    /** Returns the length of the longest run of consecutive days
     * whose high temperature was strictly greater than threshold,
     * as described in part (b). */
    public int longestHotStreak(double threshold)
    {
        /* to be implemented in part (b) */
    }
}

Part (a)

Write the daysHotterThan method. The method returns the number of entries in highs that are strictly greater than threshold.

For example, if highs contains {72.5, 80.0, 68.1, 95.4, 80.0, 81.2}, then:

CallReturned value
daysHotterThan(80.0)2 (only 95.4 and 81.2 are strictly greater)
daysHotterThan(100.0)0
daysHotterThan(0.0)6

Complete method daysHotterThan below.

/** Returns the number of days whose high temperature was
 * strictly greater than threshold, as described in part (a). */
public int daysHotterThan(double threshold)

Part (b)

Write the longestHotStreak method. The method returns the length of the longest run of consecutive days whose high temperature is strictly greater than threshold. If no day satisfies the condition, the method returns 0.

For example, if highs contains {60.0, 85.0, 90.0, 72.0, 95.0, 95.0, 95.0, 70.0}, then:

CallReturned value
longestHotStreak(80.0)3 (days at indices 4, 5, 6)
longestHotStreak(88.0)3
longestHotStreak(100.0)0

In writing longestHotStreak, you may assume daysHotterThan works as specified regardless of what you wrote in part (a). Complete method longestHotStreak below.

/** Returns the length of the longest run of consecutive days
 * whose high temperature was strictly greater than threshold,
 * as described in part (b). */
public int longestHotStreak(double threshold)
The answer and the full solution open in a window.

Question 294

Free response Unit 4: Data Collections
This question involves a movie streaming service that stores a list of movies and selects pairings for "double feature" slots — two movies that together fit…

Sign up now. It's free!

See the full question with its answer and worked solution.

Question 295

Free response Unit 4: Data Collections
A rectangular game grid of lights is represented by the partial class LightBoard below. Each entry of the 2D array is true if the light at that position is on…

Sign up now. It's free!

See the full question with its answer and worked solution.

Question 296

Free response Unit 4: Data Collections
A hardware store tracks how many units of a particular item are in stock at the end of each day. The class StockLog stores these daily counts in the array…

Sign up now. It's free!

See the full question with its answer and worked solution.

Question 297

Free response Unit 4: Data Collections

A retail system models each item for sale as a Product and uses a Store object to hold every product currently tracked by the store. The two classes are shown below; only the method totalValueOfLowStock in Store is left for you to complete. Everything else is already written.

public class Product
{
    private String name;
    private double price;
    private int quantity;

    public Product(String theName, double thePrice, int theQuantity)
    {
        name = theName;
        price = thePrice;
        quantity = theQuantity;
    }

    public String getName()      { return name; }
    public double getPrice()     { return price; }
    public int getQuantity()   { return quantity; }
}

public class Store
{
    /** Inventory of products currently tracked by this store. Never null. */
    private ArrayList<Product> inventory;

    public Store(ArrayList<Product> startingInventory)
    {
        inventory = startingInventory;
    }

    /** Returns the total dollar value of all products in inventory whose current
     *  quantity is strictly less than threshold. The dollar value of a single
     *  product is its price multiplied by its quantity. If no product has a
     *  quantity below threshold, the method returns 0.0.
     *  @param threshold the cutoff quantity; assumed to be non-negative
     *  @return the sum of price * quantity over all low-stock products
     */
    public double totalValueOfLowStock(int threshold) { /* to implement */ }
}

Write the method totalValueOfLowStock. The method must iterate over every product in inventory and accumulate the dollar value price * quantity for each product whose current quantity is strictly less than threshold.

Example

Suppose inventory holds three products:

{name:"widget", price:4.50, quantity:2}, {name:"gizmo", price:10.00, quantity:7}, {name:"bolt", price:0.25, quantity:3}.

A call to totalValueOfLowStock(5) selects the "widget" (quantity 2) and the "bolt" (quantity 3) because 7 is not less than 5. The returned value is \(4.50 \times 2 + 0.25 \times 3 = 9.75\).

public double totalValueOfLowStock(int threshold)
The answer and the full solution open in a window.

Question 298

Free response Unit 4: Data Collections

A topographic survey is stored in a class HeightMap, which uses a two-dimensional array to hold the elevation of each grid cell. Row 0 is the northernmost row and column 0 is the westernmost column. All rows have the same length. The grid is at least \(1 \times 1\).

public class HeightMap
{
    /** Elevation grid; heights[r][c] is the elevation of the cell at row r, column c.
     *  Guaranteed to be a rectangular, non-empty 2D array of integers. */
    private int[][] heights;

    public HeightMap(int[][] grid)
    {
        heights = grid;
    }

    /** Part: see below. */
    public boolean[][] peaks() { /* to implement */ }
}

Write the method peaks. The method returns a newly constructed boolean array of the same dimensions as heights. Entry [r][c] in the returned array is true if and only if the elevation at cell (r, c) is strictly greater than the elevation of every one of its orthogonal neighbors that exists in the grid. The orthogonal neighbors of (r, c) are the cells directly north, south, west, and east: (r-1, c), (r+1, c), (r, c-1), and (r, c+1). Neighbors outside the grid are simply ignored when making the comparison.

A corner cell has only two neighbors; an edge cell has only three neighbors; an interior cell has four. A cell with any neighbor at or above its own elevation is not a peak. A cell in a \(1 \times 1\) grid has no neighbors and is therefore a peak.

Example

Let heights be the grid

{ {1, 4, 2}, {3, 2, 5}, {1, 1, 2} }.

The call peaks() returns

{ {false, true, false}, {true, false, true}, {false, false, false} }.

Explanation: (0,1) = 4 beats its existing neighbors 1, 2, 2; (1,0) = 3 beats 1, 2, 1; (1,2) = 5 beats 2, 2, 2. Every other cell has at least one neighbor at least as tall as itself.

public boolean[][] peaks()

Open each "Show solution" accordion above to compare your response against the reference implementation and scoring notes.

const TOTAL = 42; const TOTAL_SECONDS = 3 * 60 * 60; let remaining = TOTAL_SECONDS; let timerId = null; let started = false; let submitted = false; function fmt(s) { let h = Math.floor(s / 3600); let m = Math.floor((s % 3600) / 60); let x = s % 60; function p(n) { return n < 10 ? "0" + n : "" + n; } return h + ":" + p(m) + ":" + p(x); } function tick() { if (remaining <= 0) { clearInterval(timerId); document.getElementById("timerEl").textContent = "0:00:00"; document.getElementById("timerEl").classList.add("danger"); return; } remaining--; const el = document.getElementById("timerEl"); el.textContent = fmt(remaining); if (remaining <= 600 && remaining > 300) el.classList.add("warn"); if (remaining <= 300) { el.classList.remove("warn"); el.classList.add("danger"); } } function mulberry32(a) { return function() { a |= 0; a = a + 0x6D2B79F5 | 0; let t = a; t = Math.imul(t ^ t >>> 15, t | 1); t ^= t + Math.imul(t ^ t >>> 7, t | 61); return ((t ^ t >>> 14) >>> 0) / 4294967296; }; } function shuffleQuestions() { const host = document.getElementById("mcqHost"); const qs = Array.from(host.querySelectorAll(".qb")); const rng = mulberry32(2026); for (let i = qs.length - 1; i > 0; i--) { const j = Math.floor(rng() * (i + 1)); if (j !== i) host.insertBefore(qs[i], qs[j]); } const kept = Array.from(host.querySelectorAll(".qb")); kept.forEach((q, idx) => { const n = q.querySelector(".qn"); if (n) n.textContent = "Question " + (idx + 1); }); buildDots(kept.length); } function buildDots(n) { const host = document.getElementById("navDots"); host.innerHTML = ""; for (let i = 0; i < n; i++) { const d = document.createElement("div"); d.className = "ndot"; d.textContent = i + 1; d.onclick = () => { const qs = document.querySelectorAll("#mcqHost .qb"); if (qs[i]) qs[i].scrollIntoView({ behavior: "smooth", block: "start" }); }; host.appendChild(d); } } function updateProgress() { const qs = document.querySelectorAll("#mcqHost .qb"); let answered = 0; const dots = document.querySelectorAll(".ndot"); qs.forEach((q, i) => { const chosen = q.querySelector(".op.sel"); if (chosen) { answered++; if (dots[i]) dots[i].classList.add("done"); } else { if (dots[i]) dots[i].classList.remove("done"); } }); document.getElementById("progFill").style.width = (100 * answered / qs.length) + "%"; document.getElementById("progLbl").textContent = answered + " / " + qs.length + " answered"; } function pick(el) { if (submitted) return; const qb = el.closest(".qb"); qb.querySelectorAll(".op").forEach(o => o.classList.remove("sel")); el.classList.add("sel"); updateProgress(); } function ap(c) { const p = 100 * c / TOTAL; if (p >= 70) return 5; if (p >= 55) return 4; if (p >= 40) return 3; if (p >= 25) return 2; return 1; } function submitMCQ() { if (submitted) return; submitted = true; let correct = 0; document.querySelectorAll("#mcqHost .qb").forEach(qb => { const answer = qb.getAttribute("data-answer"); const opts = qb.querySelectorAll(".op"); let chosen = null; opts.forEach(op => { if (op.classList.contains("sel")) chosen = op.getAttribute("data-q"); }); opts.forEach(op => { const k = op.getAttribute("data-q"); if (k === answer) op.classList.add("correct"); else if (k === chosen) op.classList.add("wrong"); }); const ex = qb.querySelector(".ex"); if (ex) ex.classList.add("show"); if (chosen === answer) correct++; }); document.getElementById("scoreBig").textContent = correct; document.getElementById("rawScore").textContent = correct + " / " + TOTAL; document.getElementById("pctScore").textContent = Math.round(100 * correct / TOTAL) + "%"; document.getElementById("apScore").textContent = ap(correct); document.getElementById("timeLeft").textContent = fmt(remaining); document.getElementById("scorePanel").classList.add("show"); document.getElementById("scorePanel").scrollIntoView({ behavior: "smooth", block: "start" }); } function startExam() { if (started) return; started = true; document.getElementById("coverPage").classList.add("hidden"); document.getElementById("examPage").classList.remove("hidden"); shuffleQuestions(); updateProgress(); timerId = setInterval(tick, 1000); }
The answer and the full solution open in a window.

Question 299

Free response Unit 4: Data Collections
A weather station records the rainfall, in millimetres, that fell during each day of an observation period. The class RainfallLog stores these daily…

Sign up now. It's free!

See the full question with its answer and worked solution.

Question 300

Free response Unit 4: Data Collections

A cinema management system models each scheduled showing as a Movie object and keeps every showing currently on the schedule inside a Theater object. The two classes are shown below; only the method averageRatingAtLeast in Theater is left for you to complete. Everything else is already written.

public class Movie
{
    private String title;
    private int lengthMinutes;
    private double rating;

    public Movie(String theTitle, int theLength, double theRating)
    {
        title = theTitle;
        lengthMinutes = theLength;
        rating = theRating;
    }

    public String getTitle()        { return title; }
    public int getLengthMinutes()   { return lengthMinutes; }
    public double getRating()      { return rating; }
}

public class Theater
{
    /** All movies currently scheduled at this theater. Never null. */
    private ArrayList<Movie> showings;

    public Theater(ArrayList<Movie> startingShowings)
    {
        showings = startingShowings;
    }

    /** Returns the average rating of every movie in showings whose length is at least
     *  minLength minutes. If no movie meets the length requirement, returns 0.0.
     *  @param minLength the inclusive lower bound on length, in minutes; assumed non-negative
     *  @return the mean rating of qualifying movies, or 0.0 when no movie qualifies
     */
    public double averageRatingAtLeast(int minLength) { /* to implement */ }
}

Write the method averageRatingAtLeast. The method must iterate over every Movie in showings, accumulate the rating of each movie whose length in minutes is at least minLength, and return the mean of those ratings as a double. If no movie meets the length requirement, the method returns 0.0.

Example

Suppose showings holds four movies:

{title:"Alpha", lengthMinutes:90, rating:4.0}, {title:"Bravo", lengthMinutes:135, rating:4.5}, {title:"Charlie", lengthMinutes:75, rating:3.0}, {title:"Delta", lengthMinutes:120, rating:3.5}.

A call to averageRatingAtLeast(120) selects the movies whose length is at least 120 minutes — Bravo and Delta — and returns the mean of their ratings: (4.5 + 3.5) / 2 = 4.0.

A call to averageRatingAtLeast(200) finds no qualifying movie and therefore returns 0.0.

public double averageRatingAtLeast(int minLength)
The answer and the full solution open in a window.
Question 291 of 329
Page 30 of 33