Distinct Short Palindromic Subsequences

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

You receive a lowercase ASCII string s ('a' through 'z'). Determine how many unique palindromic strings of lengths 2, 3, and 4 appear inside s as subsequences, and return those three counts in a 3-element integer list [c2, c3, c4].

  • A string p of length m is a subsequence of s when there exist strictly increasing positions 0 <= i_0 < i_1 < ... < i_{m - 1} < len(s) satisfying s[i_j] == p[j] for every 0 <= j < m.
  • A string p is a palindrome when reversing its characters leaves it unchanged (p == p[::-1]), such as "zz" (length 2), "zqz" or "zzz" (length 3), and "zqqz" or "zzzz" (length 4).
  • Deduplicate strictly by character sequence, never by index tuple: if several distinct index combinations spell the exact same palindrome text, include that text at most once in the count.

Implement count_distinct_palindromic_subsequences(s: str) -> List[int], where index 0 holds the count for length 2, index 1 holds the count for length 3, and index 2 holds the count for length 4.

Examples

Example 1

  • Input: s = "cat"
  • Output: [0, 0, 0]
  • Explanation: All three letters are distinct, so no matching pair of endpoints exists to build a palindrome of length 2, 3, or 4.

Example 2

  • Input: s = "xyzyx"
  • Output: [2, 3, 1]
  • Explanation: Length-2 palindromes are "xx" and "yy" (2). Length-3 palindromes are "xyx", "xzx", and "yzy" (3). Length-4 has only "xyyx" (1).

Example 3

  • Input: s = "koko"
  • Output: [2, 2, 0]
  • Explanation: Length 2 yields "kk" and "oo" (2), and length 3 yields "kok" and "oko" (2). Neither "kook" nor "okko" exists because only one 'o' lies between the two 'k's and only one 'k' lies between the two 'o's.

Example 4

  • Input: s = "mmnmm"
  • Output: [1, 2, 1]
  • Explanation: Six index pairs spell "mm", yet string deduplication counts "mm" once (1). Length 3 forms "mmm" and "mnm" (2), and length 4 forms "mmmm" (1).

Constraints

  • 0 <= len(s) <= 2 * 10^5
  • Every character in s is a lowercase English letter ('a'–'z').

