1357. Fewest Cross Inversions
A tool receives n short chunks of text in the array parts, each made only of the characters 0 and 1, and must join all of them, in one chosen order, into a single long string. The disorder of the result is the number of index pairs p < q in the final string with a 1 at position p and a 0 at position q. Return the smallest disorder over all orders of the chunks, as a 64-bit integer. Chunks are moved whole and never changed. For each chunk count its ones, its zeros and its own internal disorder; chunk a should precede chunk b when ones(a) * zeros(b) < ones(b) * zeros(a). Then scan the sorted chunks while keeping a running count of ones. Aim for O(L + n log n) time, where L is the total length.
Example 1
- Input:
- parts = ["1","0"]
- Output:
- 0
- Explanation:
Placing 0 before 1 gives the string 01, which has no 1 before a 0.
Example 2
- Input:
- parts = ["10","01"]
- Output:
- 2
- Explanation:
Both chunks have one 1 and one 0; 10 contributes 1 inside itself and one cross pair arises between the chunks, so the total is 2 in either order.
Example 3
- Input:
- parts = ["110","0","1"]
- Output:
- 2
- Explanation:
The order 0, 110, 1 gives 01101, where the two ones before the later 0 create 2 pairs, and this is the minimum.
Constraints
1 ≤ n ≤ 105
total length of all parts ≤ 2*105
each part is non-empty and contains only '0' and '1'
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 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms
Expected complexity
- Time
- O(L + n log n)
- Space
- O(n)