1739. Ones Before Zeros Order

Medium3.5 points estimatedGreedyCustom ComparatorStringSorting

A logging system stores signals as short binary snippets. Each string in parts is made of characters '0' and '1'. You may concatenate all snippets, each used exactly once, in any order you like to form one long string s. The score of s is the number of index pairs i < j with s[i] = '1' and s[j] = '0' (a one somewhere before a zero).

Return the maximum score achievable, as a long. Snippet a should come before snippet b when ones(a) * zeros(b) > ones(b) * zeros(a), and snippets that compare equal give the same score in either order, so the answer is unique. Expected: O(L + n log n) time where L is the total length, and O(n) extra space.

Example 1

Input:
parts = ["10","01","1"]
Output:
4
Explanation:

Ordering the parts as "1", "10", "01" gives "11001", where both leading ones precede both zeros, for 4 pairs, which is the maximum.

Example 2

Input:
parts = ["0","1"]
Output:
1
Explanation:

Putting "1" before "0" gives "10", which has exactly one pair.

Constraints

1 ≤ parts.length ≤ 300

1 ≤ parts[i].length ≤ 20

Every character is '0' or '1'.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(L + n log 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…