Step-by-step walkthrough

  1. Understand subsequences, palindromes, and string deduplication

    We receive a lowercase string s and want to return [count_len_2, count_len_3, count_len_4], counting unique palindromic subsequences of lengths 2, 3, and 4:

    • A subsequence picks characters from strictly increasing indices in s, skipping any unwanted positions in between.
    • A palindrome reads identically forward and backward (such as "xx", "xyx", or "xyyx").
    • Unique strings means we count distinct character sequences rather than index combinations. In Example 4 (s = "mmnmm"), six different index pairs spell "mm", yet "mm" contributes just 1 to count_len_2.
  2. Why enumerating index combinations is too slow

    A naive loop inspects every pair, triple, and quadruple of indices in s, builds the 2-, 3-, or 4-letter string, checks word == word[::-1], and inserts matches into a set.

    In a string of length n, there are roughly n^4 / 24 index quadruples—already more than 40 billion quadruples at n = 1,000, and utterly hopeless at n = 100,000. Yet the alphabet only has 26 lowercase letters! Switching our viewpoint from picking indices to picking letter templates collapses the search space.

  3. Key insight 1: lengths 2, 3, and 4 follow fixed letter shapes

    Because a palindrome mirrors symmetrically around its midpoint, short palindromes leave at most two letter choices:

    • Length 2 ("xx"): both positions must hold the same outer letter x (at most 26 distinct strings).
    • Length 3 ("xyx"): positions 0 and 2 share an outer letter x, and position 1 holds any middle letter y, including y == x for "xxx" (at most 26 * 26 = 676 distinct strings).
    • Length 4 ("xyyx"): positions 0 and 3 share x, and positions 1 and 2 both hold the same middle letter y, including y == x for "xxxx" (at most 26 * 26 = 676 distinct strings).

    Two palindromes of the same length spell the exact same string if and only if they have the same (x, y) letters. Testing each distinct outer letter x and inner letter y once eliminates duplicate counting automatically!

  4. Key insight 2: always pick the widest span `(first_index[x], last_index[x])`

    Once we fix the outer letter x, which two occurrences of x in s should serve as the left and right bookends?

    Always choose the earliest occurrence first_index[x] and the latest occurrence last_index[x]. Every other pair of xs in s sits inside [first_index[x], last_index[x]], so any character enclosed by a narrower pair of xs is guaranteed to sit strictly inside (first_index[x], last_index[x]) too:

    Example: s = "m b m c m"
             idx  0 1 2 3 4
    
    Narrow neighboring pairs of 'm':
      (0, 2) -> inner slice "b"   (misses 'c' and 'm')
      (2, 4) -> inner slice "c"   (misses 'b' and 'm')
    
    Widest pair (first_index['m']=0, last_index['m']=4):
      (0, 4) -> inner slice "bmc" (captures 'b', 'm', AND 'c' -> "mbm", "mmm", "mcm"!)
    

    Inside that widest open interval (first_index[x], last_index[x]):

    • "xx" exists if and only if first_index[x] < last_index[x] (x occurs at least twice).
    • "xyx" exists if and only if y occurs at least 1 time strictly inside (first_index[x], last_index[x]).
    • "xyyx" exists if and only if y occurs at least 2 times strictly inside (first_index[x], last_index[x]).
  5. Step 1: record the first and last index of every letter

    One pass across s populates both maps: store first_index[ch] = idx the first time ch is seen, and update last_index[ch] = idx on every visit.

        # Phase 1: Record the earliest and latest index of every distinct character in s.
        # first_index: {char: earliest_idx}, e.g. {'x': 0, 'y': 1, 'z': 2} for s = "xyzyx"
        # last_index:  {char: latest_idx},   e.g. {'x': 4, 'y': 3, 'z': 2} for s = "xyzyx"
        first_index: Dict[str, int] = {}
        last_index: Dict[str, int] = {}
        for idx, ch in enumerate(s):
            if ch not in first_index:
                first_index[ch] = idx
            last_index[ch] = idx
    
  6. Step 2: count valid middle letters inside each outer window

    Iterate over each distinct outer_char recorded in first_index:

    1. Read left = first_index[outer_char] and right = last_index[outer_char]. When left == right, outer_char appears only once and cannot form bookends, so continue.
    2. Add 1 to count_len_2 for "xx".
    3. Build inside_counts = Counter(s[left + 1 : right]) over characters strictly between left and right.
    4. Add len(inside_counts) to count_len_3 (every distinct inner letter gives one "xyx"), and add 1 to count_len_4 for each inner letter whose frequency is >= 2 (forming "xyyx").

    Let's trace Example 2 (s = "xyzyx") and Example 3 (s = "koko"):

    Trace 1 (Example 2): s = "xyzyx" -> first_index={'x': 0, 'y': 1, 'z': 2}, last_index={'x': 4, 'y': 3, 'z': 2}
      outer 'x' (left=0, right=4):
        +1 len-2 ("xx")
        s[1:4] = "yzy" -> inside_counts = {'y': 2, 'z': 1}
        +2 len-3 ("xyx", "xzx"), +1 len-4 ("xyyx" since 'y' freq 2 >= 2)
      outer 'y' (left=1, right=3):
        +1 len-2 ("yy")
        s[2:3] = "z"   -> inside_counts = {'z': 1}
        +1 len-3 ("yzy"), +0 len-4
      outer 'z' (left=2, right=2): left == right -> skip
      Totals: [2, 3, 1]
    
    Trace 2 (Example 3): s = "koko" -> first_index={'k': 0, 'o': 1}, last_index={'k': 2, 'o': 3}
      outer 'k' (0, 2): s[1:2] = "o" -> {'o': 1} -> "kk", "kok" (only ONE 'o' inside, so no "kook"!)
      outer 'o' (1, 3): s[2:3] = "k" -> {'k': 1} -> "oo", "oko" (only ONE 'k' inside, so no "okko"!)
      Totals: [2, 2, 0]
    
        count_len_2 = 0  # Distinct palindromes of shape "xx"
        count_len_3 = 0  # Distinct palindromes of shape "xyx" (y == x allowed)
        count_len_4 = 0  # Distinct palindromes of shape "xyyx" (y == x allowed)
    
        # Phase 2: Fix each distinct outer letter x and inspect its widest span (left, right).
        # Pinning x to its first and last occurrence captures every possible middle character
        # without ever counting the same (x, y) palindrome string twice.
        for outer_char in first_index:
            left = first_index[outer_char]
            right = last_index[outer_char]
    
            # If left == right, outer_char appears only once and cannot form an outer pair "x...x".
            if left == right:
                continue
    
            # At least two copies of outer_char exist, forming the unique length-2 string "xx".
            count_len_2 += 1
    
            # inside_counts: {middle_char: frequency} strictly between left and right, s[left + 1 : right].
            inside_counts = Counter(s[left + 1 : right])
    
            # Every distinct middle_char appearing >= 1 time inside forms one unique "xyx".
            count_len_3 += len(inside_counts)
    
            # Every distinct middle_char appearing >= 2 times inside forms one unique "xyyx".
            for freq in inside_counts.values():
                if freq >= 2:
                    count_len_4 += 1
    
        return [count_len_2, count_len_3, count_len_4]
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    from collections import Counter
    
    
    def count_distinct_palindromic_subsequences(s: str) -> List[int]:
        # Phase 1: Record the earliest and latest index of every distinct character in s.
        # first_index: {char: earliest_idx}, e.g. {'x': 0, 'y': 1, 'z': 2} for s = "xyzyx"
        # last_index:  {char: latest_idx},   e.g. {'x': 4, 'y': 3, 'z': 2} for s = "xyzyx"
        first_index: Dict[str, int] = {}
        last_index: Dict[str, int] = {}
        for idx, ch in enumerate(s):
            if ch not in first_index:
                first_index[ch] = idx
            last_index[ch] = idx
    
        count_len_2 = 0  # Distinct palindromes of shape "xx"
        count_len_3 = 0  # Distinct palindromes of shape "xyx" (y == x allowed)
        count_len_4 = 0  # Distinct palindromes of shape "xyyx" (y == x allowed)
    
        # Phase 2: Fix each distinct outer letter x and inspect its widest span (left, right).
        # Pinning x to its first and last occurrence captures every possible middle character
        # without ever counting the same (x, y) palindrome string twice.
        for outer_char in first_index:
            left = first_index[outer_char]
            right = last_index[outer_char]
    
            # If left == right, outer_char appears only once and cannot form an outer pair "x...x".
            if left == right:
                continue
    
            # At least two copies of outer_char exist, forming the unique length-2 string "xx".
            count_len_2 += 1
    
            # inside_counts: {middle_char: frequency} strictly between left and right, s[left + 1 : right].
            inside_counts = Counter(s[left + 1 : right])
    
            # Every distinct middle_char appearing >= 1 time inside forms one unique "xyx".
            count_len_3 += len(inside_counts)
    
            # Every distinct middle_char appearing >= 2 times inside forms one unique "xyyx".
            for freq in inside_counts.values():
                if freq >= 2:
                    count_len_4 += 1
    
        return [count_len_2, count_len_3, count_len_4]
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

