AP Computer Science Principles Algorithms and Programming — Worked Answer Explanations
Unit 3 · 24 questions explained
Below is a complete answer key for our AP Computer Science Principles Algorithms and Programming practice questions. For each question you'll find the correct choice, a full written explanation of how to get there, and — for every wrong answer — a short note on exactly why it's tempting and where it goes wrong. Reading these straight through is one of the fastest ways to find the gaps in a unit before exam day.
Prefer to test yourself first? Take the timed Algorithms and Programming practice test and come back here to review, or head back to the Algorithms and Programming unit overview.
- Question 1 · Easy
What is displayed when the following pseudocode runs?
x ← 4 y ← x + 3 x ← y * 2 DISPLAY x- A4Why not A: 4 is the initial value of x; x is reassigned twice before DISPLAY executes.
- B7Why not B: 7 is the value of y (4+3); x is then reassigned to y*2 = 14 before DISPLAY.
- C14Correct
- D8Why not D: 8 = 42 uses the original x value before y is computed; but y ← x+3 = 7, then x ← y2 = 14.
ExplanationTrace step by step:
x ← 4→ x = 4y ← x + 3= 4 + 3 = 7 → y = 7x ← y * 2= 7 * 2 = 14 → x = 14DISPLAY x→ displays 14
Key takeawayAssignment (←) replaces the variable's previous value; always trace statements in order, using the updated value at each step.
- A
- Question 2 · Easy
What is displayed when the following pseudocode runs?
a ← 10 IF a MOD 3 = 0 { DISPLAY "divisible" } ELSE { DISPLAY "not divisible" }- A
divisibleWhy not A: 10 MOD 3 = 1 (not 0), so the condition is false and the ELSE branch executes. - B
not divisibleCorrect - C
1Why not C: 1 is the value of 10 MOD 3, but the code displays a string based on the condition, not the MOD value itself. - DNothing is displayed.Why not D: One of the two branches always executes; something is always displayed.
ExplanationMOD computes the remainder of integer division. 10 ÷ 3 = 3 remainder 1, so
10 MOD 3 = 1. Since 1 ≠ 0, the conditiona MOD 3 = 0is FALSE, and the ELSE branch executes, displayingnot divisible.Key takeawayMOD gives the remainder of integer division; use it to test divisibility (remainder = 0 means divisible).
- A
- Question 3 · Easy
Which of the following lists contains the elements in the correct order after a linear (sequential) search of the list
[3, 7, 1, 9, 4]for the value9?- AThe algorithm checks 9 first because it searches for the target value.Why not A: Linear search begins at the first element and checks each element in order; it does not jump to the target.
- BThe algorithm checks elements in the order: 3, then 7, then 1, then 9 (found).Correct
- CThe algorithm checks elements in the order: 9, 4, 1, 7, 3 (reverse order).Why not C: Linear search traverses the list from the beginning (index 1) to the end, not from the end to the beginning.
- DThe algorithm sorts the list first, then searches: 1, 3, 4, 7, 9.Why not D: Linear search does not sort the list; only binary search requires a sorted list.
ExplanationA linear (sequential) search inspects each element in order, starting from the first. For
[3, 7, 1, 9, 4]searching for 9: checks 3 (no), 7 (no), 1 (no), 9 (yes — found at index 4). The algorithm stops as soon as it finds the target.Key takeawayLinear search checks each element in order from the start, stopping when the target is found or the list is exhausted.
- A
- Question 4 · Easy
Which of the following Boolean expressions evaluates to
true?- A
(5 > 7) AND (3 = 3)Why not A: The left operand5 > 7is false, so the entire AND expression is false regardless of the right operand. - B
(5 > 7) OR (3 = 3)Correct - C
NOT (3 = 3)Why not C:3 = 3is true, andNOT trueevaluates to false. - D
(5 > 7) AND NOT (3 = 3)Why not D: Both5 > 7andNOT (3 = 3)are false, so the AND expression is false.
ExplanationAn OR expression is true when at least one operand is true. In option B, the left side
5 > 7is false but the right side3 = 3is true, so the OR returns true. AND requires both sides to be true; NOT inverts a Boolean value. Understanding short-circuit-style reasoning on small Boolean expressions is a foundational CSP skill.Key takeawayOR is true when at least one operand is true; AND requires both.
- A
- Question 5 · Easy
A student writes the following procedure header:
PROCEDURE addNumbers(a, b)Which statement BEST describes what
aandbare?- AThey are the values the procedure returns to the caller.Why not A: Return values are produced by a
RETURNstatement inside the procedure body, not declared in the header parameter list. - BThey are parameters that receive the values passed in by the caller.Correct
- CThey are global variables shared between all procedures.Why not C: Variables in a procedure header are local parameters, not global. Their scope is limited to the procedure body.
- DThey are constants whose values cannot change.Why not D: Parameters are regular variables that can be reassigned inside the procedure; they are not declared as constants by appearing in the header.
ExplanationItems listed in a procedure header (after the procedure name, inside the parentheses) are parameters. When the procedure is called — e.g.,
addNumbers(3, 4)— the arguments3and4are passed in and bound to the parameter namesaandbfor the duration of that call. Parameters are local to the procedure and let the same code operate on different inputs.Key takeawayParameters in a procedure header receive the argument values passed by the caller.
- A
- Question 6 · Easy
What is displayed when the following pseudocode runs?
nums ← [10, 20, 30, 40, 50] total ← 0 FOR EACH n IN nums { total ← total + n } DISPLAY total- A50Why not A: 50 is just the last element; total accumulates ALL elements.
- B100Why not B: 100 = 10+20+30+40, which misses the last element (50). The loop iterates over all 5 elements.
- C150Correct
- D250Why not D: 250 would result from doubling each element or another arithmetic error; 10+20+30+40+50 = 150.
ExplanationThe FOR EACH loop iterates over every element in
nums. The accumulatortotalstarts at 0 and adds each element in turn:- 0 + 10 = 10
- 10 + 20 = 30
- 30 + 30 = 60
- 60 + 40 = 100
- 100 + 50 = 150
DISPLAY totaloutputs 150.Key takeawayFOR EACH iterates over every list element; an accumulator variable collects running totals by adding each value.
- A
- Question 7 · Easy
A procedure
double(n)returnsn * 2. What is the value returned bydouble(double(3))?- A6Why not A: 6 = double(3) = 3*2; this evaluates only the inner call and ignores the outer double call.
- B9Why not B: 9 = 3^2; squaring is not what double does. double multiplies by 2, not by itself.
- C12Correct
- D18Why not D: 18 = 323; this incorrectly multiplies by 3 at some step instead of 2.
ExplanationEvaluate inside-out:
- Inner call:
double(3)= 3 * 2 = 6 - Outer call:
double(6)= 6 * 2 = 12
Nested procedure calls are evaluated from the innermost outward.
Key takeawayNested procedure calls evaluate inside-out: compute the innermost call first, then use its return value as the argument to the outer call.
- A
- Question 8 · Easy
What is displayed when the following pseudocode runs?
result ← 1 REPEAT 5 TIMES { result ← result * 2 } DISPLAY result- A10Why not A: 10 = 2*5 uses addition (1+2+2+2+2) or multiplication by the loop count, not repeated doubling.
- B16Why not B: 16 = 2^4; this is the result of doubling 4 times, not 5.
- C32Correct
- D64Why not D: 64 = 2^6; this is the result of doubling 6 times, not 5.
ExplanationThe loop runs exactly 5 times, doubling
resulteach time. Starting from 1:- After iteration 1: 1 * 2 = 2
- After iteration 2: 2 * 2 = 4
- After iteration 3: 4 * 2 = 8
- After iteration 4: 8 * 2 = 16
- After iteration 5: 16 * 2 = 32
DISPLAY resultoutputs 32 (= 2^5).Key takeawayREPEAT N TIMES executes the body exactly N times; repeated doubling from 1 gives 2^N after N iterations.
- A
- Question 9 · Easy
A programmer needs to write a procedure that determines whether a given word is a palindrome (reads the same forwards and backwards). She first writes a procedure that reverses a string, then uses it inside the palindrome-checker. This approach BEST demonstrates which programming concept?
- AIteration — the palindrome check repeats the reversal multiple times.Why not A: One call to the reverse procedure is not iteration; calling a helper procedure inside another is abstraction and procedural decomposition.
- BAbstraction — using a helper procedure to hide the details of string reversal, so the palindrome checker focuses on its own logic.Correct
- CSimulation — the palindrome checker simulates reading the word backwards.Why not C: Simulation models real-world processes; calling a reversal procedure and comparing results is not simulation.
- DRecursion — the palindrome procedure calls itself to check inner characters.Why not D: The procedure calls a separate reversal helper, not itself. Recursion means a procedure calls itself.
ExplanationAbstraction means hiding complexity behind a clean interface. The programmer writes a
reverse(word)procedure that hides the reversal logic, then the palindrome checker simply callsreverse(word)and compares the result to the original — without needing to know HOW reversal is implemented. This reduces complexity and promotes code reuse.Key takeawayAbstraction hides complexity: a helper procedure encapsulates details so the calling procedure can focus on higher-level logic.
- A
- Question 10 · Easy
What is displayed when the following pseudocode runs?
x ← 10 IF (x > 5) { IF (x > 12) { DISPLAY "big" } ELSE { DISPLAY "medium" } } ELSE { DISPLAY "small" }- A
bigWhy not A:x > 12is false (10 is not greater than 12), so the inner ELSE branch runs, not the inner IF branch. - B
mediumCorrect - C
smallWhy not C: The outer IFx > 5is true (10 > 5), so the outer ELSE branch (small) is skipped. - D
big mediumWhy not D: Inner IF/ELSE branches are mutually exclusive — only one runs, never both.
ExplanationTrace the nested conditional:
x = 10. The outer IFx > 5is true, so we enter that block. Inside,x > 12is false, so the inner ELSE runs and displaysmedium. The outer ELSE (small) is skipped. Nested IF/ELSE structures are evaluated top-down; only one path through the tree executes per run.Key takeawayNested IF/ELSE evaluates conditions top-down, with only one branch executing per nesting level.
- A
- Question 11 · Easy
Which of the following pairs BEST distinguishes a procedure from an event handler?
- AA procedure can take parameters; an event handler cannot.Why not A: Both procedures and event handlers can accept parameters (event handlers often receive an event object as a parameter).
- BA procedure is called explicitly by other code; an event handler runs in response to a user action or system event.Correct
- CA procedure runs in parallel; an event handler runs sequentially.Why not C: Parallel vs sequential execution is unrelated to whether something is a procedure or event handler. Most event handlers run on a single event loop.
- DOnly event handlers can have side effects on the display.Why not D: Any procedure can produce display output (e.g., DISPLAY statements). Side effects are not exclusive to event handlers.
ExplanationA procedure (sometimes called a function or method) executes when explicitly called by other code:
myProcedure(args). An event handler is a procedure registered to run automatically when a specific event occurs — a button click, key press, mouse move, or sensor reading. The runtime invokes it for you; you don't call it directly. This event-driven model underlies most interactive applications.Key takeawayProcedures are called by code; event handlers are triggered automatically by events.
- A
- Question 12 · Medium
The following pseudocode is intended to find and return the minimum value in a list
nums(which has at least one element).PROCEDURE findMin(nums) { minVal ← nums[1] FOR EACH n IN nums { IF n < minVal { minVal ← n } } RETURN minVal }What does
findMin([8, 3, 6, 1, 5])return?- A8Why not A: 8 is the first element (initial minVal), but the loop updates minVal whenever a smaller value is found.
- B3Why not B: 3 is smaller than 8 so minVal updates to 3, but 1 is smaller still and causes a further update.
- C1Correct
- D5Why not D: 5 is the last element but is not the smallest; 1 is smaller and was seen before 5.
ExplanationTrace: minVal starts at nums[1] = 8. The FOR EACH loop checks each element:
- n=8: 8 < 8? No
- n=3: 3 < 8? Yes → minVal = 3
- n=6: 6 < 3? No
- n=1: 1 < 3? Yes → minVal = 1
- n=5: 5 < 1? No
RETURN minVal = 1.
Key takeawayA running-minimum algorithm initializes minVal to the first element, then updates it whenever a smaller element is encountered.
- A
- Question 13 · Medium
Which of the following BEST describes an undecidable problem in computer science?
- AA problem that computers cannot solve because modern processors are too slow.Why not A: Undecidability is not a hardware speed limitation; no amount of faster hardware can solve an undecidable problem.
- BA problem for which no algorithm can exist that always correctly determines a yes/no answer for every possible input.Correct
- CA problem that is difficult to solve but becomes solvable with better algorithms.Why not C: That describes an intractable or hard problem; undecidable problems are provably unsolvable algorithmically, not just currently difficult.
- DA problem with more than one correct answer, making it hard for an algorithm to decide which to return.Why not D: Multiple correct answers describe ambiguity; undecidability means no algorithm can always give a correct yes/no answer at all.
ExplanationAn undecidable problem is one for which it can be proven that no algorithm exists that always correctly answers yes or no for every possible input. The classic example is the Halting Problem: given an arbitrary program and input, determine whether the program will halt or run forever. Alan Turing proved this is undecidable — no algorithm can solve it for all cases. Undecidability is not about speed or difficulty; it is a theoretical impossibility.
Key takeawayAn undecidable problem has no algorithm that always gives a correct yes/no answer for all inputs — the Halting Problem is the canonical example.
- A
- Question 14 · Medium
A simulation models the spread of a disease through a population. Researchers run the simulation 1,000 times with slightly randomized initial conditions and observe how outcomes vary.
Which of the following BEST explains why running the simulation many times is useful?
- AEach additional run makes the simulation more accurate by correcting errors from previous runs.Why not A: Later runs do not fix errors in earlier runs; each run is independent. The benefit is statistical, not error-correction.
- BRunning many simulations allows researchers to understand the range of possible outcomes and the likelihood of each, accounting for uncertainty in initial conditions.Correct
- CA simulation must be run exactly 1,000 times to produce statistically valid results.Why not C: There is no magic number; the goal is enough runs to see the distribution of outcomes, and the required number depends on the variance.
- DRunning simulations replaces the need for real-world data because the simulation IS the experiment.Why not D: Simulations are models based on assumptions; they complement real-world data but cannot replace it, especially if the model's assumptions are wrong.
ExplanationAny simulation with randomized or uncertain inputs can produce different outcomes on each run. By running many simulations, researchers build a distribution of outcomes — they can see not just one possible result but the full range, including how likely extreme outcomes are. This is the Monte Carlo approach to quantifying uncertainty. The value is statistical insight, not error correction.
Key takeawayRunning a simulation many times reveals the distribution of outcomes under uncertainty, not just a single deterministic result.
- A
- Question 15 · Medium
What value does the following pseudocode display?
nums ← [3, 7, 2, 8, 5, 1, 9] count ← 0 FOR EACH n IN nums { IF (n > 4) { count ← count + 1 } } DISPLAY count- A
3Why not A: Off-by-one undercount — perhaps missed counting 7, 8, or 9. Recount each element greater than 4. - B
4Correct - C
5Why not C: 5 may have been incorrectly included as well as 4 — but the condition is> 4, not>= 4. 4 itself is not in the list anyway, but 5 IS greater than 4 and counts. The total is 4 (5, 7, 8, 9). - D
7Why not D: This is the length of the list (7 elements), not the count of elements satisfying the condition.
ExplanationIterate through
numsand tally elements wheren > 4. The list is [3, 7, 2, 8, 5, 1, 9]: 3 (no), 7 (yes), 2 (no), 8 (yes), 5 (yes), 1 (no), 9 (yes). Four matches, socount = 4. This is the standard accumulator pattern: a counter variable initialized outside the loop, incremented conditionally inside.Key takeawayCounting matches in a list uses an accumulator initialized outside the loop, incremented conditionally inside.
- A
- Question 16 · Medium
A list
scores ← [85, 92, 78, 90, 65]is passed to the procedure below. What value doesmystery(scores)return?PROCEDURE mystery(list) { best ← list[1] FOR EACH item IN list { IF (item > best) { best ← item } } RETURN best }- A
65Why not A: 65 is the minimum, not the maximum. The IF condition keeps the LARGER value when comparing. - B
85Why not B: 85 is the first element (the initial value ofbest), but the loop updatesbestwhenever a larger value is found, so the answer must be at least the maximum. - C
92Correct - D
410Why not D: 410 is the sum of the list. The procedure does not accumulate via addition; the only update tobestis via assignment (best ← item).
ExplanationThe procedure finds the maximum value in
list. It initializesbestto the first element, then walks the list comparing each item tobest; whenever a larger value is found,bestis updated. After processing [85, 92, 78, 90, 65],best = 92. This is the canonical "find max" pattern — interchangeable with "find min" by flipping the comparison.Key takeawayThe find-max pattern initializes to the first element and reassigns whenever a larger value is seen.
- A
- Question 17 · Medium
A binary search will only work correctly on a list that:
- AContains only positive integersWhy not A: Binary search works on any orderable values, including negative numbers, decimals, strings, etc. The constraint is ordering, not numeric sign.
- BIs sorted in orderCorrect
- CHas a length that is a power of 2Why not C: Binary search handles lists of any length. The midpoint calculation works fine for odd or non-power-of-2 sizes.
- DContains no duplicate valuesWhy not D: Binary search tolerates duplicates — it just returns one of the matching positions. The algorithm itself doesn't require uniqueness.
ExplanationBinary search repeatedly halves the search interval by comparing the target to the middle element and discarding the half it cannot be in. This logic depends on the list being sorted: "the target is greater than the middle, so it must be to the right" only holds when elements are ordered. On an unsorted list, binary search may skip past the target. Linear search makes no such assumption but is slower for large sorted lists (O(n) vs O(log n)).
Key takeawayBinary search requires a sorted list; it leverages ordering to halve the search range each step.
- A
- Question 18 · Medium
A programmer needs to compute the area of three rectangles with different dimensions and display each area. Which approach BEST demonstrates procedural abstraction?
- ACopy and paste the multiplication and DISPLAY statements three times, hard-coding each set of dimensions.Why not A: Copy-paste duplicates logic. Procedural abstraction does the opposite: extracts repeated logic into a reusable procedure.
- BWrite three separate procedures, one per rectangle, with no parameters.Why not B: Three single-purpose procedures still duplicate the multiplication logic. Abstraction needs a single procedure that handles all cases via parameters.
- CWrite one procedure
area(width, height)that returnswidth * height, then call it three times with different arguments.Correct - DUse a global variable for area and reassign it inside each section.Why not D: Global variables don't extract reusable logic; they share state. The shared computation is the area formula, which belongs in a parameterized procedure.
ExplanationProcedural abstraction is the practice of giving a name to a piece of computation so it can be reused with different inputs. The shared logic here is
width * height. Extracting it intoarea(width, height)lets the caller invokearea(3, 4),area(5, 2),area(7, 6)without restating the formula. Benefits: less code, single point of change if the formula needs updating, easier reading.Key takeawayProcedural abstraction extracts repeated logic into a parameterized procedure that can be reused with different arguments.
- A
- Question 19 · Medium
A serial (sequential) version of a program takes 60 seconds to run. A parallel version uses 4 processors and contains a portion that cannot be parallelized, which takes 10 seconds. The parallelizable portion takes 50 seconds when run serially. What is the runtime of the parallel version?
- A
15secondsWhy not A: 15 sec would require dividing the WHOLE 60-sec program by 4. The 10-sec sequential portion can't be parallelized and adds on top of the parallelized 12.5. - B
22.5secondsCorrect - C
50secondsWhy not C: 50 seconds would result if NONE of the work were parallelized. Half of the 60-sec serial budget gets reduced by parallelism. - D
60secondsWhy not D: 60 seconds is the original serial time. Parallel execution must be faster for the parallelizable portion.
ExplanationThe parallelizable portion (50 sec serial) split across 4 processors takes 50/4 = 12.5 sec. The non-parallelizable portion still takes 10 sec because it must run sequentially. Total = 10 + 12.5 = 22.5 sec. This illustrates the limit on parallel speedup (Amdahl's Law in spirit): the sequential fraction sets a lower bound on runtime no matter how many processors you add.
Key takeawayParallel runtime = sequential portion + (parallel portion / number of processors); the sequential floor bounds maximum speedup.
- A
- Question 20 · Hard
A recursive procedure
power(base, exp)computesbaseraised to the powerexpusing the rule:power(base, exp)=base * power(base, exp - 1), with the base casepower(base, 0)= 1.How many total calls to
power(including the initial call) are made when computingpower(3, 4)?- A3Why not A: 3 is the base value, not the number of recursive calls. The recursion proceeds from exp=4 down to exp=0.
- B4Why not B: 4 is the exponent; the recursion makes 4 recursive calls PLUS the initial call, for a total of 5.
- C5Correct
- D12Why not D: 12 = 3*4 multiplies base by exponent; this does not count recursive calls, which reduce exp by 1 each time from 4 to 0.
ExplanationThe call chain is:
power(3, 4)— callspower(3, 3)power(3, 3)— callspower(3, 2)power(3, 2)— callspower(3, 1)power(3, 1)— callspower(3, 0)power(3, 0)— base case, returns 1
Total: 5 calls (initial call + 4 recursive calls). In general,
power(base, exp)makesexp + 1calls.Key takeawayRecursive power(base, exp) makes exp+1 total calls: one per exponent level from exp down to 0 (inclusive).
- A
- Question 21 · Hard
A delivery company needs to find a route that visits 30 cities and returns home with the lowest total distance. An exact algorithm guaranteed to find the optimal route would take an impractically long time. Which approach is MOST appropriate?
- AUse a heuristic (e.g., "always travel to the nearest unvisited city next") that finds a good — but not necessarily optimal — route quickly.Correct
- BAlways use the exact algorithm because correctness matters more than speed.Why not B: If the exact algorithm is impractical to run, refusing to compromise means no answer at all. A heuristic gives a usable answer in practical time.
- CSkip the routing problem and have drivers pick routes manually.Why not C: Manual routing is itself a (very informal) heuristic done by humans, but it's typically worse than a well-chosen algorithmic heuristic and doesn't scale to 30 cities.
- DUse a random ordering of cities each time.Why not D: Random orderings will sometimes happen to be good but typically produce poor routes. Heuristics use problem-specific knowledge to do meaningfully better than random.
ExplanationThe traveling-salesperson-style problem belongs to a class for which no known algorithm runs in reasonable (polynomial) time on large inputs. When exact optimal solutions are infeasible, a heuristic trades guaranteed optimality for practical speed: "nearest neighbor," "two-opt," and similar approaches produce good-enough routes quickly. Recognizing when to accept a heuristic instead of an exact algorithm is a key engineering judgment.
Key takeawayHeuristics give good-enough solutions in practical time when exact algorithms are too slow; they trade optimality for tractability.
- A
- Question 22 · Hard
Two programmers are refactoring a 200-line program to reduce code duplication. Programmer A extracts every block of three or more repeated lines into its own procedure. Programmer B extracts only blocks that compute something conceptually meaningful. Which approach is MORE consistent with good procedural abstraction, and why?
- AProgrammer A — any duplication should be eliminated, regardless of what the code means.Why not A: Mechanically extracting every repeated block can produce procedures with no clear purpose and awkward parameter lists (e.g.,
helperBlock3(a, b, c, d, e, f)). Duplication is a symptom; conceptual cohesion is the goal. - BProgrammer B — procedures are most useful when they have a clear, nameable purpose, even if some duplication remains.Correct
- CProgrammer A — shorter total code is always better.Why not C: Shorter total code is not the primary goal of abstraction; readability, reusability, and maintainability are. A procedure that's only invoked once and has no clear purpose adds overhead without benefit.
- DProgrammer B — extracted procedures should never have parameters.Why not D: Parameters are essential to useful procedural abstraction; they let the same procedure work in multiple contexts. Programmer B's principle is conceptual purpose, not avoidance of parameters.
ExplanationGood procedural abstraction is driven by meaning, not just syntactic repetition. A procedure should answer the question "what does this do?" with a short, clear name —
convertCelsiusToFahrenheit,computeShippingCost,isValidEmail. Three repeated lines that don't share a conceptual purpose make a poor extraction target: the resulting procedure has no obvious name and forces awkward parameters. Sometimes leaving duplication in place is the right call.Key takeawayProcedural abstraction is most useful when the extracted procedure has a clear, nameable conceptual purpose — not just repeated text.
- A
- Question 23 · Hard
Which of the following problems has a REASONABLE (polynomial-time) algorithm, and which is considered to have only UNREASONABLE (exponential-time) algorithms for large inputs?
- Problem I: Sorting a list of n numbers
- Problem II: Checking all possible subsets of n items to find a subset that sums to a target value (brute-force subset sum)
- ABoth problems have reasonable (polynomial-time) algorithms.Why not A: Brute-force subset sum checks 2^n subsets, which grows exponentially; it is not polynomial-time.
- BProblem I has a reasonable algorithm (e.g., merge sort runs in O(n log n)); Problem II (brute-force) has an unreasonable exponential-time algorithm.Correct
- CBoth problems have only unreasonable (exponential-time) algorithms.Why not C: Sorting has well-known polynomial-time algorithms like merge sort (O(n log n)); it is not exponential.
- DProblem I is unreasonable because you must compare every pair of elements; Problem II is reasonable because you stop as soon as you find a valid subset.Why not D: Comparison-based sorting is polynomial (O(n log n)), not exponential. Stopping early helps in practice but worst-case subset sum is still exponential.
ExplanationIn AP CSP, a "reasonable" algorithm runs in polynomial time (n, n^2, n log n, etc.) and remains practical for large n. Sorting algorithms like merge sort run in O(n log n) — polynomial and very practical. Brute-force subset sum checks all 2^n subsets: for n=100, that is roughly 10^30 operations — wildly impractical. Exponential-time algorithms are considered "unreasonable" for large inputs.
Key takeawayPolynomial-time algorithms (like sorting) are reasonable; exponential-time algorithms (like brute-force subset search) are unreasonable for large inputs.
- Question 24 · Hard
Which of the following BEST describes the difference between a problem that has a reasonable algorithm and one that requires an unreasonable algorithm in the CSP framework?
- AReasonable algorithms always terminate; unreasonable algorithms may run forever.Why not A: Both reasonable and unreasonable algorithms terminate (eventually). Algorithms that never terminate are a separate concept (undecidability), not the reasonable/unreasonable distinction.
- BReasonable algorithms run in time that grows polynomially with input size; unreasonable algorithms grow exponentially (or faster), so they become impractical even on modest inputs.Correct
- CReasonable algorithms use less memory; unreasonable algorithms always run out of memory.Why not C: The reasonable/unreasonable distinction in CSP refers to time complexity, not memory. Unreasonable-time algorithms can sometimes use modest memory but still take impractical time.
- DReasonable algorithms are guaranteed to find an optimal answer; unreasonable ones only approximate.Why not D: Both reasonable and unreasonable algorithms can be exact. The distinction is about runtime scaling with input size, not optimality. Heuristics are a separate concept for approximating answers to hard problems.
ExplanationIn CSP, a reasonable-time algorithm is one whose runtime grows at most polynomially with input size (e.g., n, n², n³). An unreasonable-time algorithm grows exponentially or faster (2^n, n!) — these become impractical past small inputs because runtime explodes. For example, an O(n) algorithm on n = 100 takes 100 steps; an O(2^n) algorithm on n = 100 takes ~10³⁰ steps, far more than feasible. The distinction matters because for unreasonable problems, we often turn to heuristics or approximation.
Key takeawayReasonable-time algorithms scale polynomially; unreasonable-time ones scale exponentially or faster, becoming impractical past small inputs.
- A