TIC
The Interns Company

Palindromic Substrings

MediumAcceptance: 71.4%

Problem Statement

Given a string s, return the number of palindromic substrings in it. A string is a palindrome when it reads the same backward as forward. A substring is a contiguous sequence of characters within the string.

Constraints:

  • 1 <= s.length <= 1000
  • s consists of lowercase English letters

Input Format:

  • A string s

Output Format:

  • An integer representing the number of palindromic substrings

Examples:

Example 1:

Input:

s = "abc"

Output:

3

Explanation:

Three palindromic strings: "a", "b", "c".

Example 2:

Input:

s = "aaa"

Output:

6

Explanation:

Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".

Solutions

Expand Around Center

Time: O(n²)
Space: O(1)

Check each position as a potential center and count all palindromes.

Dynamic Programming

Time: O(n²)
Space: O(n²)

Use a 2D table to track whether each substring is a palindrome.

Algorithm Walkthrough

Example input:

Step-by-step execution:

  1. Input: s = "aaa"
  2. Initialize count = 0
  3. Iterate through each position:
  4. i = 0, character 'a':
  5. Odd center: expand(0,0):
  6. Palindrome 'a', count = 1
  7. Even center: expand(0,1):
  8. Palindrome 'aa', count = 2
  9. i = 1, character 'a':
  10. Odd center: expand(1,1):
  11. Palindrome 'a', count = 3
  12. Even center: expand(1,2):
  13. Palindrome 'aa', count = 4
  14. i = 2, character 'a':
  15. Odd center: expand(2,2):
  16. Palindrome 'a', count = 5
  17. Even center: expand(2,3): Out of bounds
  18. The entire string "aaa" is also a palindrome, found when expanding from position 1
  19. Total count = 6

Hints

Hint 1
Consider each position as a potential center of palindrome.
Hint 2
Expand around each center to count palindromes.
Hint 3
A palindrome can be centered at a character (odd length) or between characters (even length).

Video Tutorial

Video tutorials can be a great way to understand algorithms visually

Visualization

Visualize the expansion process around each center position and count all the palindromic substrings found.

Key visualization elements:

  • current center
  • expanding boundaries
  • found palindromes

Implementation Notes

Both approaches have the same time complexity, but the 'Expand Around Center' approach is generally preferred due to its simplicity and O(1) space complexity, compared to the O(n²) space complexity of the dynamic programming approach.