Home

Tutoring

Subjects

Live Classes

Study Coach

Essay Review

On-Demand Courses

Colleges

Games


Sign up

Log in

Opening subject page...

Loading your content

Practice

  • All Subjects
  • Algebra Flashcards
  • SAT Math Practice Tests
  • Math Question of the Day
  • Live Classes
  • On-Demand Courses

Varsity Tutors

  • Find a Tutor
  • Test Prep
  • Online Classes
  • K-12 Learning
  • College Search
  • VarsityTutors.com

© 2026 Varsity Tutors. All rights reserved.

← Back to quizzes

AP Computer Science Principles Quiz

AP Computer Science Principles Quiz: Developing Procedures

Practice Developing Procedures in AP Computer Science Principles with focused quiz questions that help you check what you know, review explanations, and build confidence with test-style prompts.

Question 1 / 16

0 of 16 answered

Based on the scenario, a student writes a procedure to find the maximum value in a non-empty list of integers. Input: list nums (length 1 to 50,000). Output: the largest integer in the list. Constraint: must work for negative numbers.

PROCEDURE maxValue(nums)
  max ← 0
  FOR EACH n IN nums
    IF n > max
      max ← n
    ENDIF
  ENDFOR
  RETURN max
ENDPROCEDURE

Which step is necessary to ensure the procedure works correctly for all valid inputs?

Select an answer to continue

What this quiz covers

This quiz focuses on Developing Procedures, giving you a quick way to practice the rules, question types, and explanations that matter most for AP Computer Science Principles.

How to use this quiz

Try each quiz question before looking at the correct answer. Use the explanations to review missed ideas, then come back to similar questions until the pattern feels familiar.

All questions

Question 1

Based on the scenario, a student writes a procedure to find the maximum value in a non-empty list of integers. Input: list nums (length 1 to 50,000). Output: the largest integer in the list. Constraint: must work for negative numbers.

PROCEDURE maxValue(nums)
  max ← 0
  FOR EACH n IN nums
    IF n > max
      max ← n
    ENDIF
  ENDFOR
  RETURN max
ENDPROCEDURE

Which step is necessary to ensure the procedure works correctly for all valid inputs?

  1. Initialize max to the first element of nums before the loop. (correct answer)
  2. Sort nums and return the first element to get the maximum quickly.
  3. Change the comparison to IF n < max so smaller values update max.
  4. Add a second loop to confirm that max appears at least twice.

Explanation: This question tests AP Computer Science Principles skills in developing procedures, specifically focusing on proper initialization for finding extrema. Developing procedures involves choosing appropriate initial values that work for all possible inputs, including edge cases like all-negative lists. In this scenario, initializing max to 0 fails when all numbers in the list are negative, as no value would ever be greater than 0. Choice A is correct because initializing max to the first element ensures the procedure works for any non-empty list, including lists with all negative numbers. Choice C is incorrect because changing the comparison to find smaller values would find the minimum, not the maximum, demonstrating a fundamental misunderstanding of the algorithm's purpose. To help students: Emphasize the importance of choosing neutral initial values or using the first element for extrema problems. Practice tracing through code with various inputs including all-negative, all-positive, and mixed lists.

Question 2

Based on the scenario, a student is optimizing a procedure that checks whether a username is already taken. Input: sorted list takenNames (strings, ascending) and string query. Output: Boolean indicating whether query appears in the list. Constraints: list length up to 200,000; list is already sorted; AP-style pseudocode.

A student currently uses:

PROCEDURE IsTaken(takenNames, query)
  FOR EACH name IN takenNames
    IF name = query
      RETURN TRUE
  RETURN FALSE

How can the procedure be optimized for better performance?

  1. Use binary search on the sorted list to reduce the number of comparisons. (correct answer)
  2. Reverse the list first, then scan from the beginning for the query.
  3. Sort the list again each time the procedure is called to ensure correctness.
  4. Check only the first and last elements; if neither matches, return FALSE.

