
Problem
Solution
Submissions
Duplicate Number
Certification: Basic Level
Accuracy: 0%
Submissions: 0
Points: 5
Write a C program to determine if an array of integers contains any duplicate elements. The function should return true if any value appears at least twice in the array, and false if every element is distinct.
Example 1
- Input: nums = [1, 2, 3, 1]
- Output: true
- Explanation: Step 1: We need to check if the array [1, 2, 3, 1] contains any duplicates. Step 2: We iterate through the array, checking each element. Step 3: We encounter 1 at index 0 and record that we've seen it. Step 4: We encounter 2 at index 1 and record that we've seen it. Step 5: We encounter 3 at index 2 and record that we've seen it. Step 6: We encounter 1 at index 3, but we've already seen 1 before. Step 7: Since we found a duplicate (1), we return true.
Example 2
- Input: nums = [1, 2, 3, 4]
- Output: false
- Explanation: Step 1: We need to check if the array [1, 2, 3, 4] contains any duplicates. Step 2: We iterate through the array, checking each element. Step 3: We encounter 1 at index 0 and record that we've seen it. Step 4: We encounter 2 at index 1 and record that we've seen it. Step 5: We encounter 3 at index 2 and record that we've seen it. Step 6: We encounter 4 at index 3 and record that we've seen it. Step 7: After checking all elements, we found no duplicates, so we return false.
Constraints
- 1 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
- Your solution should optimize for time complexity
- Consider the space-time trade-off in your solution
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- A naive approach would be to check each pair of elements (O(n²) time complexity).
- Sorting the array first would make it easier to find duplicates (O(n log n) time complexity).
- Using a hash table or hash set can achieve O(n) time complexity.
- If using C, you might need to implement your own hash table or use an array if the range of values is small.
- Consider the space-time trade-off when selecting your approach.