![]() |
VOOZH | about |
Given an integer M which represents an array initially having numbers 1 to M. Also given is a Query array. For every query, search the number in the initial array and bring it to the front of the array. The task is to return the indexes of the searched element in the given array for every query.
Examples:
Input : Q[] = {3, 1, 2, 1}, M = 5
Output : [2, 1, 2, 1]
Explanations :
Since m = 5 the initial array is [1, 2, 3, 4, 5].
Query1: Search for 3 in the [1, 2, 3, 4, 5] and move it in the beginning. After moving, the array looks like [3, 1, 2, 4, 5]. 3 is at index 2.
Query2: Move 1 from [3, 1, 2, 4, 5] to the beginning of the array to make the array look like [1, 3, 2, 4, 5]. 1 is present at index 1.
Query3: Move 2 from [1, 3, 2, 4, 5] to the beginning of the array to make the array look like [2, 1, 3, 2, 4, 5]. 2 is present at index 2.
Query4: Move 1 from [2, 1, 3, 4, 5] to the beginning of the array to make the array look like [1, 2, 3, 4, 5]. 1 is present at index 1.Input : Q[] = {4, 1, 2, 2}, M = 4
Output : 3, 1, 2, 0
Naive approach: The naive approach is to use a hash table to search for the element and linearly do shifts by performing swaps. The time complexity will be quadratic in nature for this approach.
Below is the naive implementation of the above approach:
2 1 2 1
Time complexity: O(n*p)
Auxiliary space: O(m)
Efficient Approach: An efficient method to solve the above problem is to use Fenwick Tree. Using the below 3 operations, the problem can be solved.
Keep the elements in a sorted manner using the set data structure, and then follow the below-mentioned points:
Below is the implementation of the above approach:
3 1 2 0
Time complexity: O(nlogn)
Auxiliary space: O(n)