Count all palindromic substrings
Company: Reevo
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Take-home Project
Quick Answer: This question evaluates proficiency with string algorithms and algorithmic problem-solving, focusing on palindrome detection and counting contiguous substrings. It is commonly asked to assess implementation skills and the ability to reason about time and space complexity within the Coding & Algorithms domain, emphasizing practical application rather than purely conceptual understanding.
Constraints
- 1 <= |s| <= 2000
- s consists of lowercase (and/or any printable) characters
- An O(n^2) approach is acceptable
Examples
Input: "abc"
Expected Output: 3
Explanation: Each single character is a palindrome: "a", "b", "c". No longer substring is a palindrome.
Input: "aaa"
Expected Output: 6
Explanation: Three single chars ("a" x3), two "aa", and one "aaa" = 6.
Input: "a"
Expected Output: 1
Explanation: A single character is itself a palindrome.
Input: "aba"
Expected Output: 4
Explanation: "a", "b", "a", and "aba" = 4.
Input: "abba"
Expected Output: 6
Explanation: "a", "b", "b", "a", "bb", and "abba" = 6.
Input: "racecar"
Expected Output: 10
Explanation: 7 single chars, plus "cec", "aceca", "racecar" = 10.
Input: "zzzz"
Expected Output: 10
Explanation: 4 + 3 + 2 + 1 = 10 palindromic substrings of a run of identical characters.
Hints
- Every palindrome has a center. For a string of length n there are 2n-1 possible centers: n single-character centers (odd-length palindromes) and n-1 gaps between characters (even-length palindromes).
- From each center, expand outward with two pointers while the characters on both sides match; every successful expansion yields one more palindromic substring.
- This center-expansion runs in O(n^2) time and O(1) extra space, which fits the |s| <= 2000 constraint comfortably.