Explanation: This question tests AP Computer Science Principles skills in developing procedures, specifically focusing on algorithm optimization for searching in sorted data. The current implementation uses linear search, checking every element sequentially, which has O(n) time complexity and is inefficient for large sorted lists of up to 200,000 elements. Since the list is already sorted in ascending order, binary search can dramatically improve performance by repeatedly dividing the search space in half. Choice A is correct because using binary search on the sorted list would reduce the number of comparisons from potentially 200,000 to at most log₂(200,000) ≈ 18, providing O(log n) time complexity. Choice D is incorrect because checking only first and last elements would miss all usernames in between, producing incorrect results. To help students: Teach the advantages of binary search for sorted data and how to recognize when linear search can be replaced with more efficient algorithms. Practice implementing and comparing different search algorithms to understand their trade-offs and appropriate use cases.

Question 3

Based on the scenario, a messaging app needs to count how many messages contain a blocked word. Input: a list messages of strings (up to 20,000) and a string blocked. Output: an integer count of messages where blocked appears as a substring, case-insensitive. Constraint: avoid unnecessary repeated work inside loops.

Current approach:

PROCEDURE countBlocked(messages, blocked)
  count ← 0
  FOR EACH msg IN messages
    IF CONTAINS(LOWER(msg), LOWER(blocked))
      count ← count + 1
    ENDIF
  ENDFOR
  RETURN count
ENDPROCEDURE

How can the procedure be optimized for better performance without changing its output?

  1. Compute lowerBlocked ← LOWER(blocked) once before the loop and reuse it in each comparison. (correct answer)
  2. Sort messages alphabetically so blocked words are easier to detect.
  3. Replace the loop with recursion that checks the first message only.
  4. Change the condition to CONTAINS(msg, blocked) to avoid lowercasing.

Explanation: This question tests AP Computer Science Principles skills in developing procedures, specifically focusing on optimization and avoiding redundant computations. Developing procedures involves identifying operations that can be moved outside loops to improve efficiency without changing functionality. In this scenario, the procedure converts 'blocked' to lowercase in every iteration, which is inefficient for large message lists. Choice A is correct because it computes LOWER(blocked) once before the loop and reuses this value, reducing redundant operations from O(n) to O(1) for this conversion. Choice D is incorrect because removing the lowercase conversion would change the functionality, making the search case-sensitive and producing different results. To help students: Teach the concept of loop invariants and moving constant computations outside loops. Practice identifying redundant operations within loops and understanding when optimizations preserve correctness.

Question 4

Based on the scenario, a messaging app must remove blocked users from a list. Input: list usernames (strings) and list blocked (strings). Output: a new list containing only usernames not in blocked, preserving original order. Constraints: nnn up to 30,000; blocked up to 5,000; do not modify usernames; AP-style pseudocode.

A student writes:

PROCEDURE FilterBlocked(usernames, blocked)
  allowed <- []
  FOR EACH name IN usernames
    IF NOT (name IN blocked)
      APPEND(allowed, name)
  RETURN allowed

What is the expected output of the procedure given the input usernames = ["ava","li","sam","li"] and blocked = ["li"]?

  1. ["ava", "sam"] (correct answer)
  2. ["ava", "li", "sam", "li"]
  3. ["li", "li"]
  4. ["sam", "ava"]

Explanation: This question tests AP Computer Science Principles skills in developing procedures, specifically focusing on list filtering and understanding how the IN operator works with lists. The procedure filters out usernames that appear in the blocked list, preserving the order of allowed users. Given usernames = ["ava","li","sam","li"] and blocked = ["li"], the procedure checks each username: "ava" is not in blocked (added), "li" is in blocked (skipped), "sam" is not in blocked (added), and the second "li" is also in blocked (skipped). Choice A is correct because the output would be ["ava", "sam"], containing only the usernames not found in the blocked list, in their original order. Choice B is incorrect because it includes "li" which should be filtered out, and Choice C is incorrect because it shows the blocked users instead of the allowed ones. To help students: Practice tracing through filtering algorithms step by step, and emphasize the importance of understanding what NOT (name IN blocked) means. Teach students to verify their understanding by working through small examples manually before coding.

