1256. Trim to Balanced Trio

Medium3.5 points estimatedHash TablePrefix SumString3 hints

A kitchen conveyor carries dishes labelled a, b or c, described by the string s. The chef must discard exactly one contiguous block of the belt; the block may be empty or may be the whole belt. The dishes left over, with the two outer parts joined together, must contain the same number of a, b and c dishes.

Return the minimum number of dishes discarded. An answer always exists, because discarding the whole belt leaves three zero counts. Trying every block is too slow for 2*10^5 characters. Aim for O(n) time and O(n) space: with prefix key (count of a minus count of b, count of b minus count of c), the block [l, r) works exactly when key[l] equals key[r] minus the key of the whole string; keep the latest index of every key in a hash map.

Example 1

Input:
s = "bcaacbbacb"
Output:
1
Explanation:

The belt has 3 a, 4 b and 3 c dishes, so discarding one b leaves three of each.

Example 2

Input:
s = "ccabbbcab"
Output:
3
Explanation:

The belt has 2 a, 4 b and 3 c dishes, and discarding the block bbc is the shortest contiguous removal that leaves two of each.

Example 3

Input:
s = "baacbcbacaa"
Output:
2
Explanation:

The belt has 5 a, 3 b and 3 c dishes, and discarding the adjacent pair aa leaves three of each.

Constraints

1 ≤ s.length ≤ 2*105; s contains only the letters a, b and c.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…