Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Count DISTINCT palindromic substrings by expanding around centres and collecting them in a set.
Problem: Count DISTINCT palindromic substrings by expanding around centres and collecting them in a set.
def distinct_pal(s):
seen = set()
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]:
seen.add(s[l:r+1]); l -= 1; r += 1
return len(seen)
print(distinct_pal("abaaa"))What is printed?- A. 9
- B. 5
- C. 7
- D. 4
Correct answer: B. 5
Palindromes by position: a (×4), b, aba, aa (×2), aaa: 9 occurrences. Distinct strings: a, b, aba, aa, aaa = 5. Counting positions instead of distinct strings is the usual mix-up.
More Coding Interview Problems questions
- Problem: Build the suffix array of a string (start indices of suffixes in sorted order) and its LCP array (Kasai's algorithm). python def…
- Problem: A Fenwick tree over a DIFFERENCE array supports 'add v to a[l..r]' and 'read a[i]' in O(log n) (1-indexed, all zeros initially)…
- Problem: Point-update / range-maximum segment tree (iterative, size n = 8). python n = 8; t = [0] (2 n) def upd(i, v): i += n; t[i] = v…
- Mo's algorithm answers q offline range queries on an array of n elements by sorting queries into √n-sized blocks of their left ends. If…
- Problem: Edges arrive one by one; report the first edge that creates an ODD cycle (making the graph non-bipartite), using union-find with…
- Problem: Total weight of a MAXIMUM spanning tree (Kruskal with edges sorted in decreasing order). python edges =…