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]:
  1. Longest unbroken fleet-uptime run (health_by_day): health_by_day[d] records boolean status checks across a fleet of services on day d. Day d qualifies as an all-clear day only when every status entry in health_by_day[d] is True. Compute ans_1, the largest count of back-to-back all-clear days (0 if no day qualifies or health_by_day is empty).

  2. Minimum window spanning the string's alphabet (s): Given a string s, let U be the set of unique characters occurring anywhere in s. Compute ans_2, the length of the shortest contiguous slice of s in which every character of U appears at least once (0 when s is empty).

  3. Fewest distinct catalog IDs after m removals (products, m): Given an integer list products of item IDs and a removal quota m, each single removal discards one element from products. After executing exactly m removals, compute ans_3, the smallest number of unique item IDs that can remain in the surviving elements.

  4. Word pairs rearrangeable into a palindrome (words): Given a list of strings words, count index pairs (i, j) satisfying 0 <= i < j < len(words) whose concatenated multiset of characters words[i] + words[j] can be reordered into a palindrome (including an empty string ""). Return that count as ans_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 = 2
    • words = ["xy", "z", "x", "yz"]
  • Output: [3, 4, 2, 2]
  • Explanation:
    • Subproblem 1: Days 2, 3, and 4 each have all services reporting True, forming a longest contiguous run of 3 days.
    • Subproblem 2: s uses four unique letters {'w', 'x', 'y', 'z'}. The slice s[3:7] = "zyxw" spans all four letters in length 4.
    • Subproblem 3: Item counts are {10: 3, 20: 2, 30: 1}. Removing the single 30 and one copy of 20 spends m = 2 removals and leaves two unique IDs (10 and 20).
    • 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, giving 2.

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 = 3
    • words = ["pp", "qq", "pq", "q"]
  • Output: [2, 2, 2, 4]
  • Explanation:
    • Subproblem 1: Day 0 has a failure, while days 1 and 2 are all-clear for a run of 2.
    • Subproblem 2: Unique letters are {'m', 'n'}, covered by "mn" (or "nm") of length 2.
    • Subproblem 3: Counts are {7: 1, 9: 1, 8: 2, 4: 3}. Spending 3 removals wipes out 7 (1), 9 (1), and one copy of 8 (1), leaving 2 unique IDs (4 and 8).
    • Subproblem 4: Valid index pairs are (0, 1) ("pqqp"), (0, 3) ("pqp"), (1, 3) ("qqq"), and (2, 3) ("qpq"), totaling 4.

Example 3

  • Input:
    • health_by_day = [[True, False], [False, False]]
    • s = "kkkk"
    • products = [11, 22, 33], m = 3
    • words = ["", "k", "m", "km"]
  • Output: [0, 1, 0, 4]
  • Explanation:
    • Subproblem 1: Every day contains at least one False, so the longest all-clear run is 0.
    • Subproblem 2: Only 'k' appears in s, so any single-character slice has length 1.
    • Subproblem 3: Removing all 3 items leaves an empty list with 0 unique IDs.
    • Subproblem 4: Pairs (0, 1) ("k"), (0, 2) ("m"), (1, 3) ("kmk"), and (2, 3) ("mkm") can each form a palindrome, giving 4.

Constraints

  • 0 <= len(health_by_day) <= 10^4, and the total number of boolean entries across all days is at most 10^5.
  • 0 <= len(s) <= 10^5
  • 0 <= len(products) <= 10^5 and 0 <= m <= len(products)
  • 0 <= len(words) <= 10^5, the sum of string lengths across words is at most 10^5, and words contains at most 26 distinct characters (empty strings "" may appear).

