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 = "bbababa"
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. 13 6
- B. 14 9
- C. 14 7
- D. 14 8
Correct answer: C. 14 7
Odd centres sit on characters and even centres between them; ignoring even centres misses palindromes like 'aa'. Output: 14 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
- Top-down merge sort (split at mid = n // 2, recurse, then merge, stopping comparisons when one side runs out) sorts [33, 53, 13, 42, 11…
- Assertion (A): Removing duplicates from a sorted array can be done in place in O(n) time with two pointers. Reason (R): In a sorted array…
- Assertion (A): Quick sort with the last element as pivot takes Θ(n²) time on an array that is already sorted. Reason (R): On sorted input…
- A Python 2-D list is created two ways and one cell is set. What is printed? python a = [[0] 3] 3 b = [[0] 3 for in range(3)] a[2][2] = 5…
- Rearrange a linked list so that nodes at odd POSITIONS (1st, 3rd, …) come first, followed by the even-position nodes, keeping relative…
- What is the length of the longest contiguous substring of ((()((()(()) that is a valid (balanced) parentheses string?