Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Count palindromic substrings (each occurrence counts separately).
Problem: Count palindromic substrings (each occurrence counts separately).
def count_pal(s):
n, c = len(s), 0
for center in range(2 * n - 1):
l, r = center // 2, center // 2 + center % 2
while l >= 0 and r < n and s[l] == s[r]:
c += 1; l -= 1; r += 1
return c
print(count_pal("abc"), count_pal("aaa"), count_pal("abba"))What is printed?- A. 3 6 6
- B. 3 3 6
- C. 3 6 4
- D. 1 6 6
Correct answer: A. 3 6 6
There are 2n − 1 centres (letters and gaps); expand while the ends match and count each step. "aaa": a, a, a, aa, aa, aaa = 6. "abba": 4 letters + bb + abba = 6. Counting distinct palindromes instead would give 3 for "aaa". O(n²).
More Coding Interview Problems questions
- Problem: Find the length of the longest arithmetic subsequence. python def longestap(a): dp = [{} for in a]; best = 1 for i in…
- Problem: Length of the longest strictly increasing subsequence with the O(n²) DP. cpp int lis(vector<int>& a) { vector<int> dp(a.size()…
- Problem: A hash table keyed by short strings uses Java's String.hashCode. Why do some keys collide? java // String.hashCode: h = 31h + c…
- Problem: Binary search on large indices in C++ (int is 32-bit). cpp int lo = 2000000000, hi = 2100000000; int bad = (lo + hi) / 2; //…
- Problem: Find the celebrity (known by all, knows nobody) with O(n) calls to knows(a, b). python M = [[0, 1, 1, 0], [0, 0, 1, 0], [0, 0, 0…
- Problem: Delete exactly one element from a binary array and return the longest run of 1s that can remain. python def afterdelete(a): l =…