4- Find the duplicate
Description
Given an array of integers arr that contains n+1 elements between 1 and n inclusive, create a function that returns the duplicate element (the element that appears more than once). Assume that:
- There is only one duplicate number
- The duplicate number can be repeated more than once
Example 1:
- Input: arr = [4, 2, 1, 3, 1]
- Output: 1
Example 2:
- Input: arr = [1, 4, 2, 2, 5, 2]
- Output: 2
Try some input:
Try to solve:
Select a language:
Solution:
Code:
Select a language:
Python code:
Brute force solution:
In case the code doesn't appear: click here
Time complexity: O(n²)
Space complexity: O(1)
By sorting the array:
In case the code doesn't appear: click here
Time complexity: O(nlogn)
Space complexity: Depends on the sorting algorithm we use
By using a dictionary:
In case the code doesn't appear: click here
Time complexity: O(n)
Space complexity: O(n)
By using Floyd's cycle detection algorithm (tortoise and hare):
In case the code doesn't appear: click here
Time complexity: O(n)
Space complexity: O(1)
Java code:
Brute force solution:
In case the code doesn't appear: click here
Time complexity: O(n²)
Space complexity: O(1)
By sorting the array:
In case the code doesn't appear: click here
Time complexity: O(nlogn)
Space complexity: Depends on the sorting algorithm we use
By using a HashMap:
In case the code doesn't appear: click here
Time complexity: O(n)
Space complexity: O(n)
By using Floyd's cycle detection algorithm (tortoise and hare):
In case the code doesn't appear: click here
Time complexity: O(n)
Space complexity: O(1)
C++ code:
Brute force solution:
In case the code doesn't appear: click here
Time complexity: O(n²)
Space complexity: O(1)
By sorting the array:
In case the code doesn't appear: click here
Time complexity: O(nlogn)
Space complexity: Depends on the sorting algorithm we use
By using an unordered_map:
In case the code doesn't appear: click here
Time complexity: O(n)
Space complexity: O(n)
By using Floyd's cycle detection algorithm (tortoise and hare):
In case the code doesn't appear: click here
Time complexity: O(n)
Space complexity: O(1)
JavaScript code:
Brute force solution:
In case the code doesn't appear: click here
Time complexity: O(n²)
Space complexity: O(1)
By sorting the array:
In case the code doesn't appear: click here
Time complexity: O(nlogn)
Space complexity: Depends on the sorting algorithm we use
By using an Object as a hash table:
In case the code doesn't appear: click here
Time complexity: O(n)
Space complexity: O(n)
By using Floyd's cycle detection algorithm (tortoise and hare):
In case the code doesn't appear: click here
Time complexity: O(n)
Space complexity: O(1)
Frequently asked questions:
No questions yet.
You can ask a question in comment section below.
0 comments