Data Structures & AlgorithmsVery hardProduct company OA
Counting palindromic substrings (by position) with centre expansion over 2n − 1 centres. What is printed?
Counting palindromic substrings (by position) with centre expansion over 2n − 1 centres. What is printed?
def pal(s):
c = 0
for center in range(2 * len(s) - 1):
l = center // 2; r = l + center % 2
while l >= 0 and r < len(s) and s[l] == s[r]: c += 1; l -= 1; r += 1
return c
print(pal("aabaa"), pal("abcba"), pal("aaaa"))- A. 9 5 10
- B. 7 7 10
- C. 9 7 6
- D. 9 7 10
Correct answer: D. 9 7 10
Each centre (a character or a gap) expands while the ends match, adding one palindrome per step. aabaa: 5 singles + 'aa' twice + 'aba' + 'aabaa' = 9. abcba: 5 + 'bcb' + 'abcba' = 7. aaaa: every substring is a palindrome, 4·5/2 = 10. Forgetting the even (gap) centres misses 'aa' and gives 7 for aabaa. O(n²) worst case; Manacher is O(n).
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- Sum over all subarrays of (max − min), computed as Σ max − Σ min with two monotonic-stack passes, checked against brute force. What is…
- Merging files costs the size of the result each time. Compare the greedy 'always merge the two smallest' (heap) with merging left to right…
- You must count pairs i < j with a[i] + a[j] ≤ T for n ≤ 2·10⁵ values up to 10⁹ in absolute value (time limit 1 s). Which plan passes?
- A service stores n = 10⁵ integer keys in a chained hash table with m = 1000 buckets and h(k) = k mod m. An attacker sends keys that are…
- An empty queue performs: enqueue 7, enqueue 2, enqueue 9, dequeue, enqueue 4, dequeue. Which element is now at the front?
- In a doubly linked list you are given a pointer to a node X somewhere in the middle. What is the time to delete X?