Make Unique Array

You are given an array ‘ARR’ of size ‘N,’ and you have to tell the minimum number of elements that need to be removed such that the array contains all distinct elements. More formally, there should not be any ‘I’ and ‘J’ such that ‘I’ != ‘J’ and ‘ARR’[‘I’] = ‘ARR’[‘J’].

For example:

Given ‘N’ = 4, 
'ARR' = { 1, 2, 1, 2} 
Then the answer is 2 because 1 and 2 are repeated once therefore we need to remove 2 elements.
Input format:
The first line of input contains an integer ‘T’ denoting the number of test cases.

The first line of each test case contains a single integer, ‘N,’ where ‘N’ is the number of elements of the array.

The second line of each test case contains ‘N’ space-separated integers, denoting the array elements.
Output Format :
For each test case, You are supposed to return an integer denoting the minimum number of elements to remove from the array, such that the array contains all distinct elements.
Note:
You are not required to print the expected output; it has already been taken care of. Just implement the function.
Constraints:
1 <= ‘T’ <= 10
1 <= ‘N’ <= 5000
0 <= 'ARR[i]’ <= 10 ^ 6

Time Limit: 1 sec.
CodingNinjas
author
2y
Brute force

The idea is to maintain an array which contains only unique elements, then for each element in the given array search whether the unique array has that element or not. In the return ‘N’ min...read more

CodingNinjas
author
2y
Sorting

The idea is to sort the array and then check if the consecutive elements are the same. If they are, then we increase the counter to remove elements.


The steps are as follows:

  • Maintain a variabl...read more
CodingNinjas
author
2y
Hash Map

The idea is to use a hash map, which stores all the elements we have seen so far, and if any element re-appears, then we remove it. Else we mark that element as present.


The steps are as follo...read more

Add answer anonymously...
Nagarro Senior Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter