Data Structures & AlgorithmsHardICPC regional · String round
Problem: Count the palindromic substrings of 'abacaba' (every occurrence counts, so single characters count too).
Problem: Count the palindromic substrings of 'abacaba' (every occurrence counts, so single characters count too).
def count(s):
total = 0
for c in range(2 * len(s) - 1):
l, r = c // 2, c // 2 + c % 2
while l >= 0 and r < len(s) and s[l] == s[r]:
total += 1
l -= 1
r += 1
return total
print(count('abacaba'))What is printed?- A. 7
- B. 12
- C. 9
- D. 5
Correct answer: B. 12
Expanding around all 2n − 1 centres counts 7 single letters, the three triples aba, aca, aba, the 5-letter bacab and the whole string: 12 occurrences. Counting distinct palindromic strings gives 7, a loop guard l > 0 instead of l >= 0 never reaches index 0 and gives 9, and skipping single letters gives 5.
More Coding Interview Problems questions
- Problem: A directed graph with V vertices is relaxed with Bellman-Ford. After V - 1 full rounds of relaxing all edges, one more round…
- Problem: A Fenwick tree of size 8 receives point adds (1,+5), (3,+2), (5,+7), (8,+1) with the usual add and prefix-query code, then prints…
- Problem: You want the maximum number of non-overlapping intervals. Which greedy rule is provably optimal?
- Problem: Count subarrays whose XOR is zero, for a = [1, 2, 3, 0, 3, 3]. python from collections import Counter def cnt(a): seen =…
- Problem: What does the following print? python print([format(i ^ (i >> 1), '03b') for i in range(4)])
- Problem: Count the pairs (i < j) with a[i] + a[j] < 6 for the array [5, 1, 4, 2, 3]. python def count(a, T): a = sorted(a) i, j = 0…