Count of array elements whose order of deletion precedes order of insertion

Given an initial array, A[] and a final array B[] both of size N containing integers from the range [1, N], where A[] represent the order in which elements were inserted and B[] represents the order in which they were removed, the task is to find the number of elements in B[] lying at an index earlier than its respective position in A[].
Examples: 
 

 Input: A[ ] = {1, 2, 4, 3}, B[ ] = {2, 3, 4, 1}
Output: 3
Explanation: 
The element 2 was inserted after 1, but removed before 1. 
The element 3 was inserted after 4, but removed before 4. 
The element 4 was inserted after 1, but removed before 1. 
Hence, total 3 elements have moved ahead.

Input: A[ ] = {1, 2, 3, 4} B[ ] = {1, 2, 4, 3}
Output: 1
Explanation: 
The element 4 was inserted after 3, but removed before 3. 
Hence, only 1 element has moved ahead.

 

Naive Approach: The simplest way to solve this problem is to compare the position of every element in B[] with the position of every other element in A[] and check if it was inserted after an element in A[] but removed before in B[]. If yes, then increment the count. Finally, print the total count.

Time Complexity: O(N2)
Auxiliary Space: O(1)

Efficient Approach: A better approach to solve this problem is to maintain a queue and insert the elements of B[] into this queue and also insert all elements to an unordered set. An unordered set is used to efficiently check if a particular element is processed yet or not. Traverse A[] and pop elements from the queue until current element A[i] appears at top of the queue, also keep incrementing the count and marking the elements appearing at top of queue as processed. Finally, the total count will give the number of elements that have moved ahead in B[].



Follow the steps below to solve the problem: 

  • Maintain a Queue and unordered set and store the values of array B[] in both.
  • Now, iterate over array A[].
  • If the current element is not present in the unordered set, it means it has already been removed.
  • Initialize a variable count. If any ith element is not found in the queue, remove all the elements present in the queue before A[i] from the queue and unordered set keep increasing count.
  • Remove A[i] from the queue and unordered set.
  • Finally, print the total count.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ Program to implement
// the above appraoch
#include <bits/stdc++.h>
using namespace std;
  
// Function returns maximum number
// of required elements
int maximumCount(int A[], int B[], int n)
{
  
    queue<int> q;
    unordered_set<int> s;
  
    // Insert the elements of array B
    // in the queue and set
    for (int i = 0; i < n; i++) {
  
        s.insert(B[i]);
        q.push(B[i]);
    }
  
    // Stores the answer
    int count = 0;
  
    for (int i = 0; i < n; i++) {
  
        // If A[i] is already processed
        if (s.find(A[i]) == s.end())
            continue;
  
        // Until we find A[i] in the queue
        while (!q.empty() && q.front() != A[i]) {
  
            // Remove elements from the queue
            s.erase(q.front());
            q.pop();
  
            // Increment the count
            count++;
        }
  
        // Remove the current element A[i]
        // from the queue and set.
        if (A[i] == q.front()) {
  
            q.pop();
            s.erase(A[i]);
        }
  
        if (q.empty())
            break;
    }
  
    // Return total count
    cout << count << endl;
}
  
// Driver Code
int main()
{
    int N = 4;
    int A[] = { 1, 2, 3, 4 };
    int B[] = { 1, 2, 4, 3 };
  
    maximumCount(A, B, N);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement
// the above appraoch
import java.util.*;
  
class GFG{
  
// Function returns maximum number
// of required elements
static void maximumCount(int A[], int B[], int n)
{
    Queue<Integer> q = new LinkedList<>();
    HashSet<Integer> s = new HashSet<>();
  
    // Insert the elements of array B
    // in the queue and set
    for(int i = 0; i < n; i++) 
    {
        s.add(B[i]);
        q.add(B[i]);
    }
  
    // Stores the answer
    int count = 0;
  
    for(int i = 0; i < n; i++) 
    {
          
        // If A[i] is already processed
        if (!s.contains(A[i]))
            continue;
  
        // Until we find A[i] in the queue
        while (!q.isEmpty() && q.peek() != A[i]) 
        {
  
            // Remove elements from the queue
            s.remove(q.peek());
            q.remove();
  
            // Increment the count
            count++;
        }
  
        // Remove the current element A[i]
        // from the queue and set.
        if (A[i] == q.peek()) 
        {
            q.remove();
            s.remove(A[i]);
        }
          
        if (q.isEmpty())
            break;
    }
      
    // Return total count
    System.out.print(count + "\n");
}
  
// Driver Code
public static void main(String[] args)
{
    int N = 4;
    int A[] = { 1, 2, 3, 4 };
    int B[] = { 1, 2, 4, 3 };
  
    maximumCount(A, B, N);
}
}
  
// This code is contributed by princi singh

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement 
// the above appraoch 
using System;
using System.Collections.Generic;
  
class GFG{ 
  
// Function returns maximum number 
// of required elements 
static void maximumCount(int []A, int []B, int n) 
    Queue<int> q = new Queue<int>(); 
    HashSet<int> s = new HashSet<int>(); 
  
    // Insert the elements of array B 
    // in the queue and set 
    for(int i = 0; i < n; i++) 
    
        s.Add(B[i]); 
        q.Enqueue(B[i]); 
    
  
    // Stores the answer 
    int count = 0; 
  
    for(int i = 0; i < n; i++) 
    
          
        // If A[i] is already processed 
        if (!s.Contains(A[i])) 
            continue
  
        // Until we find A[i] in the queue 
        while (q.Count != 0 && q.Peek() != A[i]) 
        
  
            // Remove elements from the queue 
            s.Remove(q.Peek()); 
            q.Dequeue(); 
  
            // Increment the count 
            count++; 
        
  
        // Remove the current element A[i] 
        // from the queue and set. 
        if (A[i] == q.Peek()) 
        
            q.Dequeue(); 
            s.Remove(A[i]); 
        
        if (q.Count == 0) 
            break
    
      
    // Return total count 
    Console.Write(count + "\n"); 
  
// Driver Code 
public static void Main(String[] args) 
    int N = 4; 
    int []A = { 1, 2, 3, 4 }; 
    int []B = { 1, 2, 4, 3 }; 
  
    maximumCount(A, B, N); 
  
// This code is contributed by princi singh 

chevron_right


Output: 

1

Time Complexity: O(N) 
Auxiliary Space: O(N)
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : princi singh