![]() |
VOOZH | about |
Given an array that contains each number between 1 to n exactly once. Your task is to collect the numbers from 1 to n in increasing order. On each round, you go through the array from left to right and collect as many numbers as possible. Given m operations that swap two numbers in the array, your task is to report the number of rounds after each operation.
Examples:
Input: n = 5, m = 3, values[] = {4, 2, 1, 5, 3}, swaps[][] = {{2, 3}, {1, 5}, {2,3}}
Output:
2
3
4
Explanation:
- In the 1st operation after swapping the values of 2nd and 3rd position the array is {4, 1, 2, 5, 3}. We can collect 1, 2, 3 in the 1st round and 4, 5 in the 2nd round. Hence, the answer is 2.
- In the 2nd operation after swapping the values of 1st and 5th position the array is {3, 1, 2, 5, 4}. We can collect 1, 2 in the 1st round, 3, 4 in the 2nd round and 5 in the 3rd round. Hence, the answer is 3.
- In the 3rd operation after swapping the values of 2nd and 3rd position the array is {3, 2, 1, 5, 4}. We can collect 1 in the 1st round, 2 in the 2nd round, 3, 4 in the 3rd round and 5 in the 4th round. Hence, the answer is 4.
Input: n = 4, m = 1, values[] = {4, 2, 3, 1}, swaps[][] = {{1, 4}}
Output: 1
Explanation: After the first swap operation, the array will be {1, 2, 3, 4}. We can collect 1, 2, 3 and 4 in the first round only.
Approach: To solve the problem, follow the idea below:
The idea is to calculate the number of inversions, where values[i] > values[j] and position[i] < position[j], between adjacent elements. This will give us the number of rounds required to collect all numbers from 1 to n in the given order. Count the number of inversions formed by given order of elements. Begin the operation. Since only the adjacent elements (the previous and next element of the current element) are affected, we store them in a set if they exist. Then subtract from the count, the inversions formed by our current set as there may be some elements that don’t form an inversion after the swap and if they form they'll be counted. Next, we swap the elements, update the positions, and again count and add the inversions by adjacent elements to our existing count. This approach reduces the time complexity by checking only the neighboring elements.
Step-by-step algorithm:
Below is the implementation of the algorithm:
2 3 4
Time Complexity: O(n), where n is the size of the array.
Auxiliary Space: O(n), where n is the size of the array.