A subsequence picks characters from strictly increasing indices in s while skipping any unwanted positions, and a palindrome reads identically forward and backward. Think of assembling palindromes of lengths 2, 3, and 4 like setting two matching bookends x ... x on a bookshelf: length 2 is the bare pair "xx", length 3 places one book y between them ("xyx"), and length 4 places two identical books yy between them ("xyyx"). To maximize the choice of inner books for a given outer letter x, always push the two x bookends as wide apart as possible—using the earliest x and latest x in s—and tally which letters appear at least once (for "xyx") or at least twice (for "xyyx") strictly inside that span.

Enumerating every 2-, 3-, and 4-index tuple in s takes O(n^4) time, timing out once n reaches a few hundred characters while also requiring a hash set to filter duplicate strings. Conversely, inspecting only neighboring occurrences of x instead of (first_index[x], last_index[x]) misses valid middles—in "mbmcm", neighboring ms enclose "b" and "c" separately and overlook "mmm" altogether. Iterating over the at most 26 distinct outer letters once and counting inside (first_index[x], last_index[x]) achieves linear time with automatic deduplication.

Walk through Example 2 (s = "xyzyx"): 1. One pass records first_index = {'x': 0, 'y': 1, 'z': 2} and last_index = {'x': 4, 'y': 3, 'z': 2}. 2. Outer 'x' (0 to 4) adds "xx" to length 2; its interior s[1:4] = "yzy" has {'y': 2, 'z': 1}, adding "xyx" and "xzx" to length 3 plus "xyyx" to length 4. 3. Outer 'y' (1 to 3) adds "yy" to length 2 and "yzy" (s[2:3] = "z") to length 3, while 'z' (2 == 2) appears once and is skipped, giving [2, 3, 1].

Complexity

Let n be len(s) and A be the number of distinct characters in s (A <= 26 for lowercase ASCII letters).

  • Time: O(A * n), which simplifies to O(n) since A <= 26. One pass of n characters builds first_index and last_index, and at most 26 outer letters each scan an interior slice shorter than n.
  • Space: O(n) in Python as written because slicing s[left + 1 : right] allocates a temporary substring of up to n - 2 characters (first_index, last_index, and inside_counts each store at most 26 entries). Counting via an index loop for idx in range(left + 1, right) lowers extra space to O(A) (O(1)).