Question 5

Based on the scenario, an app uses a simple weather API helper procedure GetWeather(city) that returns either a record {tempF, condition} or the value NULL if the city is not found. Input: string city. Output: a formatted string like "72F Clear" or "City not found". Constraints: do not crash on NULL; AP-style pseudocode only.

A student writes:

PROCEDURE WeatherLine(city)
  w <- GetWeather(city)
  RETURN w.tempF + "F " + w.condition

Which part of the procedure handles errors effectively?

  1. Add a check IF w = NULL THEN RETURN "City not found" before accessing fields. (correct answer)
  2. Call GetWeather(city) twice to confirm the API result is consistent.
  3. Return "City not found" for every city to avoid runtime errors.
  4. Change the return to RETURN w so the caller can format the record.

Explanation: This question tests AP Computer Science Principles skills in developing procedures, specifically focusing on error handling and null value management. The procedure needs to format weather data from an API that might return NULL for unknown cities, but the student's code doesn't handle this case and would crash when trying to access fields of a NULL value. The current code immediately tries to access w.tempF and w.condition without checking if w is NULL, which would cause a runtime error. Choice A is correct because adding a check IF w = NULL THEN RETURN "City not found" before accessing fields would prevent the crash and provide appropriate error handling. Choice C is incorrect because returning "City not found" for every city would make the procedure useless and wouldn't actually use the weather data. To help students: Teach defensive programming practices and the importance of checking for null/invalid values before using them. Practice identifying potential runtime errors and implementing appropriate error handling strategies, especially when working with external APIs or user input.

Question 6

Based on the scenario, a school app must display the top 10 highest quiz scores from a list of integers. Input: an array scores of length nnn (may include duplicates). Output: an array of up to 10 integers sorted in descending order. Constraints: 1≤n≤50,0001 \le n \le 50{,}0001≤n≤50,000; scores are 0–100; avoid non-standard libraries; use AP-style pseudocode. A student proposes:

PROCEDURE TopTen(scores)
  SORT(scores)          // sorts ascending
  result <- []
  FOR i <- LENGTH(scores) - 1 TO MAX(LENGTH(scores) - 10, 0) STEP -1
    APPEND(result, scores[i])
  RETURN result

What is the most efficient way to implement the procedure described while still producing the correct output under the constraints?

  1. Use nested loops to swap elements until the list is fully sorted, then take the last 10 items.
  2. Sort the list once using a built-in SORT, then iterate from the end to collect up to 10 values. (correct answer)
  3. Convert scores to a string, sort characters, and then parse the last 10 characters as numbers.
  4. Scan for the maximum 10 times without removing used values, appending the same max repeatedly.

Explanation: This question tests AP Computer Science Principles skills in developing procedures, specifically focusing on algorithm efficiency and correct implementation for finding top values. The task requires creating a procedure that returns the top 10 highest quiz scores from a potentially large array, which involves sorting and selecting elements efficiently. The student's proposed solution sorts the entire array in ascending order using SORT(), then iterates backwards from the end to collect up to 10 values, which correctly produces the top 10 scores in descending order. Choice B is correct because it accurately describes the student's approach: sort the list once using a built-in SORT function, then iterate from the end to collect up to 10 values, which is both efficient and correct. Choice A is incorrect because nested loops for sorting would be much less efficient than using a built-in sort function, especially for arrays up to 50,000 elements. To help students: Emphasize the importance of using built-in functions when available for efficiency, and practice tracing through array indices to ensure correct boundary handling. Teach students to verify their procedures handle edge cases like arrays with fewer than 10 elements.

Question 7

Based on the scenario, a teacher needs to count how many times each letter grade appears in a list grades containing strings from the set {"A","B","C","D","F"}. Input: list grades of length nnn. Output: a dictionary-like mapping from grade to count. Constraints: nnn up to 200,000; only these five possible values; AP-style pseudocode.

