Data Structures & AlgorithmsModerateAmazon · Microsoft OA
Problem: Count palindromic substrings (by position, so equal strings at different places count separately) by expanding around every centre.
Problem: Count palindromic substrings (by position, so equal strings at different places count separately) by expanding around every centre.
def count(s):
res = 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]:
res += 1; l -= 1; r += 1
return res
print(count("aaab"))What is printed?- A. 4
- B. 7
- C. 5
- D. 10
Correct answer: B. 7
Single letters give 4; 'aa' occurs twice (positions 0–1 and 1–2); 'aaa' once: 4 + 2 + 1 = 7. Counting DISTINCT palindromes would give only 4 (a, b, aa, aaa).
More Coding Interview Problems questions
- Problem: Cut a rod of length 7 into integer pieces to maximise total price, where price[i] is the price of a piece of length i + 1…
- Problem: Envelopes [w, h] nest only if both dimensions are strictly smaller. Find the longest nesting chain by sorting and then running…
- Problem: Can the array be split into k subsets with equal sums? (Backtracking over bucket fills.) python def can(a, k): s = sum(a) if s %…
- Problem: Find the minimum number of single-bit flips in a and b so that (a OR b) == c. python def flips(a, b, c): res = 0 while a or b or…
- Problem: Enumerate all non-empty submasks of a mask with the s = (s − 1) & m trick. python m = 0b101101 s, cnt = m, 0 while s: cnt += 1 s…
- A bitmask DP loops over every mask of n bits and, for each mask, over all of its submasks. What is the total number of (mask, submask)…