Four Independent Coding Tasks
Medium · Coding & Algorithms · Software Engineer · Online Assessment
Problem Statement
Implement solve_four_coding_problems, a single entry point that evaluates four independent algorithmic subproblems and returns their integer results in a four-element list [ans_1, ans_2, ans_3, ans_4]:
def solve_four_coding_problems(
health_by_day: List[List[bool]],
s: str,
products: List[int],
m: int,
words: List[str],
) -> List[int]:
-
Longest unbroken fleet-uptime run (
health_by_day):health_by_day[d]records boolean status checks across a fleet of services on dayd. Daydqualifies as an all-clear day only when every status entry inhealth_by_day[d]isTrue. Computeans_1, the largest count of back-to-back all-clear days (0if no day qualifies orhealth_by_dayis empty). -
Minimum window spanning the string's alphabet (
s): Given a strings, letUbe the set of unique characters occurring anywhere ins. Computeans_2, the length of the shortest contiguous slice ofsin which every character ofUappears at least once (0whensis empty). -
Fewest distinct catalog IDs after
mremovals (products,m): Given an integer listproductsof item IDs and a removal quotam, each single removal discards one element fromproducts. After executing exactlymremovals, computeans_3, the smallest number of unique item IDs that can remain in the surviving elements. -
Word pairs rearrangeable into a palindrome (
words): Given a list of stringswords, count index pairs(i, j)satisfying0 <= i < j < len(words)whose concatenated multiset of characterswords[i] + words[j]can be reordered into a palindrome (including an empty string""). Return that count asans_4.
Examples
Example 1
- Input:
health_by_day = [[True, True], [False, True], [True, True], [True, True], [True, True], [True, False]]s = "xyyzyxwx"products = [10, 20, 10, 30, 20, 10],m = 2words = ["xy", "z", "x", "yz"]
- Output:
[3, 4, 2, 2] - Explanation:
- Subproblem 1: Days
2,3, and4each have all services reportingTrue, forming a longest contiguous run of3days. - Subproblem 2:
suses four unique letters{'w', 'x', 'y', 'z'}. The slices[3:7] = "zyxw"spans all four letters in length4. - Subproblem 3: Item counts are
{10: 3, 20: 2, 30: 1}. Removing the single30and one copy of20spendsm = 2removals and leaves two unique IDs (10and20). - Subproblem 4: Pair
(0, 2)combines"xy"and"x"into"xyx", and pair(1, 3)combines"z"and"yz"into"zyz". No other pair works, giving2.
- Subproblem 1: Days
Example 2
- Input:
health_by_day = [[False, True, True], [True, True, True], [True, True, True]]s = "mmnmm"products = [4, 4, 8, 9, 8, 4, 7],m = 3words = ["pp", "qq", "pq", "q"]
- Output:
[2, 2, 2, 4] - Explanation:
- Subproblem 1: Day
0has a failure, while days1and2are all-clear for a run of2. - Subproblem 2: Unique letters are
{'m', 'n'}, covered by"mn"(or"nm") of length2. - Subproblem 3: Counts are
{7: 1, 9: 1, 8: 2, 4: 3}. Spending3removals wipes out7(1),9(1), and one copy of8(1), leaving2unique IDs (4and8). - Subproblem 4: Valid index pairs are
(0, 1)("pqqp"),(0, 3)("pqp"),(1, 3)("qqq"), and(2, 3)("qpq"), totaling4.
- Subproblem 1: Day
Example 3
- Input:
health_by_day = [[True, False], [False, False]]s = "kkkk"products = [11, 22, 33],m = 3words = ["", "k", "m", "km"]
- Output:
[0, 1, 0, 4] - Explanation:
- Subproblem 1: Every day contains at least one
False, so the longest all-clear run is0. - Subproblem 2: Only
'k'appears ins, so any single-character slice has length1. - Subproblem 3: Removing all
3items leaves an empty list with0unique IDs. - Subproblem 4: Pairs
(0, 1)("k"),(0, 2)("m"),(1, 3)("kmk"), and(2, 3)("mkm") can each form a palindrome, giving4.
- Subproblem 1: Every day contains at least one
Constraints
0 <= len(health_by_day) <= 10^4, and the total number of boolean entries across all days is at most10^5.0 <= len(s) <= 10^50 <= len(products) <= 10^5and0 <= m <= len(products)0 <= len(words) <= 10^5, the sum of string lengths acrosswordsis at most10^5, andwordscontains at most26distinct characters (empty strings""may appear).
Step-by-step walkthrough
Break the function into four self-contained helpers
solve_four_coding_problemsbundles four unrelated algorithmic tasks into one wrapper returning[ans_1, ans_2, ans_3, ans_4]:- Unbroken fleet-uptime run: given
health_by_day[d][k], measure the longest contiguous run of days where every status entry isTrue. - Minimum alphabet-spanning window: given
s, find the shortest contiguous slice containing every unique character present ins. - Fewest surviving catalog IDs: given
productsandmsingle-item removals, minimize how many unique IDs survive. - Palindrome-permutable word pairs: given
words, count index pairsi < jwhose combined characters can be rearranged into a palindrome.
Writing one focused helper per subproblem keeps each state variable local and easy to verify on its own.
- Unbroken fleet-uptime run: given
Subproblem 1: Unbroken fleet-uptime run (running counter)
Trying every possible start day and scanning forward re-reads the same days repeatedly in
O(D^2 * S)time (forDdays andSservices). Instead, scan the days once from left to right with two integers:current_streak: how many consecutive all-clear days end on today. Ifall(day)isTrue, incrementcurrent_streakand updatebest_streak; if any check isFalse, resetcurrent_streak = 0.- Updating
best_streakon every passing day (rather than only when a failure occurs) ensures a run that reaches the final day is never missed.
Example 1: health_by_day = [[T, T], [F, T], [T, T], [T, T], [T, T], [T, F]] Day 0: all(day) = True -> current_streak = 1, best_streak = 1 Day 1: all(day) = False -> current_streak = 0, best_streak = 1 Day 2: all(day) = True -> current_streak = 1, best_streak = 1 Day 3: all(day) = True -> current_streak = 2, best_streak = 2 Day 4: all(day) = True -> current_streak = 3, best_streak = 3 Day 5: all(day) = False -> current_streak = 0, best_streak = 3 --> returns 3def longest_healthy_streak(health_by_day: List[List[bool]]) -> int: """Task 1: Return the maximum number of consecutive days where every service passed.""" best_streak = 0 # current_streak: number of consecutive all-healthy days ending on the day just scanned current_streak = 0 for day in health_by_day: if all(day): current_streak += 1 # Update best_streak immediately so a streak reaching the final day is still recorded. if current_streak > best_streak: best_streak = current_streak else: # Any single False in `day` breaks the consecutive streak. current_streak = 0 return best_streakSubproblem 2: Minimum window spanning the alphabet of `s` (sliding window)
Checking all
O(n^2)slices takesO(n^3)time. Notice instead that onces[left : right + 1]already covers every unique character ofs, extendingrightfurther cannot make that slice shorter — we want to advanceleftto trim extra duplicate letters off the front!This gives a two-pointer sliding window:
- First compute
required_distinct = len(set(s))(returning0immediately ifsis empty). - Advance
rightfrom0tolen(s) - 1, addings[right]towindow_counts. Whenever a character's count inside the window rises from0to1, incrementcovered_distinct. - As long as
covered_distinct == required_distinct, recordright - left + 1againstshortest_lenand pops[left]by incrementingleft(decrementingcovered_distinctif its count hits0).
Trace on Example 1: s = "xyyzyxwx" (required_distinct = 4 for {'w', 'x', 'y', 'z'}): right = 0..5 ("xyyzyx"): covered_distinct = 3 ('w' has not appeared yet) right = 6 ('w'): window [0..6] = "xyyzyxw" covers all 4! shrink left -> [1..6] "yyzyxw" -> [2..6] "yzyxw" -> [3..6] "zyxw" (len 4, all 4 present!) pop 'z' at 3 -> [4..6] "yxw" lacks 'z' (covered_distinct = 3) -> stop shrinking. right = 7 ('x'): window [4..7] = "yxwx" still lacks 'z'. Shortest = 4.def shortest_covering_substring(s: str) -> int: """Task 2: Return the shortest substring length containing all distinct characters of s.""" required_distinct = len(set(s)) if required_distinct == 0: return 0 # window_counts: char -> occurrences inside current window s[left : right + 1], e.g. {'a': 2, 'b': 1} window_counts: Dict[str, int] = {} # covered_distinct: count of unique characters currently having window_counts[ch] >= 1 covered_distinct = 0 shortest_len = len(s) left = 0 # Phase 1: Expand `right` one character at a time until all distinct characters are covered. for right in range(len(s)): right_char = s[right] window_counts[right_char] = window_counts.get(right_char, 0) + 1 if window_counts[right_char] == 1: covered_distinct += 1 # Phase 2: Shrink `left` while the window still covers every distinct character. while covered_distinct == required_distinct: # Record length BEFORE popping s[left], while the window is guaranteed valid. window_len = right - left + 1 if window_len < shortest_len: shortest_len = window_len left_char = s[left] window_counts[left_char] -= 1 if window_counts[left_char] == 0: covered_distinct -= 1 left += 1 return shortest_len- First compute
Subproblem 3: Fewest surviving catalog IDs (greedy sorting)
An item ID vanishes only when every single copy of that ID is removed. So if ID
30appears1time and ID10appears3times, spending1removal on ID30eliminates a whole unique ID, whereas spending1removal on ID10eliminates none!To wipe out the maximum number of unique IDs within
mremovals, greedily clear out the rarest IDs first:- Count each item ID's occurrences in
freq_by_id. - Sort the occurrence counts from smallest to largest in
group_sizes. - Subtract each
sizefrombudgetwhilesize <= budget, decrementingremaining_distinctby1per wiped-out group.
What if
budget > 0is left over when the loop stops (saybudget = 1, nextsize = 2)? Becausebudget < size, those leftover removals simply deletebudgetcopies from that next group — at least1copy of that ID still survives, soremaining_distinctstays exact for exactmremovals!Example 1: products = [10, 20, 10, 30, 20, 10], m = 2 freq_by_id = {10: 3, 20: 2, 30: 1} group_sizes = [1, 2, 3], remaining_distinct = 3, budget = 2 - size = 1 <= 2: wipe out ID 30 -> budget = 1, remaining_distinct = 2 - size = 2 > 1: stop! (1 leftover removal deletes one copy of ID 20, leaving [10, 10, 10, 20] -> 2 IDs)def min_distinct_after_deletions(products: List[int], m: int) -> int: """Task 3: Return the fewest distinct product IDs remaining after deleting m items.""" # freq_by_id: product_id -> total occurrences, e.g. {1: 2, 2: 2, 3: 1} freq_by_id: Dict[int, int] = {} for product in products: freq_by_id[product] = freq_by_id.get(product, 0) + 1 # group_sizes: ascending list of occurrence counts, e.g. [1, 2, 2] group_sizes = sorted(freq_by_id.values()) remaining_distinct = len(group_sizes) budget = m # Wipe out the smallest groups first to eliminate as many distinct IDs as possible. # Any leftover budget (< next group's size) partially shrinks a surviving group without removing it. for size in group_sizes: if size > budget: break budget -= size remaining_distinct -= 1 return remaining_distinct- Count each item ID's occurrences in
Subproblem 4: Palindrome-permutable word pairs (parity bitmasks and XOR)
When can a multiset of letters be permuted into a palindrome? Every letter on the left half needs a matching twin on the right half, plus at most one solo letter can sit in the exact center (for odd-length palindromes like
"xyx"). That means at most one character may have an odd total count!Notice we do not care whether
'x'appears2,4, or100times — only whether its count is even (0) or odd (1). We pack those even/odd flags into an integer bitmask by assigning each distinct character its own bit position0, 1, 2, ...:- Flipping bit
bwith XOR (mask ^= 1 << b) toggles0 -> 1(odd) and1 -> 0(back to even) as we scan a word. - When two words combine, adding counts combines parities via XOR (
mask_i ^ mask_j)! A pair(i, j)can form a palindrome precisely whenmask_i ^ mask_jhas 0 bits set or 1 bit set:0bits set:mask_i == mask_j(every combined letter count is even).1bit set:mask_i == mask_j ^ (1 << bit)for some character bit (exactly one letter count is odd).
Scanning
wordsleft to right and keepingmask_counts[mask]for earlier words lets us count all valid partnersi < jinA + 1hash-map lookups per word (whereAis the alphabet size):Example 1: words = ["xy", "z", "x", "yz"] with bit positions: 'x'->0 (1), 'y'->1 (2), 'z'->2 (4) j=0, "xy": mask = 1 ^ 2 = 3 (0b011). mask_counts is empty -> +0 pairs. Record mask_counts[3] = 1. j=1, "z": mask = 4 (0b100). Look up 4, 5, 6, 0 -> +0 pairs. Record mask_counts[4] = 1. j=2, "x": mask = 1 (0b001). Look up 1, 0, 3, 5 -> mask_counts[3] = 1 ("xy" + "x" -> "xyx"). Record mask_counts[1] = 1. j=3, "yz": mask = 2 ^ 4 = 6 (0b110). Look up 6, 7, 4, 2 -> mask_counts[4] = 1 ("z" + "yz" -> "zyz"). Record mask_counts[6] = 1. Total pair_count = 2.def count_palindrome_pairs(words: List[str]) -> int: """Task 4: Count index pairs i < j whose combined characters can form a palindrome.""" # bit_index: char -> unique bit position 0..A-1, e.g. {'a': 0, 'b': 1, 'c': 2} bit_index: Dict[str, int] = {} for word in words: for ch in word: if ch not in bit_index: bit_index[ch] = len(bit_index) # mask_counts: parity bitmask -> count of earlier words (indices < j) having that mask mask_counts: Dict[int, int] = {} pair_count = 0 for word in words: # Build parity mask: bit k is 1 if character k appears an odd number of times in `word`. mask = 0 for ch in word: mask ^= 1 << bit_index[ch] # Case 1 (even-length palindrome): partner has the exact same mask -> 0 odd counts combined. pair_count += mask_counts.get(mask, 0) # Case 2 (odd-length palindrome): partner differs in 1 bit -> 1 odd center character combined. for bit in range(len(bit_index)): partner_mask = mask ^ (1 << bit) pair_count += mask_counts.get(partner_mask, 0) # Record `mask` AFTER querying so we only count pairs i < j and never pair a word with itself. mask_counts[mask] = mask_counts.get(mask, 0) + 1 return pair_count- Flipping bit
Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def longest_healthy_streak(health_by_day: List[List[bool]]) -> int: """Task 1: Return the maximum number of consecutive days where every service passed.""" best_streak = 0 # current_streak: number of consecutive all-healthy days ending on the day just scanned current_streak = 0 for day in health_by_day: if all(day): current_streak += 1 # Update best_streak immediately so a streak reaching the final day is still recorded. if current_streak > best_streak: best_streak = current_streak else: # Any single False in `day` breaks the consecutive streak. current_streak = 0 return best_streak def shortest_covering_substring(s: str) -> int: """Task 2: Return the shortest substring length containing all distinct characters of s.""" required_distinct = len(set(s)) if required_distinct == 0: return 0 # window_counts: char -> occurrences inside current window s[left : right + 1], e.g. {'a': 2, 'b': 1} window_counts: Dict[str, int] = {} # covered_distinct: count of unique characters currently having window_counts[ch] >= 1 covered_distinct = 0 shortest_len = len(s) left = 0 # Phase 1: Expand `right` one character at a time until all distinct characters are covered. for right in range(len(s)): right_char = s[right] window_counts[right_char] = window_counts.get(right_char, 0) + 1 if window_counts[right_char] == 1: covered_distinct += 1 # Phase 2: Shrink `left` while the window still covers every distinct character. while covered_distinct == required_distinct: # Record length BEFORE popping s[left], while the window is guaranteed valid. window_len = right - left + 1 if window_len < shortest_len: shortest_len = window_len left_char = s[left] window_counts[left_char] -= 1 if window_counts[left_char] == 0: covered_distinct -= 1 left += 1 return shortest_len def min_distinct_after_deletions(products: List[int], m: int) -> int: """Task 3: Return the fewest distinct product IDs remaining after deleting m items.""" # freq_by_id: product_id -> total occurrences, e.g. {1: 2, 2: 2, 3: 1} freq_by_id: Dict[int, int] = {} for product in products: freq_by_id[product] = freq_by_id.get(product, 0) + 1 # group_sizes: ascending list of occurrence counts, e.g. [1, 2, 2] group_sizes = sorted(freq_by_id.values()) remaining_distinct = len(group_sizes) budget = m # Wipe out the smallest groups first to eliminate as many distinct IDs as possible. # Any leftover budget (< next group's size) partially shrinks a surviving group without removing it. for size in group_sizes: if size > budget: break budget -= size remaining_distinct -= 1 return remaining_distinct def count_palindrome_pairs(words: List[str]) -> int: """Task 4: Count index pairs i < j whose combined characters can form a palindrome.""" # bit_index: char -> unique bit position 0..A-1, e.g. {'a': 0, 'b': 1, 'c': 2} bit_index: Dict[str, int] = {} for word in words: for ch in word: if ch not in bit_index: bit_index[ch] = len(bit_index) # mask_counts: parity bitmask -> count of earlier words (indices < j) having that mask mask_counts: Dict[int, int] = {} pair_count = 0 for word in words: # Build parity mask: bit k is 1 if character k appears an odd number of times in `word`. mask = 0 for ch in word: mask ^= 1 << bit_index[ch] # Case 1 (even-length palindrome): partner has the exact same mask -> 0 odd counts combined. pair_count += mask_counts.get(mask, 0) # Case 2 (odd-length palindrome): partner differs in 1 bit -> 1 odd center character combined. for bit in range(len(bit_index)): partner_mask = mask ^ (1 << bit) pair_count += mask_counts.get(partner_mask, 0) # Record `mask` AFTER querying so we only count pairs i < j and never pair a word with itself. mask_counts[mask] = mask_counts.get(mask, 0) + 1 return pair_count def solve_four_coding_problems( health_by_day: List[List[bool]], s: str, products: List[int], m: int, words: List[str], ) -> List[int]: return [ longest_healthy_streak(health_by_day), shortest_covering_substring(s), min_distinct_after_deletions(products, m), count_palindrome_pairs(words), ]✅ Submit now — all tests should pass.
Intuition & how it works
Each of the four subproblems looks like a nested search at first glance, yet all four collapse into one clean pass (or a quick sort) once you keep only the exact summary information each task cares about:
- Running counter (Subproblem 1): Like marking an unbroken daily run on a wall calendar, each day where every status check is
Trueadds1tocurrent_streak, and any failed day resets it to0. - Sliding window (Subproblem 2): A sliding window is a movable
[left, right]slice whererightsteps forward to gather missing characters andleftsteps forward to shed redundant duplicate characters from the front. - Greedy group removal (Subproblem 3): A greedy algorithm makes the locally cheapest move at each step — like clearing out the smallest moving boxes first when you can carry away only
mitems and want the fewest boxes left behind. - Parity bitmask with XOR (Subproblem 4): Permuting letters into a palindrome requires mirrored pairs with at most one solo middle character, so only each letter's parity (whether its count is even or odd) matters. Packing those
0/1parity flags into an integer bitmask (an integer where each bit position stores one boolean flag) lets us toggle parities with bitwise XOR (^) (an operation where matching bits cancel to0and differing bits produce1) and find every valid partner inO(1)hash-map lookups.
Why do the naive approaches fall short? Re-scanning runs from every start day wastes O(D^2 * S) checks, testing every slice of s takes O(n^3) time, enumerating m-element removal subsets grows exponentially, and concatenating all O(W^2) word pairs is quadratic in the number of words. Replacing nested loops with running state brings all four subproblems down to linear or O(d log d) time.
Here is how Example 2 (health_by_day = [[F,T,T],[T,T,T],[T,T,T]], s = "mmnmm", products = [4,4,8,9,8,4,7], m = 3, words = ["pp","qq","pq","q"]) works across all four helpers:
Subproblem 1 (Uptime): [F,T,T] -> 0, [T,T,T] -> 1, [T,T,T] -> 2 --> 2
Subproblem 2 (Window): "mmnmm" needs {'m','n'}; slice "mn" (idx 1..2) --> 2
Subproblem 3 (Remove): counts {7:1, 9:1, 8:2, 4:3}, sorted [1,1,2,3], m = 3:
wipe 7 (rem 2), wipe 9 (rem 1), trim one 8 --> 2 IDs left (4 and 8)
Subproblem 4 (Pairs): masks ('p'=bit0, 'q'=bit1):
"pp"->0, "qq"->0, "pq"->3, "q"->2
(0,1)=0^0=0, (0,3)=0^2=2, (1,3)=0^2=2, (2,3)=3^2=1 --> 4 pairs
Complexity
- Subproblem 1 (
longest_healthy_streak) — TimeO(D * S), SpaceO(1): forDdays andSstatus entries per day, we scan each day once andall(day)inspects at mostSbooleans, storing only two integer counters. - Subproblem 2 (
shortest_covering_substring) — TimeO(n), SpaceO(k): forn = len(s)andkunique characters ins,rightadvancesntimes andleftadvances at mostntimes (O(1)average hash-map updates per step), whilewindow_countsstores at mostkkeys. - Subproblem 3 (
min_distinct_after_deletions) — TimeO(P + d log d), SpaceO(d): forP = len(products)items anddunique catalog IDs, counting frequencies scans allPitems once, sortinggroup_sizestakesO(d log d), andfreq_by_idplusgroup_sizesstoredintegers. - Subproblem 4 (
count_palindrome_pairs) — TimeO(L + W * A), SpaceO(W + A): forW = len(words), total character lengthLacross all words, andAunique characters appearing inwords(at most26for lowercase English letters, fitting in one machine word), building all masks scansLcharacters total and each word performsA + 1dictionary lookups inmask_counts, which holds at mostWdistinct masks.
Edge cases
- Empty inputs (
[],"",[]withm = 0,[]): all four helpers cleanly return0. - Subproblem 1 — run ending on the last day or zero passing days: updating
best_streakinsideif all(day):captures runs that never hit a trailingFalse, and all-Falseschedules return0. An empty list[]on a day evaluatesall([]) == True(vacuously all zero checks passed). - Subproblem 2 — single repeated character (
"kkkk"):required_distinct == 1, so the window immediately shrinks to length1. - Subproblem 3 —
m = 0orm = len(products):m = 0breaks on the first group and returnsd;m = len(products)removes every group and returns0. Leftover budget smaller than the next group's size removes copies from that surviving group without changingremaining_distinct. - Subproblem 4 — empty strings and duplicate words:
""has mask0, so["", ""]has0 ^ 0 = 0(1pair, forming the empty palindrome""), and""pairs with"k"(0 ^ 1 = 1). Duplicate words like["xy", "xy", "xy"]share the same mask and yield0 + 1 + 2 = 3pairs.
Common mistakes
- Subproblem 1: updating
best_streakonly inside theelsebranch, which misses the longest run whenever the final day is all-clear. - Subproblem 2: computing
right - left + 1after incrementingleft(off-by-one error), or checkinglen(window_counts) == required_distinctwithout deleting zero-count keys fromwindow_counts. - Subproblem 3: removing from the largest groups instead of the smallest, or computing
d - mas if every single-item removal eliminated an entire catalog ID. - Subproblem 4: checking whether
words[i] + words[j]is already a palindrome without reordering; forgetting Case 1 (mask == mask, even-length palindromes); or insertingmaskintomask_countsbefore querying, which pairs a word with itself (i == j).
Alternative approaches
- Subproblem 3 in strictly
O(P)linear time: because every group size lies between1andP, counting sort (bucketing group sizes into an arraybuckets[1..P]instead of comparison sorting) avoids theO(d log d)sort and runs inO(P)time and space. - Subproblem 4 with tuple keys: storing a 26-tuple of
0/1parities as the dictionary key works without bit manipulation, though hashing and flipping 26-tuples adds a larger constant factor than single-integer XOR.
Follow-up questions
- What changes in Subproblem 1 if daily check batches arrive continuously from an unbounded stream? The exact same logic already acts as a streaming algorithm (processing one batch at a time without storing historical days): maintain just the two integers
current_streakandbest_streakinO(1)persistent memory, updating them as each day's boolean batch arrives so the running maximum is always ready inO(1)time. - How would Subproblem 2 adapt if you needed the shortest substring covering a target multiset t (including character multiplicities)? Build a
target_countsdictionary fromtand setrequired_distinct = len(target_counts). During the sliding window overs, incrementcovered_distinctonly whenwindow_counts[ch] == target_counts[ch]and decrement it whenwindow_counts[ch]drops belowtarget_counts[ch]; ifcovered_distinctnever reachesrequired_distinct, no valid substring exists, and both timeO(len(s) + len(t))and spaceO(k)stay linear. - How would you solve Subproblem 4 if concatenating words[i] + words[j] had to form a palindrome directly without rearranging letters? Character order now matters, so parity bitmasks no longer apply. Instead, store reversed words in a hash map (
rev_word -> indices); for each word and each split point dividing it intoprefix + suffix, ifprefixis already a palindrome then prependingreverse(suffix)forms a palindrome (and symmetrically appendingreverse(prefix)whensuffixis a palindrome), solving unordered ordered pairs inO(W * K^2)time for words of maximum lengthK.
Follow-up questions
- What changes in Subproblem 1 if daily check batches arrive continuously from an unbounded stream?
- How would Subproblem 2 adapt if you needed the shortest substring covering a target multiset t (including character multiplicities)?
- How would you solve Subproblem 4 if concatenating words[i] + words[j] had to form a palindrome directly without rearranging letters?
Similar questions
- 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
- Increment Digit Array