Data Structures & AlgorithmsModerateTCS NQT · string counting
Problem: How many palindromic substrings of length at least 1 does 'abcba' contain? Run the code.
Problem: How many palindromic substrings of length at least 1 does 'abcba' contain? Run the code.
s = 'abcba' print(sum(1 for i in range(len(s)) for j in range(i + 1, len(s) + 1) if s[i:j] == s[i:j][::-1]))What is printed?
- A. 5
- B. 12
- C. 2
- D. 7
Correct answer: D. 7
The 5 single letters, 'bcb' and 'abcba' give 7 palindromic substrings. Stopping j at len(s) misses the substrings ending at the last character (5), starting j at i also counts 5 empty slices (12), and skipping single letters gives 2.
More Coding Interview Problems questions
- Problem: What is the smallest positive integer whose decimal digits multiply to 36? Run the search code. python x = 1 while True: p = 1…
- Problem: How many ways are there to place 2 non-attacking rooks on a 3 x 3 board (distinct squares, different rows and different columns…
- Problem: How many monotone lattice paths from (0,0) to (2,2) exist on a 3 x 3 grid if the moves are right, down or diagonal (down-right)?…
- Problem: What is the sum of i (5 - i) for i from 1 to 4? Run the code. python print(sum(i (5 - i) for i in range(1, 5))) What is printed?
- Problem: What is the sum of gcd(i, j) over all pairs 1 <= i < j <= 4? Run the code. python from math import gcd print(sum(gcd(i, j) for i…
- Problem: What is the digit sum of 2^100? Run the code. python print(sum(int(c) for c in str(2 100))) What is printed?