Shared-Letter Splits and Best Uniform Bundles
StringsAuto-graded · 24 test casesLast updated
Count string split points whose halves share more than k distinct characters, and find the most equal-total bundles of one or two items from a cost list, with a special rule for zero-cost items.
You are given a string categories, an integer k, and a list of integers costs. Solve two independent tasks and return both answers together.
Task 1: Splits with many shared characters
A split at position i (where 1 <= i <= len(categories) - 1) cuts the string into a prefix categories[:i] and a suffix categories[i:]. Both parts are non-empty.
A split is good if the number of distinct characters that appear in both the prefix and the suffix is strictly greater than k.
Count the good splits. If the string has fewer than 2 characters, there are no splits and the count is 0.
Task 2: Largest set of equal-total bundles
You may form bundles from the items in costs. Each bundle holds one or two items, and its total is the sum of the costs of its items. Each item can be placed in at most one bundle, and items need not all be used.
All bundles you form must have the same total. You choose that total. Find the largest number of bundles you can form. If costs is empty, the answer is 0.
Items are distinguished by position, so two items with equal cost are still two separate items.
Rule for the total 0
When the chosen total is 0, items of cost 0 follow this rule: they are paired with each other first, as many pairs as possible. If one zero-cost item is left over, it forms a one-item bundle. So z zero-cost items yield exactly z // 2 + z % 2 bundles of total 0 (that is, ceil(z / 2)). Items with non-zero cost are not affected by this rule. Each of them can still go alone (only if its cost equals the total) or be paired with an item of the opposite cost.
For any non-zero total, a zero-cost item may be paired with an item whose cost equals the total, or left unused. Pairing it never beats using that item alone.
Output
Return a list [good_splits, max_bundles].
Constraints
categoriesis a string of characters. It may be empty or have length 1.kis an integer and may be negative or larger than the number of distinct characters.costsis a list of integers and may be empty. Values may be 0 or negative.- Assume the input sizes are moderate, for example up to a few thousand characters or items.
- A bundle contains at least one and at most two items.
Examples
Example 1
Input: split_and_bundle('abaca', 1, [1, 2, 3, 4])
Output: [0, 2]
Example 2
Input: split_and_bundle('aaaa', 0, [2, 2, 2, 2])
Output: [3, 4]
Example 3
Input: split_and_bundle('abcde', 0, [1, 1, 2, 2, 3])
Output: [0, 3]
Example 4
Input: split_and_bundle('abab', 1, [5, 5, 5, 10, 0])
Output: [1, 3]
Hints
Hint 1
For Task 1, do not rebuild two sets at every split. Moving the split one step right transfers exactly one character from the suffix to the prefix, so only that character's status can change.
Hint 2
Track how many times each character still occurs in the suffix, plus the set of characters already seen in the prefix. Maintain a running count of characters that are in both, and adjust it in O(1) per step.
Hint 3
For Task 2, fix the target total T. Items equal to T can be bundled alone, and the other items pair up by complement (a with T - a), with each complement class independent. Score every candidate T at once by looping over pairs of distinct non-zero values, and treat zero-cost items at T = 0 with the special rule (ceil(z / 2) bundles).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The two tasks are independent, so each is solved on its own and the results are returned together.
Task 1: good splits
Sweep the split point from left to right. Moving from split i to split i + 1 moves exactly one character c from the suffix to the prefix, so only c's membership can change.
Maintain:
suffix_count[c], the number of occurrences ofcstill in the suffix (initialised from the whole string).in_prefix, the set of characters already seen in the prefix.common, the number of characters that are in the prefix and still havesuffix_count > 0.
When moving c:
- Decrement
suffix_count[c]. - If
cis new to the prefix and still occurs in the suffix, it just became shared, socommon += 1. - If
cwas already in the prefix and its suffix count just hit 0, it stopped being shared, socommon -= 1. - Otherwise nothing changes.
After each move, check common > k and count the split. Splits at the very start and end are never evaluated, so both halves are always non-empty.
Task 2: bundles
Fix a target total T. Values split into complement classes {a, T - a}, and these classes are disjoint, so each can be maximised independently:
- Every non-zero item of cost exactly
Tforms a single-item bundle. - For
a != T - a, pair them formin(cnt[a], cnt[T - a])bundles. - For
a == T - a(non-zero), you getcnt[a] // 2bundles.
Zero-cost items need care:
- For a non-zero
T, a zero paired with aTitem gives one bundle but uses two items, which is no better than theTitem alone. So zeros are left out of pairing. - For
T = 0, the problem's rule says zeros pair with each other first, and a lone leftover forms a single bundle. Withzzeros that givesz - z // 2bundles.
Only totals equal to an item cost or to a sum of two non-zero costs can yield bundles. Instead of simulating each total, accumulate a score for all totals in one pass over distinct values:
score[v] += cnt[v]for each non-zerov(single bundles).score[0] += z - z // 2for the zeros.score[2a] += cnt[a] // 2for equal non-zero pairs.score[a + b] += min(cnt[a], cnt[b])for distinct non-zeroa < b. This includesb = -a, which feeds total 0.
The answer is the maximum score. Every total that can form at least one bundle appears as a key, so the maximum is the correct value.
Complexity
- Task 1: O(n) time, O(sigma) space for the alphabet size sigma.
- Task 2: with
ddistinct costs, O(m + d^2) time and O(d^2) space for the score map, wheremis the number of items.
Reference solution
from typing import List
from collections import Counter, defaultdict
def split_and_bundle(categories: str, k: int, costs: List[int]) -> List[int]:
# ---- Task 1: good splits ----
n = len(categories)
good_splits = 0
if n >= 2:
suffix_count = Counter(categories)
in_prefix = set()
common = 0
for i in range(n - 1):
c = categories[i]
suffix_count[c] -= 1
if c not in in_prefix:
in_prefix.add(c)
if suffix_count[c] > 0:
common += 1
elif suffix_count[c] == 0:
common -= 1
if common > k:
good_splits += 1
# ---- Task 2: max equal-total bundles ----
if not costs:
return [good_splits, 0]
cnt = Counter(costs)
values = sorted(cnt)
nonzero = [v for v in values if v != 0]
score = defaultdict(int)
# Single-item bundles. Zero-cost items at total 0 are paired first,
# so z zeros give z - z // 2 = ceil(z / 2) bundles.
for v in values:
if v == 0:
score[0] += cnt[0] - cnt[0] // 2
else:
score[v] += cnt[v]
# Two-item bundles among non-zero values.
for idx, a in enumerate(nonzero):
score[2 * a] += cnt[a] // 2
for b in nonzero[idx + 1:]:
score[a + b] += min(cnt[a], cnt[b])
return [good_splits, max(score.values())]