Edge cases

  • Empty or single-character string ("", "a"): Every seen letter has first_index == last_index, returning [0, 0, 0].
  • All letters distinct ("cat", "abcdef"): No letter repeats to form bookends, returning [0, 0, 0].
  • Single repeated letter: Three copies have interior length 1 ([1, 1, 0]), whereas four or more copies ("mmmm", "aaaaaaa") have at least two inner copies and return [1, 1, 1].
  • Inner letter equal to outer letter (y == x): "mmnmm" counts inner ms inside s[1:4] = "mnm" ({'m': 2, 'n': 1}), capturing "mmm" and "mnm" for length 3 and "mmmm" for length 4 ([1, 2, 1]).
  • Adjacent pairs with empty interior ("aabb"): Both 'a' (0..1) and 'b' (2..3) have empty slices between their endpoints, returning [2, 0, 0].

Common mistakes

  • Counting index combinations instead of unique strings: Returning 6 instead of 1 for length-2 palindromes in "mmnmm" because six index pairs spell "mm".
  • Checking adjacent occurrences of x instead of (first_index[x], last_index[x]): In "mbmcm", windows (0, 2) and (2, 4) miss the middle 'm' at index 2 and split repeated inner letters across windows.
  • Excluding y == x: Filtering outer_char out of inside_counts drops valid single-letter palindromes "xxx" and "xxxx".
  • Counting y across all of s instead of strictly inside (left, right): In Example 3 ("koko"), 'o' appears twice overall, yet only one 'o' sits between the two 'k's, so "kook" does not exist ([2, 2, 0]).
  • Allowing mismatched inner letters in length 4: A length-4 palindrome requires template "xyyx", never "xyzx"—the same inner letter y must appear at least twice inside (left, right).

Alternative approaches

  • Greedy subsequence test on all 1,378 templates: Generate every candidate "xx" (26), "xyx" (676), and "xyyx" (676) and scan s for each one in O(n) time. That takes O(A^2 * n) time—still linear in n for a fixed alphabet, though roughly 26x more work than scanning 26 outer spans.
  • 2D prefix-frequency table: Precompute prefix[c][i], the count of letter c in s[:i] (a prefix-sum array stores cumulative counts from index 0 so any range count is answered in O(1) by subtraction). Each inner letter's count in (left, right) is then prefix[y][right] - prefix[y][left + 1] in O(1), taking O(A * n + A^2) time total.

Follow-up questions

  • Suppose Q substring queries each give bounds (L, R) and ask for the [c2, c3, c4] counts restricted to s[L : R + 1]. How can you preprocess s to answer each query quickly? Build a 26 x (n + 1) prefix-frequency table alongside a sorted index list positions[c] per letter c in O(A * n) time. On query (L, R), run binary search (halving a sorted list to locate a boundary in O(log n) time) on positions[x] to find the earliest index left >= L and latest index right <= R for each outer letter x; whenever left < right, compute each inner letter's count inside (left, right) in O(1) via prefix subtraction, answering each query in O(A * log n + A^2) time.
  • How would you extend your template-and-window approach to also count unique palindromic subsequences of length 5? Every length-5 palindrome matches "xyzyx", uniquely keyed by (x, y, z). Pin outer x to (first_index[x], last_index[x]), then for each y use binary search on positions[y] to find its earliest index left_y > first_index[x] and latest index right_y < last_index[x]. Whenever left_y < right_y, every letter z with positive prefix-count difference inside (left_y, right_y) adds 1, running in O(A * n + A^2 * log n + A^3) time.
  • If the problem instead asked for the total number of distinct non-empty palindromic subsequences across every possible length (modulo 10^9 + 7), what algorithm would you use? Because total distinct palindromes can grow exponentially with n, use dynamic programming (tabulating answers to smaller subproblems so each is computed once) on intervals dp[i][j] representing the count of distinct non-empty palindromic subsequences inside s[i : j + 1]. Precomputing next_occ[i][c] and prev_occ[j][c] tables lets each state sum dp[lo + 1][hi - 1] + 2 (or + 1 when lo == hi) across each letter c present in s[i : j + 1] in O(A * n^2) time and O(n^2) space.

Follow-up questions

Similar questions

More Quora interview questions

All 2 Quora questions →