A student writes:

PROCEDURE CountGrades(grades)
  counts <- {"A":0,"B":0,"C":0,"D":0,"F":0}
  FOR EACH g IN grades
    FOR EACH key IN counts
      IF g = key
        counts[key] <- counts[key] + 1
  RETURN counts

How can the procedure be optimized for better performance?

  1. Replace the inner loop with a direct update: counts[g] <- counts[g] + 1. (correct answer)
  2. Sort grades first, then run the same nested loops to count faster.
  3. Use three nested loops so each grade is checked multiple times for accuracy.
  4. Remove the initialization of counts and create keys only at the end.

Explanation: This question tests AP Computer Science Principles skills in developing procedures, specifically focusing on algorithm optimization and eliminating unnecessary nested loops. The student's code uses nested loops where the outer loop iterates through each grade and the inner loop iterates through all possible grade keys to find a match, resulting in inefficient O(n×5) time complexity. Since the grade is already known from the outer loop, we can directly access and update the corresponding count without searching through all keys. Choice A is correct because replacing the inner loop with a direct update counts[g] <- counts[g] + 1 eliminates the unnecessary searching and reduces the time complexity to O(n), making it much more efficient for large datasets. Choice B is incorrect because sorting wouldn't help with counting and would add unnecessary overhead, and the nested loops would still be inefficient. To help students: Teach recognition of unnecessary nested loops and how to use direct access with dictionaries/maps. Practice analyzing time complexity and identifying opportunities to eliminate redundant operations, especially when working with known key sets.

Question 8

Based on the scenario, an online store keeps an array prices of decimal numbers. The program must compute the average price of items that cost at least 10.00. Input: list prices. Output: the average of qualifying prices, or 0 if none qualify. Constraints: nnn up to 100,000; one pass preferred; AP-style pseudocode.

PROCEDURE AvgAtLeastTen(prices)
  sum <- 0
  count <- 0
  FOR EACH p IN prices
    IF p >= 10.00
      sum <- sum + p
      count <- count + 1
  IF count = 0
    RETURN 0
  RETURN sum / count

What is the expected output of the procedure given the input prices = [9.99, 10.00, 12.50, 7.00]?

  1. 0
  2. 11.25 (correct answer)
  3. 10.83
  4. 9.87

Explanation: This question tests AP Computer Science Principles skills in developing procedures, specifically focusing on conditional aggregation and calculating averages with filters. The procedure calculates the average price of items costing at least $10.00, handling the edge case where no items qualify. Given prices = [9.99, 10.00, 12.50, 7.00], the procedure processes each price: 9.99 < 10 (skipped), 10.00 >= 10 (sum=10.00, count=1), 12.50 >= 10 (sum=22.50, count=2), 7.00 < 10 (skipped), resulting in sum=22.50 and count=2. Choice B is correct because 22.50 / 2 = 11.25, which is the average of the two qualifying prices (10.00 and 12.50). Choice C (10.83) might result from incorrectly including 9.99, and Choice D (9.87) might come from averaging all prices regardless of the condition. To help students: Emphasize the importance of carefully applying conditions before aggregating values, and practice tracing through calculations step by step. Teach students to verify their filtering logic by listing which values pass the condition before calculating.

Question 9

Based on the scenario, a library system processes a large list of book records books, where each record has fields title (string) and checkedOut (Boolean). Input: list books. Output: list of titles for books that are not checked out, in the same order they appear. Constraints: nnn can be up to 100,000; do not modify the original books list; use AP-style pseudocode.

A student writes:

PROCEDURE AvailableTitles(books)
  titles <- []
  FOR EACH book IN books
    IF book.checkedOut = TRUE
      APPEND(titles, book.title)
  RETURN titles

Which step is necessary to ensure the procedure works correctly?

  1. Change the condition to append titles only when book.checkedOut = FALSE. (correct answer)
  2. Sort books by title before filtering to avoid missing any records.
  3. Set titles <- NULL so the procedure can detect when no books are available.
  4. Replace the loop with recursion to reduce the time required for large lists.

