KatInterview

Splitting Strings and Batching Equal-Cost Item Pairs

Arrays & HashingModel answer
MediumModel answerArrays & Hashingcountingfrequency-arrayshash-map

Last 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.