Implementing String Algorithms

Help Questions

AP Computer Science A › Implementing String Algorithms

Questions 1 - 10
1

Problem: Implement public static String compress(String inputString) using run-length encoding: replace consecutive repeated characters with the character followed by the count (always include the count). Input: one string. Output: compressed string. Example: "aaabbc" -> "a3b2c1". Constraints: $0 \le$ length $\le 10^5$. Given the problem description above, what is the output of the function when given the input "aabccc"?

a2b1c3

a2bc3

a2b1c1c2

aabccc

Explanation

This question tests AP Computer Science A skills: implementing string algorithms using selection and iteration. String algorithms often use loops to process each character and conditionals to make decisions, allowing tasks like reversal, searching, and manipulation. In this problem, students must trace through run-length encoding that always includes counts, even for single characters. Choice B is correct because the algorithm compresses "aabccc" to "a2b1c3", including the count "1" for the single 'b' as specified by "always include the count" in the problem. Choice A is incorrect because it omits the count for 'b', violating the requirement to always include counts. To help students, emphasize careful reading of specifications and practice tracing algorithms step-by-step. Use examples with single and repeated characters to reinforce consistent formatting rules.

2

Problem: Write public static int countChar(String inputString, char target) that counts occurrences of target in inputString using a loop. Input: a string and a character. Output: count as an int. Example: ("mississippi", 's') -> 4. Constraints: $0 \le$ length $\le 10^5$. Given the problem description above, which function signature matches the problem requirements?

public static int countChar(String inputString)

public int countChar(char target, String inputString)

public static char countChar(String inputString, char target)

public static int countChar(String inputString, char target)

Explanation

This question tests AP Computer Science A skills: implementing string algorithms using selection and iteration. String algorithms often use loops to process each character and conditionals to make decisions, allowing tasks like reversal, searching, and manipulation. In this problem, students must identify the correct method signature that matches the problem requirements for counting character occurrences. Choice A is correct because it includes the static modifier (required for standalone utility methods), returns int (the count), and accepts both required parameters: the string to search and the target character. Choice D is incorrect because it's missing the target character parameter, making it impossible to know which character to count. To help students, practice matching method signatures to problem descriptions. Emphasize checking return types, parameter lists, and modifiers against requirements.

3

Problem: Write public static boolean isPalindrome(String text) using a loop that compares mirrored characters. Constraints: length 0 to 1000. Example: "abba" returns true. Given the problem description above, how many iterations will the loop execute for input of length $n$?

$n^2$

$n$

$\lfloor n/2 \rfloor$

$n - 1$

Explanation

This question tests AP Computer Science A skills: implementing string algorithms using selection and iteration. String algorithms often use loops to process each character and conditionals to make decisions, allowing tasks like reversal, searching, and manipulation. In this problem, students must determine how many iterations occur when checking palindromes by comparing mirrored characters. Choice C is correct because an efficient palindrome check only needs to compare up to the middle of the string - for a string of length n, this is floor(n/2) comparisons since each comparison checks two positions simultaneously. Choice A is incorrect because it suggests checking every character, which would do redundant work by checking each pair twice. To help students, draw diagrams showing which characters get compared in palindrome checking. Emphasize the efficiency gained by stopping at the middle.

4

Problem: Write public static String reverseString(String inputString) that returns inputString reversed using a for loop (no external libraries). Input: one string length 0 to 1000. Output: reversed string. Example: input "cat" outputs "tac". Given the problem description above, which statement correctly initializes the loop to reverse the string?

for (int i = inputString.length() - 1; i >= 0; i--)

for (int i = inputString.length() - 1; i > 0; i--)

for (int i = inputString.length(); i >= 0; i--)

for (int i = 0; i <= inputString.length() - 1; i--)

Explanation

This question tests AP Computer Science A skills: implementing string algorithms using selection and iteration. String algorithms often use loops to process each character and conditionals to make decisions, allowing tasks like reversal, searching, and manipulation. In this problem, students must correctly initialize a loop to reverse a string, ensuring all characters are processed from last to first. Choice B is correct because it starts at inputString.length() - 1 (the last valid index) and continues while i >= 0, processing every character including the one at index 0. Choice A is incorrect because it starts at inputString.length(), which is an invalid index causing an IndexOutOfBoundsException. To help students, emphasize that string indices range from 0 to length-1. Practice with visual diagrams showing string indices helps prevent off-by-one errors.

5

Problem: Write public static boolean isPalindrome(String text) that returns true if text reads the same forward and backward (case-sensitive), using loops and charAt. Constraints: length 0 to 1000. Example: "racecar" returns true. Given the problem description above, which code snippet correctly checks for a palindrome?

for (int i = 0; i < text.length() / 2; i++) if (text.charAt(i) != text.charAt(text.length() - 1 - i)) return true; return false;

for (int i = 0; i <= text.length() / 2; i++) if (text.charAt(i) != text.charAt(text.length() - i)) return false; return true;

for (int i = 0; i < text.length() / 2; i++) if (text.charAt(i) != text.charAt(text.length() - 1 - i)) return false; return true;

for (int i = 0; i < text.length(); i++) if (text.charAt(i) == text.charAt(text.length() - 1 - i)) return false; return true;

Explanation

This question tests AP Computer Science A skills: implementing string algorithms using selection and iteration. String algorithms often use loops to process each character and conditionals to make decisions, allowing tasks like reversal, searching, and manipulation. In this problem, students must check if a string reads the same forward and backward by comparing mirrored characters. Choice A is correct because it compares each character at position i with its mirror at position (length - 1 - i), only checking up to the middle, and returns false if any mismatch is found. Choice B is incorrect because it uses (length - i) instead of (length - 1 - i), causing an off-by-one error that accesses an invalid index. To help students, draw diagrams showing how indices map to their mirrors. Emphasize that palindrome checking only needs to go halfway through the string.