Explanation: This question tests AP Computer Science Principles skills in developing procedures, specifically focusing on logical conditions and filtering data correctly. The task requires creating a procedure that returns titles of books that are NOT checked out, but the student's code has a logical error in the condition. The student's code currently checks if book.checkedOut = TRUE and appends those titles, which would return checked-out books instead of available books. Choice A is correct because changing the condition to append titles only when book.checkedOut = FALSE would fix the logical error and return the correct list of available books. Choice B is incorrect because sorting wouldn't fix the logical error, and the problem specification requires preserving the original order anyway. To help students: Teach careful reading of requirements and the importance of testing conditions with sample data. Practice converting English requirements like 'not checked out' into proper Boolean expressions, and encourage students to trace through their code with example inputs to verify correctness.

Question 10

Based on the scenario, a classroom tool merges two lists of student IDs. Input: list a and list b, each containing integers (IDs may repeat across lists). Output: a new list containing all IDs from a followed by all IDs from b. Constraints: do not change a or b; preserve order within each list; AP-style pseudocode.

A student writes:

PROCEDURE MergeLists(a, b)
  merged <- a
  FOR EACH id IN b
    APPEND(a, id)
  RETURN merged

Which step is necessary to ensure the procedure works correctly?

  1. Initialize merged as an empty list and append items from a and then b into merged. (correct answer)
  2. Sort a and b before merging so the output is always in numeric order.
  3. Remove duplicates while merging so each ID appears only once.
  4. Append all items from a into b instead, then return b to save memory.

Explanation: This question tests AP Computer Science Principles skills in developing procedures, specifically focusing on list manipulation and avoiding unintended side effects. The procedure should merge two lists by creating a new list containing all elements from list a followed by all elements from list b, without modifying the original lists. The student's code has a critical error: it sets merged <- a (which creates a reference, not a copy) and then appends to a directly, which modifies the original list a and violates the constraint. Choice A is correct because initializing merged as an empty list and then appending items from both a and b would create a new list without modifying the originals, satisfying all requirements. Choice D is incorrect because appending to b would modify the original list b, violating the constraint not to change the input lists. To help students: Teach the difference between creating references and copies of lists, and emphasize the importance of preserving input data when specifications require it. Practice identifying when procedures have unintended side effects and how to create independent copies of data structures.

Question 11

Based on the scenario, a game awards points when a player collects coins. Input: integer coinsCollected (may be 0 or more). Output: integer score added for this event. Rules: each coin is worth 10 points; if coinsCollected is at least 5, add a 50-point bonus once. Constraints: handle all nonnegative integers; AP-style pseudocode.

A student writes:

PROCEDURE CoinScore(coinsCollected)
  score <- 0
  score <- coinsCollected * 10
  IF coinsCollected > 5
    score <- score + 50
  RETURN score

Which step is necessary to ensure the procedure works correctly?

  1. Initialize score to 50 so the bonus is included by default.
  2. Change the condition to IF coinsCollected >= 5 to match the bonus rule. (correct answer)
  3. Replace multiplication with repeated addition to avoid arithmetic errors.
  4. Return coinsCollected instead of score to keep the output small.

Explanation: This question tests AP Computer Science Principles skills in developing procedures, specifically focusing on boundary conditions and correct implementation of bonus rules. The procedure calculates a score based on coins collected, with each coin worth 10 points and a bonus of 50 points if at least 5 coins are collected. The student's code has an off-by-one error: it checks if coinsCollected > 5 instead of >= 5, which means the bonus won't be applied when exactly 5 coins are collected. Choice B is correct because changing the condition to IF coinsCollected >= 5 ensures the bonus is applied when the player collects 5 or more coins, matching the stated rule. Choice A is incorrect because initializing score to 50 would give the bonus even when fewer than 5 coins are collected, violating the game rules. To help students: Emphasize the importance of carefully translating 'at least' into >= rather than >, and practice identifying boundary cases in conditional logic. Encourage testing procedures with boundary values (like exactly 5 coins) to catch off-by-one errors.

