VOOZH about

URL: https://www.geeksforgeeks.org/dsa/queries-to-search-an-element-in-an-array-and-move-it-to-front-after-every-query/

⇱ Queries to search an element in an array and move it to front after every query - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Queries to search an element in an array and move it to front after every query

Last Updated : 27 Sep, 2022

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:  


Output: 
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.  

  1. Push element in the front
  2. Find the index of a number
  3. Update the indexes of the rest of the elements.

Keep the elements in a sorted manner using the set data structure, and then follow the below-mentioned points:  

  • Instead of pushing the element to the front i.e assigning an index 0 for every query.
  • We assign -1 for the first query, -2 for the second query, -3 for the third, and so on till -m.
  • Doing so, the range of index’s updates to [-m, m]
  • Perform a right shift for all values [-m, m] by a value of m, so our new range is [0, 2m]
  • Initialize a Fenwick tree of size 2m and set all the values from [1…m] i.e [m..2m]
  • For every query, find its position by finding the number of set elements lesser than the given query, once done set its position to 0 in the Fenwick tree.

Below is the implementation of the above approach:  


Output: 
3 1 2 0

 

Time complexity: O(nlogn) 
Auxiliary space: O(n)

Comment
Article Tags: