Find Duplicate in Array-Asked in Ola

Placewit
2 min readDec 11, 2021

--

Problem Statement :

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.

Input Format:

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

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

The third 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.

Given:

1
3
1 1 2

Output:

1

Constraints:

1 <= T <= 51 <= N <= 10^51 <= ARR[i] <= N — 1Time Limit: 1 sec

Explanation of given Test Cases :

1 is repeated in the array, hence function returns 1.

Approach:

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 we can simply just print the element, which is equal to its previous element as soon as we find it.

Code:

Time Complexity: O(N*log(N))
Space Complexity: O(1)

Thanks for Reading

Placewit grows the best engineers by providing an interactive classroom experience and by helping them develop their skills and get placed in amazing companies.

Learn more at Placewit. Follow us on Instagram and Facebook for daily learning.

--

--

Placewit
Placewit

Written by Placewit

Upskilling students for tech placements!

No responses yet