6

Problem: Implement public static int indexOfSubstring(String text, String pattern) returning the first index where pattern occurs in text, or -1 if not found, using nested loops (no libraries). Constraints: 0 <= text.length() <= 2000, 0 <= pattern.length() <= 200. Example: text "banana", pattern "na" returns 2. Given the problem description above, what is the runtime complexity of the provided substring search algorithm?

$O(n)$

$O(n \cdot m)$

$O(n^2)$

$O(\log n)$

Explanation

This question tests AP Computer Science A skills: implementing string algorithms using selection and iteration. String algorithms often use loops to process each character and conditionals to make decisions, allowing tasks like reversal, searching, and manipulation. In this problem, students must analyze the runtime complexity of a substring search algorithm using nested loops. Choice C is correct because the outer loop runs up to n times (text length) and for each position, the inner loop runs up to m times (pattern length) to check for a match, resulting in O(n·m) complexity. Choice A is incorrect because it assumes only one loop, ignoring the nested structure required to check each character of the pattern at each position. To help students, trace through small examples showing how many comparisons occur. Emphasize that nested loops often multiply their iteration counts for total complexity.

7

Problem: Reverse a string using a loop. Input: inputString (length 0–1000). Output: reversed string. No external libraries. Function signature: public static String reverse(String inputString). Given the problem description above, which statement correctly initializes the loop to reverse the string?

for (int i = inputString.length(); i >= 0; i--)

for (int i = inputString.length() - 1; i > 0; i--)

for (int i = inputString.length() - 1; i >= 0; i--)

for (int i = 0; i <= inputString.length() - 1; i--)

Explanation

This question tests AP Computer Science A skills: implementing string algorithms using selection and iteration. String algorithms often use loops to process each character and conditionals to make decisions, allowing tasks like reversal, searching, and manipulation. In this problem, students must correctly initialize a loop to traverse a string backwards for reversal. Choice B is correct because it starts at the last valid index (length - 1) and continues while i >= 0, ensuring all characters are processed in reverse order. Choice A is incorrect because starting at inputString.length() would cause an IndexOutOfBoundsException since string indices range from 0 to length-1. To help students, use visual representations of string indices and emphasize that the last character is at position length-1. Practice writing loops that traverse arrays and strings in both directions to reinforce proper boundary conditions.

8

Problem: Count character frequencies. Input: inputString (length 0–1000) containing only lowercase letters a–z. Output: an int[] counts of length 26 where counts0 is the number of 'a's, counts25 is the number of 'z's. No external libraries. Function signature: public static int[] countLetters(String inputString). Given the problem description above, which statement correctly updates counts for character ch?

counts[ch]++;

counts[ch - 'a']++;

counts[ch.substring(0, 1) - "a"]++;

counts['a' - ch]++;

Explanation

This question tests AP Computer Science A skills: implementing string algorithms using selection and iteration. String algorithms often use loops to process each character and conditionals to make decisions, allowing tasks like reversal, searching, and manipulation. In this problem, students must map lowercase letters to array indices for frequency counting. Choice A is correct because subtracting 'a' from any lowercase letter gives its position in the alphabet (0-25), perfectly mapping to array indices for the counts array. Choice B is incorrect because it uses the character's ASCII value directly as an index, which would require an array of size 123+ and waste space. To help students understand character arithmetic, demonstrate how 'a' - 'a' = 0, 'b' - 'a' = 1, etc. Practice problems involving character-to-index mappings reinforce this common pattern in string algorithms.

9

Problem: Determine if two strings are anagrams ignoring spaces and case. Input: s1 and s2 (each length 0–1000) containing letters and spaces. Output: true if they contain the same letters with the same counts; otherwise false. No external libraries. Function signature: public static boolean isAnagram(String s1, String s2). Given the problem description above, which function signature matches the problem requirements?

public static String isAnagram(String s1, String s2)

public static int isAnagram(String s1, String s2)

public static boolean isAnagram(String s1, String s2)

public boolean isAnagram(String s1)

Explanation

This question tests AP Computer Science A skills: implementing string algorithms using selection and iteration. String algorithms often use loops to process each character and conditionals to make decisions, allowing tasks like reversal, searching, and manipulation. In this problem, students must identify the correct method signature for an anagram checker based on given requirements. Choice A is correct because it matches all requirements: static method (can be called without object), boolean return type (true/false output), and two String parameters (comparing two strings). Choice C is incorrect because it lacks the static modifier and only takes one parameter, making it impossible to compare two strings for anagram status. To help students, practice matching method signatures to problem specifications. Emphasize reading requirements carefully to identify return types, parameter lists, and access modifiers.

10

Problem: Sort an array of strings in lexicographical order using selection sort. Input: String[] words (length 1–200) where each word length is 0–50. Output: the same array sorted ascending. No external libraries. Function signature: public static void selectionSort(String[] words). Given the problem description above, how many iterations will the outer loop execute for input of length n?

$n$

$n^2$

$n / 2$

$n - 1$

Explanation

This question tests AP Computer Science A skills: implementing string algorithms using selection and iteration. String algorithms often use loops to process each character and conditionals to make decisions, allowing tasks like reversal, searching, and manipulation. In this problem, students must understand selection sort's structure when applied to string arrays. Choice B is correct because selection sort's outer loop runs n-1 times: it finds the minimum for positions 0 through n-2, with the last element automatically in place after n-1 iterations. Choice A is incorrect because it suggests n iterations, but the last pass is unnecessary since a single remaining element is already sorted. To help students understand sorting algorithms, trace through small examples showing why the last element doesn't need processing. Emphasize the pattern that many sorting algorithms need only n-1 passes to sort n elements.

Page 1 of 2