Question 12

Based on the scenario, a program reads a list of file sizes (integers) and must compute the total size, but the input may contain invalid values (negative numbers) due to a logging bug. Input: list sizes (length 0 to 100,000). Output: total of only valid sizes (values ≥ 0). Constraint: the procedure should skip invalid values rather than stopping the program.

PROCEDURE totalValidSizes(sizes)
  total ← 0
  FOR EACH s IN sizes
    total ← total + s
  ENDFOR
  RETURN total
ENDPROCEDURE

Which part of the procedure handles errors effectively while meeting the constraint to skip invalid values?

  1. Add IF s < 0 THEN CONTINUE before adding s to total. (correct answer)
  2. Return immediately when a negative value is found to prevent incorrect totals.
  3. Sort sizes so negatives appear first, then remove the first element.
  4. Set total ← -1 if any negative value is found to signal an error.

Explanation: This question tests AP Computer Science Principles skills in developing procedures, specifically focusing on error handling and input validation. Developing procedures involves implementing robust error handling that allows programs to continue processing valid data while skipping invalid entries. In this scenario, the procedure must skip negative file sizes while continuing to process valid ones. Choice A is correct because it adds a condition to skip negative values using CONTINUE, which moves to the next iteration without adding invalid values to the total. Choice B is incorrect because returning immediately would stop processing all remaining values, including valid ones, which violates the requirement to process all valid sizes. To help students: Teach the difference between skipping invalid data (continue) versus stopping execution (return). Practice implementing input validation that allows graceful handling of mixed valid and invalid data.

Question 13

Based on the scenario, a fitness app processes a large list of step counts (integers). Input is a list steps with up to 100,000 values (each 000 to 100,000100,000100,000). Output is the average step count for only the days with at least 10,000 steps; if there are no such days, output 0. Constraints: single pass preferred; avoid non-standard libraries. The procedure skeleton is:

PROCEDURE avgHighSteps(steps)
  total ← 0
  count ← 0
  FOR EACH s IN steps
    IF s ≥ 10000
      total ← total + s
      count ← count + 1
    ENDIF
  ENDFOR
  IF count = 0
    RETURN 0
  ENDIF
  RETURN total / count
ENDPROCEDURE

Which step is necessary to ensure the procedure works correctly for all valid inputs?

  1. Replace the loop with a nested loop to confirm each value is an integer.
  2. Initialize total and count to 1 to avoid dividing by zero.
  3. Include the check IF count = 0 RETURN 0 before computing total / count. (correct answer)
  4. Sort steps first so that all values ≥ 10000 are contiguous.

Explanation: This question tests AP Computer Science Principles skills in developing procedures, specifically focusing on error handling and edge cases. Developing procedures involves anticipating potential runtime errors and implementing safeguards to ensure correct output for all valid inputs. In this scenario, the procedure calculates an average but must handle the case where no values meet the criteria (count = 0), which would cause division by zero. Choice C is correct because it adds a check before the division operation to return 0 when count equals 0, preventing a runtime error. Choice B is incorrect because initializing count to 1 would produce incorrect results by artificially inflating the count of qualifying days. To help students: Emphasize the importance of testing edge cases, especially empty sets and division operations. Practice tracing through code with various inputs including edge cases to identify potential runtime errors.

Question 14

Based on the scenario, a game awards bonus points when a player collects coins. Input: an integer coinsCollected (0 to 1,000) and an integer currentScore (0 to 1,000,000). Output: the updated score. Rules: each coin is worth 10 points, and if coinsCollected is a multiple of 10, add an extra 100-point bonus once. Constraints: use a single procedure and simple conditionals.

PROCEDURE updateScore(currentScore, coinsCollected)
  currentScore ← currentScore + (coinsCollected * 10)
  IF coinsCollected MOD 10 = 0
    currentScore ← currentScore + 100
  ENDIF
  RETURN currentScore
