Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.
- Input:
nums = [1, 1, 1, 3, 3, 4, 3, 2, 4, 2] - Output:
true
- Input:
nums = [1, 2, 3, 4, 5] - Output:
false
This problem can be solved optimally using either a Set or an Object to detect duplicate elements. Below is the step-by-step approach:
- Create an empty
SetorObjectto store elements from the array. - Iterate through the input array using a loop.
- For each element:
- If the current element already exists in the
SetorObject, returntrueimmediately (indicating duplicates exist). - Otherwise, add the current element to the
SetorObject.
- If the current element already exists in the
- If the loop completes without finding any duplicates, return
false.
-
Time Complexity:
The time complexity of this algorithm is O(n), wherenis the number of elements in the array. This is because we iterate through the array once, and operations like adding or checking membership in aSetorObjectare constant time on average. -
Space Complexity:
The space complexity is O(n) as we use an additional data structure (SetorObject) to store elements from the array.