Find the duplicate number-coding question asked by Meta, JPMC

Problem statement:

Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.

There is only one repeated number in nums, return this repeated number.

You must solve the problem without modifying the array nums and uses only constant extra space.

Input Format:

Output Format:

Sample Input 1:

Sample Output 1:

Sample Input 2:

Sample Output 2:

Constraint:

Approach:

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 iterate over the array and insert each element into a set. Before inserting we check whether the element is already present in the set or not. If it is found, we get the repeated element and hence return it.

Time complexity: O(n)

Space complexity: O(n)

Code:

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.

--

--

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