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
pof lengthmis a subsequence ofswhen there exist strictly increasing positions0 <= i_0 < i_1 < ... < i_{m - 1} < len(s)satisfyings[i_j] == p[j]for every0 <= j < m. - A string
pis a palindrome when reversing its characters leaves it unchanged (p == p[::-1]), such as"zz"(length2),"zqz"or"zzz"(length3), and"zqqz"or"zzzz"(length4). - 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, or4.
Example 2
- Input:
s = "xyzyx" - Output:
[2, 3, 1] - Explanation: Length-
2palindromes are"xx"and"yy"(2). Length-3palindromes are"xyx","xzx", and"yzy"(3). Length-4has only"xyyx"(1).
Example 3
- Input:
s = "koko" - Output:
[2, 2, 0] - Explanation: Length
2yields"kk"and"oo"(2), and length3yields"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). Length3forms"mmm"and"mnm"(2), and length4forms"mmmm"(1).
Constraints
0 <= len(s) <= 2 * 10^5- Every character in
sis a lowercase English letter ('a'–'z').
Step-by-step walkthrough
Understand subsequences, palindromes, and string deduplication
We receive a lowercase string
sand want to return[count_len_2, count_len_3, count_len_4], counting unique palindromic subsequences of lengths2,3, and4:- 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 just1tocount_len_2.
- A subsequence picks characters from strictly increasing indices in
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, checksword == word[::-1], and inserts matches into aset.In a string of length
n, there are roughlyn^4 / 24index quadruples—already more than40billion quadruples atn = 1,000, and utterly hopeless atn = 100,000. Yet the alphabet only has 26 lowercase letters! Switching our viewpoint from picking indices to picking letter templates collapses the search space.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 letterx(at most26distinct strings). - Length 3 (
"xyx"): positions0and2share an outer letterx, and position1holds any middle lettery, includingy == xfor"xxx"(at most26 * 26 = 676distinct strings). - Length 4 (
"xyyx"): positions0and3sharex, and positions1and2both hold the same middle lettery, includingy == xfor"xxxx"(at most26 * 26 = 676distinct 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 letterxand inner letteryonce eliminates duplicate counting automatically!- Length 2 (
Key insight 2: always pick the widest span `(first_index[x], last_index[x])`
Once we fix the outer letter
x, which two occurrences ofxinsshould serve as the left and right bookends?Always choose the earliest occurrence
first_index[x]and the latest occurrencelast_index[x]. Every other pair ofxs inssits inside[first_index[x], last_index[x]], so any character enclosed by a narrower pair ofxs 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 iffirst_index[x] < last_index[x](xoccurs at least twice)."xyx"exists if and only ifyoccurs at least1time strictly inside(first_index[x], last_index[x])."xyyx"exists if and only ifyoccurs at least2times strictly inside(first_index[x], last_index[x]).
Step 1: record the first and last index of every letter
One pass across
spopulates both maps: storefirst_index[ch] = idxthe first timechis seen, and updatelast_index[ch] = idxon 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] = idxStep 2: count valid middle letters inside each outer window
Iterate over each distinct
outer_charrecorded infirst_index:- Read
left = first_index[outer_char]andright = last_index[outer_char]. Whenleft == right,outer_charappears only once and cannot form bookends, socontinue. - Add
1tocount_len_2for"xx". - Build
inside_counts = Counter(s[left + 1 : right])over characters strictly betweenleftandright. - Add
len(inside_counts)tocount_len_3(every distinct inner letter gives one"xyx"), and add1tocount_len_4for 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]- Read
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 toO(n)sinceA <= 26. One pass ofncharacters buildsfirst_indexandlast_index, and at most26outer letters each scan an interior slice shorter thann. - Space:
O(n)in Python as written because slicings[left + 1 : right]allocates a temporary substring of up ton - 2characters (first_index,last_index, andinside_countseach store at most26entries). Counting via an index loopfor idx in range(left + 1, right)lowers extra space toO(A)(O(1)).
Edge cases
- Empty or single-character string (
"","a"): Every seen letter hasfirst_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 innerms insides[1:4] = "mnm"({'m': 2, 'n': 1}), capturing"mmm"and"mnm"for length3and"mmmm"for length4([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
6instead of1for length-2palindromes in"mmnmm"because six index pairs spell"mm". - Checking adjacent occurrences of
xinstead of(first_index[x], last_index[x]): In"mbmcm", windows(0, 2)and(2, 4)miss the middle'm'at index2and split repeated inner letters across windows. - Excluding
y == x: Filteringouter_charout ofinside_countsdrops valid single-letter palindromes"xxx"and"xxxx". - Counting
yacross all ofsinstead 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-
4palindrome requires template"xyyx", never"xyzx"—the same inner letterymust appear at least twice inside(left, right).
Alternative approaches
- Greedy subsequence test on all
1,378templates: Generate every candidate"xx"(26),"xyx"(676), and"xyyx"(676) and scansfor each one inO(n)time. That takesO(A^2 * n)time—still linear innfor a fixed alphabet, though roughly26xmore work than scanning26outer spans. - 2D prefix-frequency table: Precompute
prefix[c][i], the count of lettercins[:i](a prefix-sum array stores cumulative counts from index0so any range count is answered inO(1)by subtraction). Each inner letter's count in(left, right)is thenprefix[y][right] - prefix[y][left + 1]inO(1), takingO(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 listpositions[c]per lettercinO(A * n)time. On query(L, R), run binary search (halving a sorted list to locate a boundary inO(log n)time) onpositions[x]to find the earliest indexleft >= Land latest indexright <= Rfor each outer letterx; wheneverleft < right, compute each inner letter's count inside(left, right)inO(1)via prefix subtraction, answering each query inO(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-
5palindrome matches"xyzyx", uniquely keyed by(x, y, z). Pin outerxto(first_index[x], last_index[x]), then for eachyuse binary search onpositions[y]to find its earliest indexleft_y > first_index[x]and latest indexright_y < last_index[x]. Wheneverleft_y < right_y, every letterzwith positive prefix-count difference inside(left_y, right_y)adds1, running inO(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 intervalsdp[i][j]representing the count of distinct non-empty palindromic subsequences insides[i : j + 1]. Precomputingnext_occ[i][c]andprev_occ[j][c]tables lets each state sumdp[lo + 1][hi - 1] + 2(or+ 1whenlo == hi) across each lettercpresent ins[i : j + 1]inO(A * n^2)time andO(n^2)space.
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?
- How would you extend your template-and-window approach to also count unique palindromic subsequences of length 5?
- 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?
Similar questions
- Evaluating a Standalone Post Composer Under Network Interference
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One