Skip to content
mlmentorship

Palindromic Substrings

Count each accepted center radius as a separate index range, then distinguish occurrence lists from unique palindrome text values.

Published · 14 min read ·Core ·Mixed

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Palindromic Substrings

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. A Python string text. Output. Return the number of nonempty palindromic substring occurrences. Rules. Different start/end ranges count separately, even when they contain identical text. Ranges must be contiguous. Use exact code-point equality without normalization or grapheme grouping. Leave the string unchanged. Empty input returns zero. Example. "aaa" returns 6: three one-character ranges, two "aa" ranges, and one "aaa" range. For "abc", return 3, one occurrence for each character.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Each accepted radius contributes one range. Equal text at different positions counts separately.

Problem trace

Equal palindrome text at different positions counts as separate occurrences

Input and goalCount every continuous palindrome in a string.
Initialize center sumFor aaa, the lazy sum has not consumed a center yet. Its accumulated total is zero.
ma0a1a2
inputaaarunningTotal0
Six distinct palindrome occurrences in aaa, using half-open intervals. Solid intervals have been counted at this checkpoint, 0 in total; dashed intervals have not. Equal text at distinct positions still represents different occurrences.COUNTED 0 / 6; intervals are [start,end)a0a1a2m0 [0,1)m0 [0,2)m1 [1,2)m1 [0,3)m1 [1,3)m2 [2,3)6 interval occurrences; only 3 distinct strings.
m
0
input
aaa
running total
0

Recognize it
The task counts contiguous palindrome occurrences, including equal text at different positions, so each center-radius pair should contribute separately.
Keep true
Each successful while iteration adds one new palindrome for that center and then expands one cell outward. Completed centers contribute disjoint occurrences because every palindrome has one unique center.
Reuse it
Map each combinatorial object to a unique center and radius, then count every successful expansion once; the same enumeration underlies longest-palindrome and palindrome-radius algorithms.
For aaa, the lazy sum has not consumed a center yet. Its accumulated total is zero. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why are there six palindromic occurrences in aaa but only three distinct palindrome strings?
Full interview answer 14 min read

Count every nonempty contiguous substring that reads the same forward and backward, including repeated occurrences.

Problem

Input. A Python string text.

Output. Return the number of nonempty palindromic substring occurrences.

Rules. Different start/end ranges count separately, even when they contain identical text. Ranges must be contiguous. Use exact code-point equality without normalization or grapheme grouping. Leave the string unchanged. Empty input returns zero.

Example. "aaa" returns 6: three one-character ranges, two "aa" ranges, and one "aaa" range. For "abc", return 3, one occurrence for each character.

Picture

Reuse center expansion. Only aggregation changes: add one for each accepted radius instead of retaining a longest range.

For aaa, report half-open ranges:

middleOdd-center rangesEven-center rangesNew occurrencesTotal
0[0,1) is a[0,2) is aa22
1[1,2) is a; [0,3) is aaa[1,3) is aa35
2[2,3) is aNone: right endpoint is outside16

Every palindromic range has one center and radius, so contributions are disjoint. The two aa ranges differ by position; a text set would incorrectly merge them for this task.

Inside expand, left/right are inclusive candidate endpoints. The guard certifies a palindrome before count += 1. Moving outward creates the next unchecked candidate. Each call returns its local count. The outer sum combines both center types lazily, without storing per-center results.

Problem trace

Equal palindrome text at different positions counts as separate occurrences

Worked example: count locations, not just distinct palindrome textsString aaa has three length-one, two length-two, and one length-three palindromic substrings. These are six occurrences, not three distinct strings.The same text at a different intervalis another occurrencea at 0a at 1a at 2[0,1)[1,2)[2,3)[0,2)[1,3)[0,3)Six start-end intervals; only threedistinct palindrome texts.
Read it this way: String aaa has three length-one, two length-two, and one length-three palindromic substrings. These are six occurrences, not three distinct strings. Why do the three one-character intervals count separately even though each contains a?
Reference drawing

Problem trace

Equal palindrome text at different positions counts as separate occurrences