ENDPROCEDURE

What is the expected output of the procedure given the input currentScore = 250 and coinsCollected = 20?

  1. 350
  2. 450
  3. 550 (correct answer)
  4. 650

Explanation: This question tests AP Computer Science Principles skills in developing procedures, specifically focusing on tracing through code execution and calculating outputs. Developing procedures involves understanding how sequential operations and conditional statements affect program state. In this scenario, the procedure updates a score based on coins collected, with a bonus for multiples of 10. Choice C (550) is correct because: starting with currentScore = 250, adding 20 coins × 10 points = 200 points gives 450, then since 20 MOD 10 = 0, the bonus of 100 is added, resulting in 550. Choice B (450) is incorrect because it omits the bonus calculation, demonstrating a common error in overlooking conditional logic. To help students: Practice step-by-step tracing with actual values, and emphasize checking all conditions in the code. Use visual representations or trace tables to track variable values through each line of execution.

Question 15

Based on the scenario, a teacher’s grading tool must remove duplicate student IDs from a list while preserving the first occurrence order. Input: list ids of integers (length up to 30,000). Output: a new list containing each ID once, in the order it first appeared. Constraint: keep the procedure simple and avoid non-standard libraries.

Current procedure:

PROCEDURE uniqueIDs(ids)
  result ← []
  FOR EACH id IN ids
    IF NOT CONTAINS(result, id)
      APPEND(result, id)
    ENDIF
  ENDFOR
  RETURN result
ENDPROCEDURE

How can the procedure be optimized for better performance on large inputs while keeping the same output?

  1. Use a second list seen and store every ID twice to reduce comparisons.
  2. Replace CONTAINS(result, id) with a set-like structure for membership checks, while still appending to result. (correct answer)
  3. Sort ids first, then remove adjacent duplicates to make the loop shorter.
  4. Remove the IF and always append, since duplicates do not affect correctness.

Explanation: This question tests AP Computer Science Principles skills in developing procedures, specifically focusing on optimizing duplicate detection. Developing procedures involves recognizing when data structure choices significantly impact performance, especially for membership testing operations. In this scenario, the CONTAINS operation on a list has O(n) complexity, making the overall algorithm O(n²) for large inputs. Choice B is correct because using a set-like structure for membership checks reduces the complexity of CONTAINS from O(n) to O(1) on average, while still maintaining the result list for ordered output. Choice D is incorrect because removing the duplicate check would fundamentally change the procedure's purpose, returning a list with duplicates instead of unique values. To help students: Teach the performance characteristics of different data structures for common operations. Practice identifying bottlenecks in algorithms and understanding how data structure choices affect overall complexity.

Question 16

Based on the scenario, a library app needs to efficiently check whether a book ID exists in a list that is already sorted in ascending order. Input: a sorted list bookIDs of integers (length up to 200,000) and an integer targetID. Output: true if targetID is in the list; otherwise false. Constraint: improve time efficiency compared with checking every element.

What is the most efficient way to implement the procedure described?

  1. Use a linear search that checks each ID from start to end until found.
  2. Use binary search by repeatedly checking the middle element and narrowing the range. (correct answer)
  3. Shuffle the list randomly, then check the first half for the target ID.
  4. Convert each ID to a string and compare string prefixes to find the target faster.

Explanation: This question tests AP Computer Science Principles skills in developing procedures, specifically focusing on algorithm selection for efficiency. Developing procedures involves choosing appropriate algorithms based on input characteristics, such as using binary search for sorted data. In this scenario, the list is pre-sorted, making binary search the optimal choice with O(log n) time complexity. Choice B is correct because binary search repeatedly divides the search space in half, dramatically reducing the number of comparisons needed compared to linear search's O(n) complexity. Choice A is incorrect because linear search doesn't take advantage of the sorted property, checking potentially all 200,000 elements in the worst case. To help students: Teach the importance of leveraging data properties (like being sorted) to choose efficient algorithms. Practice implementing and comparing linear versus binary search, understanding when each is appropriate.