C++ program to find array after removal of left occurrences of duplicate elements

C++Server Side ProgrammingProgramming

Suppose we have an array A with n elements. We want to remove duplicate elements. We want to leave only the rightmost entry for each element of the array. The relative order of the remaining unique elements should not be changed.

So, if the input is like A = [1, 5, 5, 1, 6, 1], then the output will be [5, 6, 1]

Steps

To solve this, we will follow these steps −

Define two arrays b and vis of size: 1200 each
x := 0
n := size of A
for initialize i := n - 1, when i >= 0, update (decrease i by 1), do:
   if vis[A[i]] is zero, then:
      b[x] := A[i]
      (increase x by 1)
      vis[A[i]] := 1
for initialize i := x - 1, when i >= 0, update (decrease i by 1), do:
   print b[i]

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;

void solve(vector<int> A) {
   int b[1200], vis[1200], x = 0;
   int n = A.size();
   for (int i = n - 1; i >= 0; i--) {
      if (!vis[A[i]]) {
         b[x] = A[i];
         x++;
         vis[A[i]] = 1;
      }
   }
   for (int i = x - 1; i >= 0; i--)
      cout << b[i] << ", ";
}
int main() {
   vector<int> A = { 1, 5, 5, 1, 6, 1 };
   solve(A);
}

Input

{ 1, 5, 5, 1, 6, 1 }

Output

5, 6, 1,
raja
Updated on 03-Mar-2022 07:40:37

Advertisements