Worked example: count locations, not just distinct palindrome textsString aaa has three length-one, two length-two, and one length-three palindromic substrings. These are six occurrences, not three distinct strings.The same text at a different intervalis another occurrencea at 0a at 1a at 2[0,1)[1,2)[2,3)[0,2)[1,3)[0,3)Six start-end intervals; only threedistinct palindrome texts.
Execution trace
Input and goalCount every continuous palindrome in a string.
Initialize center sumFor aaa, the lazy sum has not consumed a center yet. Its accumulated total is zero.
ma0a1a2
inputaaarunningTotal0
Six distinct palindrome occurrences in aaa, using half-open intervals. Solid intervals have been counted at this checkpoint, 0 in total; dashed intervals have not. Equal text at distinct positions still represents different occurrences.COUNTED 0 / 6; intervals are [start,end)a0a1a2m0 [0,1)m0 [0,2)m1 [1,2)m1 [0,3)m1 [1,3)m2 [2,3)6 interval occurrences; only 3 distinct strings.
m
0
input
aaa
running total
0

Recognize it
The task counts contiguous palindrome occurrences, including equal text at different positions, so each center-radius pair should contribute separately.
Keep true
Each successful while iteration adds one new palindrome for that center and then expands one cell outward. Completed centers contribute disjoint occurrences because every palindrome has one unique center.
Reuse it
Map each combinatorial object to a unique center and radius, then count every successful expansion once; the same enumeration underlies longest-palindrome and palindrome-radius algorithms.
For aaa, the lazy sum has not consumed a center yet. Its accumulated total is zero. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why are there six palindromic occurrences in aaa but only three distinct palindrome strings?
Read it this way: String aaa has three length-one, two length-two, and one length-three palindromic substrings. These are six occurrences, not three distinct strings. Why do the three one-character intervals count separately even though each contains a?

Code

def count_palindromic_substrings(text: str) -> int:
   def expand(left: int, right: int) -> int:
      count = 0
      while left >= 0 and right < len(text) and text[left] == text[right]:
         count += 1
         left -= 1
         right += 1
      return count

   return sum(
      expand(middle, middle) + expand(middle, middle + 1)
      for middle in range(len(text))
   )

Cost: worst-case comparisons and a constant number of auxiliary scalar slots. The count is at most ; scalar bit widths grow with . The source copies no substrings inside its loops.

Change the Output Identity

Start from count_palindromic_substrings. Keep both center types and their equality guard; change what an accepted radius saves.

  1. Return occurrence ranges.

    New task: Inspect or highlight every palindrome’s boundaries.

    Picture and change: Append [left,right+1] instead of incrementing a scalar. Different centers remain distinct occurrences.

    Code: Complete replacement, sorted by boundaries:

    def palindrome_occurrences(text):
       result = []
       for middle in range(len(text)):
          for left, right in ((middle, middle), (middle, middle + 1)):
             while left >= 0 and right < len(text) and text[left] == text[right]:
                result.append([left, right + 1])
                left -= 1
                right += 1
       return sorted(result)

    Check: aaa returns [[0,1],[0,2],[0,3],[1,2],[1,3],[2,3]].

    Use when: Positions are required. For occurrences, stored ranges take slots and sorting adds work beyond expansion.

  2. Count unique text values.

    New task: Equal palindrome text must count once, regardless of position.

    Picture and change: Insert the accepted slice into a set. This changes answer identity, not the center enumeration.

    Code: Complete replacement:

    def distinct_palindrome_count(text):
       distinct = set()
       for middle in range(len(text)):
          for left, right in ((middle, middle), (middle, middle + 1)):
             while left >= 0 and right < len(text) and text[left] == text[right]:
                distinct.add(text[left:right + 1])
                left -= 1
                right += 1
       return len(distinct)

    Check: aaa retains only a, aa, aaa, so returns three. Empty input returns zero.

    Use when: Unique content matters rather than occurrence positions. Copying and hashing every accepted slice can take total work. The set also retains text, so storage is not constant.

Rebuild the Counting Proof

Can two different centers produce the same occurrence range?

Answer: No. Its endpoints determine one midpoint and parity. Different centers can produce equal text at different positions.