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:3Explanation:

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:1Explanation:

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(N^{2})**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**i**element is not found in the queue, remove all the elements present in the queue before^{th}**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++

`// 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*

*filter_none*

## Java

`// 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*

*filter_none*

## Python3

`# Python3 Program to implement ` `# the above appraoch ` `import` `queue ` `# Function returns maximum number ` `# of required elements ` `def` `maximumCount(A, B, n): ` ` ` `q ` `=` `queue.Queue() ` ` ` `s ` `=` `set` `() ` ` ` `# Insert the elements of ` ` ` `# array B in the queue ` ` ` `# and set ` ` ` `for` `i ` `in` `range` `(n):` ` ` `s.add(B[i]) ` ` ` `q.put(B[i])` ` ` `# Stores the answer ` ` ` `count ` `=` `0` ` ` `for` `i ` `in` `range` `(n):` ` ` `# If A[i] is already ` ` ` `# processed ` ` ` `if` `(A[i] ` `not` `in` `s): ` ` ` `continue` ` ` `# Until we find A[i] ` ` ` `# in the queue ` ` ` `while` `(q.qsize() > ` `0` `and` ` ` `q.queue[` `0` `] !` `=` `A[i]): ` ` ` `# Remove elements from ` ` ` `# the queue ` ` ` `s.remove(q.queue[` `0` `]); ` ` ` `q.get() ` ` ` `# Increment the count ` ` ` `count ` `+` `=` `1` ` ` `# Remove the current element A[i] ` ` ` `# from the queue and set. ` ` ` `if` `(A[i] ` `=` `=` `q.queue[` `0` `]):` ` ` `q.get() ` ` ` `s.remove(A[i])` ` ` `if` `(q.qsize() ` `=` `=` `0` `):` ` ` `break` ` ` `# Return total count ` ` ` `print` `(count)` ` ` `# Driver code` `N ` `=` `4` `A ` `=` `[` `1` `, ` `2` `, ` `3` `, ` `4` `]` `B ` `=` `[` `1` `, ` `2` `, ` `4` `, ` `3` `]` `maximumCount(A, B, N)` `# This code is contributed by divyeshrabadiya07` |

*chevron_right*

*filter_none*

## C#

`// 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*

*filter_none*

**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.

## Recommended Posts:

- Array obtained by repeatedly reversing array after every insertion from given array
- Insertion Sort by Swapping Elements
- Count of elements whose absolute difference with the sum of all the other elements is greater than k
- Count maximum elements of an array whose absolute difference does not exceed K
- Count arrays of length K whose product of elements is same as that of given array
- Count of elements in an Array whose set bits are in a multiple of K
- Count array elements whose product of digits is a Composite Number
- Count of Array elements greater than all elements on its left and next K elements on its right
- Count of Array elements greater than all elements on its left and at least K elements on its right
- Find Maximum dot product of two arrays with insertion of 0's
- Kth largest element after every insertion
- Queries on insertion of an element in a Bitonic Sequence
- Lower Insertion Point
- Check if there exist two elements in an array whose sum is equal to the sum of rest of the array
- Sum of elements in an array whose difference with the mean of another array is less than k
- Minimize K whose XOR with given array elements leaves array unchanged
- Sort elements of an array in increasing order of absolute difference of adjacent elements
- Count of sub-arrays whose elements can be re-arranged to form palindromes
- Count elements whose sum with K is greater than max element
- Count of elements which cannot form any pair whose sum is power of 2

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.