Find Duplicate in Array-Asked in Ola

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.

--

--

--

Upskilling students for tech placements!

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

THM Linux Fundamentals PT 2

Protecting Your Backups with Backup Copy

sensenet ECM 7 stable release is out

Compressing Animated Gifs with PHP

Java Stream API

Learnings after a year as an Engineering Manager

100 Days of Code 2017 — Week 4 Recap

Yin and Yang approach in the software development

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Placewit

Placewit

Upskilling students for tech placements!

More from Medium

Class Quiz

LeetCode 253 — Meeting Rooms 2

Monotonic Stack Problems

“Delete and Earn” problem using Dynamic Programming