Count partitions and equal-cost packages
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Take-home Project
Quick Answer: This question evaluates string-processing and combinatorial counting skills, including tracking distinct-character occurrences across contiguous partitions and using frequency-based pairing logic on arrays to form equal-cost packages.
Count Valid Prefix/Suffix Partitions
Constraints
- 1 <= len(itemCategories) <= 10^5
- itemCategories consists of lowercase/uppercase letters (or any characters)
- 0 <= k <= 26 (or up to the alphabet size)
Examples
Input: ("aabba", 1)
Expected Output: 1
Explanation: Splits: a|abba (share {a}=1), aa|bba (share {a}=1), aab|ba (share {a,b}=2>1 VALID), aabb|a (share {a}=1). Only 1 valid.
Input: ("abcabc", 2)
Expected Output: 1
Explanation: Only abc|abc shares all 3 distinct chars {a,b,c}=3>2. Other splits share at most 2.
Hints
- A partition shares a character c if and only if c appears in the prefix AND c appears in the suffix.
- For each split point, you only need the SET of distinct characters on each side, not their counts.
- To optimize beyond O(n^2): precompute, for each character, the first and last index it appears at. A character is shared by the split at i iff its first occurrence is < i and its last occurrence is >= i.
Maximum Equal-Cost Packages
Constraints
- 0 <= len(itemCosts) <= 10^4
- 0 <= itemCosts[i] <= 10^9
- A package may contain one item (cost == target) or two items (costs sum to target)
Examples
Input: ([1, 2, 3, 4],)
Expected Output: 2
Explanation: Target 5: pairs (1,4) and (2,3) -> 2 packages, the maximum.
Input: ([2, 2, 2, 2],)
Expected Output: 4
Explanation: Target 2: four 1-item packages (each item costs 2). Better than target 4 which only yields 2 pair-packages.
Hints
- The target total cost must be either a single item's cost (1-item package) or the sum of two item costs (2-item package), so only those values are worth trying.
- To MAXIMIZE the number of packages for a fixed target, prefer 1-item packages (use an item whose cost equals the target) before pairing, since a package counts the same whether it holds 1 or 2 items but a single uses fewer items.
- For 2-item packages with target S, greedily pair frequency[a] with frequency[S-a]; handle a == S-a (same value) using count//2.