Tutorialspoint
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
ArrayseBayApple
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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.

Steps to solve by this approach:

 Step 1: Handle edge cases (null array or array with 0 or 1 elements)

 Step 2: Sort the array using qsort() function with a custom compare function
 Step 3: Iterate through the sorted array starting from the second element
 Step 4: For each element, compare it with the previous element
 Step 5: If any adjacent elements are equal, return true (duplicate found)
 Step 6: If the entire array is traversed without finding duplicates, return false
 Step 7: The time complexity is O(n log n) due to the sorting operation

Submitted Code :