← Questions

Split item categories into a prefix and suffix that share enough

0
AmazonCodingLast asked Aug 2025

A coding interview question asked in Amazon's online assessment, last asked Aug 2025. It tests strings, hashing and prefix counts.

A string item_categories lists the categories of items on sale, one character per item. Count the ways to cut it into a non-empty prefix and a non-empty suffix such that more than k distinct categories appear in both parts.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • count_splits(item_categories: str, k: int) -> int — a cut after position i (1 <= i <= n - 1) gives prefix s[:i] and suffix s[i:]; it counts when the number of characters present in both is greater than k.

Example

"aabba", k = 1    ->  1   # only "aab" | "ba" shares {a, b}
"abcabc", k = 2   ->  1   # only "abc" | "abc" shares all three
"abcabc", k = 1   ->  3   # "ab"|"cabc", "abc"|"abc", "abca"|"bc"

Constraints

  • 1 <= len(item_categories) <= 10^5
  • The alphabet is small (letters), and 0 <= k <= its size.

Clarifying questions

  • Are categories case-sensitive?
  • Does a category need to appear just once on each side, or a minimum number of times?
  • Strictly more than k, or at least k?

What a strong answer covers

  • The brute force (build both sets at every cut, O(n · alphabet) with care, O(n^2) naively).
  • One pass with running counts: a count of each character in the suffix, a seen flag for the prefix, and a running number of shared characters updated as each character moves from suffix to prefix.
  • Equivalently, a character is shared at cut i exactly when its first index is < i and its last index is >= i.
  • O(n) time, O(alphabet) space; tests: length 2, all one character, k larger than the alphabet.

Follow-ups

  • Return the cut that maximises the number of shared categories.
  • Count cuts into three non-empty parts where every part shares more than k categories with the others.
  • The alphabet is large (arbitrary item ids). What changes in space and time?

Where it's asked

  • Amazon · Online assessment · Last asked Aug 2025Coding problems plus a repository bug-fix section with a built-in assistant or a design scenario, then a work-style survey · AI only inside the bug-fix section's built-in assistant

What it tests

strings · hashing · prefix counts

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding