Data Structures & AlgorithmsVery hardGATE CS · DSA
Count palindromic substrings by expanding around all 2n − 1 centres, and also count DISTINCT palindromic substrings. What is printed?
Count palindromic substrings by expanding around all 2n − 1 centres, and also count DISTINCT palindromic substrings. What is printed?
s = "babbbbb"
cnt, seen = 0, 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]:
cnt += 1; seen.add(s[l:r + 1]); l -= 1; r += 1
print(cnt, len(seen))- A. 19 7
- B. 18 7
- C. 17 7
- D. 12 5
Correct answer: B. 18 7
Odd centres sit on characters and even centres between them; ignoring even centres misses palindromes like 'aa'. Output: 18 7.
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
- You need to sort 10⁷ integers, each in the range 0 to 999. Which approach is asymptotically fastest?
- Count pairs with a given difference k (k > 0) among DISTINCT values using a hash set. What is printed? python a, k = [8, 7, 7, 10, 5, 11…
- Why is a tombstone (a 'deleted' marker) used instead of emptying a slot when deleting from an open-addressing hash table?
- Which statement about using a hash set versus sorting to detect duplicates in an array of n integers is correct?
- Can a string become a palindrome by deleting at most one character? Two pointers try skipping either side on the first mismatch. What is…
- How many contiguous subarrays of [4, 3, 1, 7, 5, 7, 4, 3, 2, 1] contain exactly 2 odd numbers? (Use exactly(k) = atMost(k) − atMost(k − 1).)