Step-by-step walkthrough

  1. Break the function into four self-contained helpers

    solve_four_coding_problems bundles four unrelated algorithmic tasks into one wrapper returning [ans_1, ans_2, ans_3, ans_4]:

    1. Unbroken fleet-uptime run: given health_by_day[d][k], measure the longest contiguous run of days where every status entry is True.
    2. Minimum alphabet-spanning window: given s, find the shortest contiguous slice containing every unique character present in s.
    3. Fewest surviving catalog IDs: given products and m single-item removals, minimize how many unique IDs survive.
    4. Palindrome-permutable word pairs: given words, count index pairs i < j whose 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.

  2. 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 (for D days and S services). Instead, scan the days once from left to right with two integers:

    • current_streak: how many consecutive all-clear days end on today. If all(day) is True, increment current_streak and update best_streak; if any check is False, reset current_streak = 0.
    • Updating best_streak on 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 3
    
    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
    
  3. Subproblem 2: Minimum window spanning the alphabet of `s` (sliding window)

    Checking all O(n^2) slices takes O(n^3) time. Notice instead that once s[left : right + 1] already covers every unique character of s, extending right further cannot make that slice shorter — we want to advance left to trim extra duplicate letters off the front!

    This gives a two-pointer sliding window:

    1. First compute required_distinct = len(set(s)) (returning 0 immediately if s is empty).
    2. Advance right from 0 to len(s) - 1, adding s[right] to window_counts. Whenever a character's count inside the window rises from 0 to 1, increment covered_distinct.
    3. As long as covered_distinct == required_distinct, record right - left + 1 against shortest_len and pop s[left] by incrementing left (decrementing covered_distinct if its count hits 0).
    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
    
  4. 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 30 appears 1 time and ID 10 appears 3 times, spending 1 removal on ID 30 eliminates a whole unique ID, whereas spending 1 removal on ID 10 eliminates none!

    To wipe out the maximum number of unique IDs within m removals, greedily clear out the rarest IDs first:

    1. Count each item ID's occurrences in freq_by_id.
    2. Sort the occurrence counts from smallest to largest in group_sizes.
    3. Subtract each size from budget while size <= budget, decrementing remaining_distinct by 1 per wiped-out group.

    What if budget > 0 is left over when the loop stops (say budget = 1, next size = 2)? Because budget < size, those leftover removals simply delete budget copies from that next group — at least 1 copy of that ID still survives, so remaining_distinct stays exact for exact m removals!

    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
    
  5. 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' appears 2, 4, or 100 times — 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 position 0, 1, 2, ...:

    • Flipping bit b with XOR (mask ^= 1 << b) toggles 0 -> 1 (odd) and 1 -> 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 when mask_i ^ mask_j has 0 bits set or 1 bit set:
      • 0 bits set: mask_i == mask_j (every combined letter count is even).
      • 1 bit set: mask_i == mask_j ^ (1 << bit) for some character bit (exactly one letter count is odd).

    Scanning words left to right and keeping mask_counts[mask] for earlier words lets us count all valid partners i < j in A + 1 hash-map lookups per word (where A is 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
    
  6. 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:

  1. Running counter (Subproblem 1): Like marking an unbroken daily run on a wall calendar, each day where every status check is True adds 1 to current_streak, and any failed day resets it to 0.
  2. Sliding window (Subproblem 2): A sliding window is a movable [left, right] slice where right steps forward to gather missing characters and left steps forward to shed redundant duplicate characters from the front.
  3. 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 m items and want the fewest boxes left behind.
  4. 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/1 parity 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 to 0 and differing bits produce 1) and find every valid partner in O(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) — Time O(D * S), Space O(1): for D days and S status entries per day, we scan each day once and all(day) inspects at most S booleans, storing only two integer counters.
  • Subproblem 2 (shortest_covering_substring) — Time O(n), Space O(k): for n = len(s) and k unique characters in s, right advances n times and left advances at most n times (O(1) average hash-map updates per step), while window_counts stores at most k keys.
  • Subproblem 3 (min_distinct_after_deletions) — Time O(P + d log d), Space O(d): for P = len(products) items and d unique catalog IDs, counting frequencies scans all P items once, sorting group_sizes takes O(d log d), and freq_by_id plus group_sizes store d integers.
  • Subproblem 4 (count_palindrome_pairs) — Time O(L + W * A), Space O(W + A): for W = len(words), total character length L across all words, and A unique characters appearing in words (at most 26 for lowercase English letters, fitting in one machine word), building all masks scans L characters total and each word performs A + 1 dictionary lookups in mask_counts, which holds at most W distinct masks.

Edge cases

  • Empty inputs ([], "", [] with m = 0, []): all four helpers cleanly return 0.
  • Subproblem 1 — run ending on the last day or zero passing days: updating best_streak inside if all(day): captures runs that never hit a trailing False, and all-False schedules return 0. An empty list [] on a day evaluates all([]) == True (vacuously all zero checks passed).
  • Subproblem 2 — single repeated character ("kkkk"): required_distinct == 1, so the window immediately shrinks to length 1.
  • Subproblem 3 — m = 0 or m = len(products): m = 0 breaks on the first group and returns d; m = len(products) removes every group and returns 0. Leftover budget smaller than the next group's size removes copies from that surviving group without changing remaining_distinct.
  • Subproblem 4 — empty strings and duplicate words: "" has mask 0, so ["", ""] has 0 ^ 0 = 0 (1 pair, forming the empty palindrome ""), and "" pairs with "k" (0 ^ 1 = 1). Duplicate words like ["xy", "xy", "xy"] share the same mask and yield 0 + 1 + 2 = 3 pairs.

Common mistakes

  • Subproblem 1: updating best_streak only inside the else branch, which misses the longest run whenever the final day is all-clear.
  • Subproblem 2: computing right - left + 1 after incrementing left (off-by-one error), or checking len(window_counts) == required_distinct without deleting zero-count keys from window_counts.
  • Subproblem 3: removing from the largest groups instead of the smallest, or computing d - m as 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 inserting mask into mask_counts before querying, which pairs a word with itself (i == j).

Alternative approaches

  • Subproblem 3 in strictly O(P) linear time: because every group size lies between 1 and P, counting sort (bucketing group sizes into an array buckets[1..P] instead of comparison sorting) avoids the O(d log d) sort and runs in O(P) time and space.
  • Subproblem 4 with tuple keys: storing a 26-tuple of 0/1 parities 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_streak and best_streak in O(1) persistent memory, updating them as each day's boolean batch arrives so the running maximum is always ready in O(1) time.
  • How would Subproblem 2 adapt if you needed the shortest substring covering a target multiset t (including character multiplicities)? Build a target_counts dictionary from t and set required_distinct = len(target_counts). During the sliding window over s, increment covered_distinct only when window_counts[ch] == target_counts[ch] and decrement it when window_counts[ch] drops below target_counts[ch]; if covered_distinct never reaches required_distinct, no valid substring exists, and both time O(len(s) + len(t)) and space O(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 into prefix + suffix, if prefix is already a palindrome then prepending reverse(suffix) forms a palindrome (and symmetrically appending reverse(prefix) when suffix is a palindrome), solving unordered ordered pairs in O(W * K^2) time for words of maximum length K.

Follow-up questions

Similar questions

More Nebius interview questions

All 1 Nebius questions →