ProgrammingHardTCS NQT · Accenture
A string is a rotation of another when it can be obtained by moving some prefix to the end. The procedure below checks whether "waterbottle" is a rotation of "erbottlewat" by searching for "waterbottle" in the doubled string "erbottlewat" + "erbottlewat", counting every start position where the match occurs. What is printed?
A string is a rotation of another when it can be obtained by moving some prefix to the end. The procedure below checks whether "waterbottle" is a rotation of "erbottlewat" by searching for "waterbottle" in the doubled string "erbottlewat" + "erbottlewat", counting every start position where the match occurs. What is printed?
doubled = s2 + s2 count = number of positions i with doubled[i .. i+len-1] == s1 Print count
- A. 0
- B. 1
- C. 22
- D. 2
Correct answer: B. 1
The doubled string contains waterbottle at exactly one start position, so the count is 1. Searching in the undoubled string finds nothing, the doubled length is 22, and counting the substring wat in the doubled string gives 2.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- The array [1, 2, 3, 4, 5, 6, 7] is shifted left by 2 positions by the procedure below: the element at index k is placed at index (k - 2)…
- The procedure below uses bitmasks over the set {1, 2, 3} (bit i set means element i+1 is included), so it visits the 8 subsets including…
- The number of trailing zeros in the decimal form of 2^20 5^3 is found by the procedure below, which divides out factors of 10 one at a…
- The procedure below computes the integer square root of 200 by testing r = 0, 1, 2, ... and stopping at the largest r with (r + 1) (r + 1)…
- The procedure below finds the smallest 0-based index i at which the prefix sum of [4, -1, 3, -2, 5] reaches at least 7. It prints i. What…
- Two sorted arrays a = [1, 4, 7] and b = [2, 3, 8, 9] are merged by the two-pointer procedure below, and the procedure prints the 4th…