Implementing String Algorithms
Help Questions
AP Computer Science A › Implementing String Algorithms
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 - 1$
$n$
$n^2$
$n / 2$
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.
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 static int countChar(String inputString, char target)
public int countChar(char target, String inputString)
public static char 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.
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 \cdot m)$
$O(\log n)$
$O(n)$
$O(n^2)$
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.
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['a' - ch]++;
counts[ch.substring(0, 1) - "a"]++;
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.
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$?
$\lfloor n/2 \rfloor$
$n^2$
$n$
$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.
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 = 0; i <= inputString.length() - 1; i--)
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--)
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.
Problem: Find the first occurrence of pattern in text using a loop (no libraries). Input: text and pattern. Output: first index or -1. Function signature: public static int indexOf(String text, String pattern). Given the problem description above, what is the output of the function when given the input "banana" and "ana"?
-1
1
2
3
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 a substring search to find where "ana" first appears in "banana". Choice B is correct because "ana" first appears at index 1 in "banana" (b-a-n-a-n-a, positions 0-1-2-3-4-5), where positions 1-2-3 contain "ana". Choice C is incorrect because it represents the second occurrence of "ana" starting at index 3, but the problem asks for the first occurrence. To help students trace string algorithms, use index diagrams and highlight pattern matches visually. Practice finding all occurrences of a pattern to understand why algorithms typically return the first match.
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
aabccc
a2b1c1c2
a2bc3
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.
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 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;
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;
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.
Problem: Reverse a string using a loop. Input: inputString (length 0–1000). Output: reversed string. Function signature: public static String reverse(String inputString). Given the problem description above, what is the output of the function when given the input "example"?
example
elpmaxe
xamplee
elpmaxee
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 a string reversal algorithm with the input "example". Choice A is correct because reversing "example" character by character produces "elpmaxe" - each character is placed in reverse order from the original string. Choice B is incorrect because it shows an extra 'e' at the end, suggesting an error in the loop bounds or string building logic. To help students debug string algorithms, encourage step-by-step tracing with small examples. Use tables showing the string being built at each iteration to visualize the reversal process.