U

185. Modify Merge Sort to Count

Easy

Problem Description

Modify merge sort to count the number of inversions in an array.

Input Format

  • •Line 1: Two space-separated integers NN and MM (1≤N,M≤1051 \le N, M \le 10^5).
  • •Line 2: NN space-separated integers A1,…,ANA_1, \dots, A_N.
  • •Line 3: MM space-separated integers B1,…,BMB_1, \dots, B_M.

Output Format

Print the merged or evaluated space-separated integers.

Example 1:
Input:
3 3
1 3 5
2 4 6
Output:
1 2 3 4 5 6
Explanation: Merged sorted sequence combining both arrays.
Example 2:
Input:
2 1
1 5
3
Output:
1 3 5
Explanation: Combining unequal collections preserves sorted ordering.
Example 3:
Input:
1 1
10
20
Output:
10 20
Explanation: Single element from each array merged.
Constraints:
  • 1 <= N, M <= 10^5
  • -10^9 <= elements <= 10^9
  • Time complexity target: O(N + M)
  • Auxiliary space target: O(1) or O(N + M)
Follow up:Can this algorithm be adapted to an online streaming setting where the entire input cannot be held in memory simultaneously?
1,180 Online