Splitting Strings and Batching Equal-Cost Item Pairs
Arrays & HashingModel answerLast updated
Count splits where prefix and suffix share more than k letters, then find the target cost that yields the most single-or-pair packages.
Two independent warm-up style tasks, both of which reward spotting structure that turns an apparent quadratic scan into something incremental.
Task 1 — Shared-letter splits. You are given a string itemCategories made of lowercase English letters, and an integer k with 0 ≤ k ≤ 26. For every split position i with 1 ≤ i < n, cut the string into a non-empty prefix itemCategories[0..i-1] and a non-empty suffix itemCategories[i..n-1]. Count how many split positions have strictly more than k letters that occur at least once in the prefix and at least once in the suffix. Return that count. Constraints: 1 ≤ n ≤ 100000.
Task 2 — Uniform-cost packages. You are given itemCosts, an array of n positive prices. You must group items into packages such that every package has exactly the same total cost S, each package holds at most two items, and no item appears in more than one package. A one-item package is legal only when that item's cost equals S; a two-item package is legal only when the two costs sum to S. Pick S so the number of packages is as large as possible, and return that maximum. Explain your reasoning and the resulting time complexity.
For both tasks, state your assumptions, cover degenerate cases, and justify why your counting is exact.
Hints
Hint 1
Task 1: when the split point shifts right by one, exactly one character changes sides — so only that character's shared/not-shared status can change.
Hint 2
Task 1: keep per-letter counts for both sides plus a running tally of letters present on both sides; update the tally by comparing the moved letter's status before and after.
Hint 3
Task 2: for a fixed S, the item values fall into self-contained groups {v, S−v}; within a two-value group you can pair at most min(count[v], count[S−v]) times, and a single value v pairs with itself ⌊count[v]/2⌋ times.
Hint 4
Task 2: the best S is always either an existing price or a sum of two prices — so accumulate each value-pair's contribution into a map keyed by its sum instead of rescanning the array per candidate.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Task 1 — Shared-letter splits
Structure to exploit. Moving the split from i to i+1 moves exactly one character, itemCategories[i], from the suffix side to the prefix side. No other letter's presence on either side changes. So instead of rebuilding two sets at every position (O(n·26) or worse), maintain pre[26] and suf[26] counts plus a scalar common = number of letters with a positive count on both sides.
The update. Before touching the counts, record whether the moving letter c was shared. Then pre[c] += 1, suf[c] -= 1, and record whether it is shared afterwards. Add the difference to common. Because only c's counts changed, only c's shared status could flip — the update is exact, not approximate.
Order of business. Seed suf with a full pass over the string (the split at i = 0, which is not counted since the prefix would be empty). Then loop idx from 0 to n-2, each time moving one character and, if common > k, counting the split at idx+1.
Correctness. After processing itemCategories[0..idx], pre and suf describe the split at idx+1 exactly, and common equals the size of the intersection of the two letter sets. We test the condition once per valid split, so the count is exact.
Complexity. O(n) time, O(1) extra space (two 26-entry arrays).
Edge cases. n = 1 → no valid split, answer 0. k ≥ 26 → common ≤ 26 ≤ k always, so 0 falls out naturally. k = 0 → counts splits sharing at least one letter. A constant string → every split has common = 1.
def count_splits(itemCategories: str, k: int) -> int:
n = len(itemCategories)
pre, suf = [0] * 26, [0] * 26
for ch in itemCategories:
suf[ord(ch) - 97] += 1
common = 0
answer = 0
for idx in range(n - 1):
c = ord(itemCategories[idx]) - 97
before = pre[c] > 0 and suf[c] > 0
pre[c] += 1
suf[c] -= 1
after = pre[c] > 0 and suf[c] > 0
common += after - before
if common > k:
answer += 1
return answer
Task 2 — Uniform-cost packages
Fix S first, then count greedily. With positive prices, an item costing S can only be a singleton (any partner would need cost 0), and an item costing v < S can only pair with an item costing S − v. That means the values decompose into independent groups {v, S−v} (or the singleton group {S}), and choices in one group never constrain another. So for a fixed S the optimum is the sum of per-group optima:
- two distinct values
a < bwitha + b = S: at mostmin(count[a], count[b])pairs; - one value
vwith2v = S: at most⌊count[v]/2⌋pairs; - the value
Sitself:count[S]singles, none of which can be paired (positive costs).
Avoid re-scanning per candidate. The only S values worth considering are existing prices (to enable singles) and sums of two distinct-or-equal prices. Rather than computing the formula from scratch for each one, sweep over unordered value pairs once and accumulate each pair's contribution into a hash map keyed by the pair sum. Then for each key S, the candidate total is contribution[S] + count[S]. Take the maximum.
Correctness. Each group {a, b} is enumerated exactly once under key a + b, so no contribution is double-counted. Every S that is neither a price nor a pair sum admits zero packages, so the candidate set is complete. Within each group the bound min / floor(count/2) is achievable, so the per-group values are exact, and by independence they sum to the true optimum.
Complexity. O(n + D²) time where D is the number of distinct prices, O(D²) space for the map. If prices are known to be bounded by some C, arrays replace the map: O(n + C²) time, O(C) space.
Edge cases. n = 1 → one singleton, answer 1. All prices equal to x → count[x] singles beat ⌊count[x]/2⌋ pairs of 2x, so the answer is count[x]. If zero prices are allowed, discard value 0 from pair enumeration: for S > 0 a zero-cost item adds nothing (its only legal partner already stands alone), and S = 0 yields count[0] singles — the code below keeps 0 out of vals and still finds it as a candidate via the count keys.
from collections import Counter, defaultdict
def max_packages(itemCosts: list[int]) -> int:
if not itemCosts:
return 0
count = Counter(itemCosts)
vals = sorted(v for v in count if v > 0)
pair_hits = defaultdict(int)
for i, a in enumerate(vals):
pair_hits[2 * a] += count[a] // 2
for b in vals[i + 1:]:
pair_hits[a + b] += min(count[a], count[b])
best = 0
for s in set(pair_hits) | set(count):
best = max(best, pair_hits.get(s, 0) + count.get(s, 0))
return best
What separates strong answers from weak ones
- Task 1: recognising the single-character delta and updating the shared tally in O(1). Rebuilding both sets at every split, or comparing all 26 letters each step without saying why, is passable but clumsy.
- Task 2: arguing the independence of
{v, S−v}groups instead of asserting a global greedy works; and inverting the loop order so you accumulate pair contributions once instead of re-scanning the array for every candidateS.
Frequent slips: pairing the middle value with itself via min(count, count) instead of count // 2; forgetting singletons, or counting an S-cost item both as a singleton and inside a pair; and off-by-one splits in Task 1 (including i = 0 or i = n, which produce an empty side).