Find Duplicate in Array

You are given an array of integers 'ARR' containing N elements. Each integer is in the range [1, N-1], with exactly one element repeated in the array.

Your task is to find the duplicate element.

Note :

All the integers in the array appear only once except for precisely one integer which appears two or more times.

Input format:

The first line of input contains an integer ‘T’ denoting the number of test cases. Then the T test cases follow.

The first line of each test case contains an integer ‘N’, the number of elements in the array. 

The second line of each test case contains ‘N’ space-separated integers representing the elements of the array. 

Output format:

For each test case, the duplicate element of the given array is printed.

The output of each test case is printed in a separate line. 
Note :
You are not supposed to print anything; It has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 5
1 <= N <= 10^5
1 <= ARR[i] <= N - 1

Time Limit: 1 sec
CodingNinjas
author
2y

Concept of indexing can be used to solve this question.
Traverse the array. For every element at index i,visit a[i]. If a[i] is positive, then change it to negative. If a[i] is negative, it means the e...read more

CodingNinjas
author
2y
Using Sort

First, we sort the array. Now, the rest of the algorithm becomes fairly simple. We just compare each element to its previous element. As we know there is exactly one repeated element, hence ...read more

CodingNinjas
author
2y
Binary Search

We perform binary search on the array [1,N], then COUNT the number of elements that are less than or equal to MID of [1,N]. If the duplicate is on the left side of the middle element, the...read more

CodingNinjas
author
2y
Using Set

We need to insert elements into a data structure and look them up in constant time, so as to improve the complexity of sorting approach. A set can be used to satisfy these conditions. So, we ...read more

CodingNinjas
author
2y
Modifying Array IN-PLACE

For this approach we use the array indices to store the visited state of each number. We know that only the duplicate element would be visited more than once. For each number w...read more

CodingNinjas
author
2y
Floyd’s Tortoise and Hare Approach

For this approach, we divide the whole process into two phases and use two pointers named tortoise and hare..

Phase 1(Find the intersection point): The hare would be ...read more

Add answer anonymously...
Housing.com 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