![]() |
VOOZH | about |
Given three numbers N, A, and X, the task is to construct the lexicographically smallest binary array of size N, containing A 0s and having an inversion count of X.
Examples:
Input: N=5, A=2, X=1
Output: 0 1 0 1 1
Explanation:
The number of inversions in this array is 1(2nd and 3rd index).Input: N=5, A=2, X=3
Output: 0 1 1 1 0
Approach: The given problem can be solved using two pointer technique based on the following observations:
- The array with A 0s having 0 inversion is the array with all 0s to the beginning and then the all the 1s.
- If an element 0 at index i and an element 1 at index j is swapped, then inversion count increases by count of 1s in the range [i, j].
- The maximum possible inversion count is A*(N-A).
Follow the steps below to solve the problem:
Below is the implementation of the above approach:
0 1 0 1 1
Time complexity: O(N)
Auxiliary Space: O(1)