Array Duplicates - FreeCodeCamp Daily Challenge
2 min
Array Duplicates: Analysis and Solution
Problem Statement
Given an array of integers, return a new array with the numbers that appear more than once, sorted in ascending order and without repetitions. If there are no duplicates, return an empty array.
Initial Analysis
Key points:
- Only numbers that appear at least twice are considered duplicates.
- The result must not contain repetitions.
- The output array must be sorted in ascending order.
- If there are no duplicates, the result is an empty array.
Test Cases
| Input | Expected Output | Explanation |
|---|---|---|
[1, 2, 3, 4, 5] | [] | No duplicates |
[1, 2, 3, 4, 1, 2] | [1, 2] | 1 and 2 appear more than once |
[2, 34, 0, 1, -6, 23, 5, 3, 2, 5, 67, -6, 23, 2, 43, 2, 12, 0, 2, 4, 4] | [-6, 0, 2, 4, 5, 23] | Several duplicates, including negatives and zeros |
Solution Development
Strategy
- Use a
Mapto count the frequency of each number (supports negatives and zeros). - Filter numbers whose frequency is greater than 1.
- Sort the result in ascending order.
- Return the array (empty if there are no duplicates).
Final Commented Code
/**
* Returns the duplicate numbers from an array, sorted and without repetitions.
* @param {number[]} arr - Array of integers
* @returns {number[]} Array of sorted duplicates
*/
function findDuplicates(arr) {
const frequencyMap = new Map() // Stores the frequency of each number
const result = []
// Count frequencies
for (const num of arr) {
frequencyMap.set(num, (frequencyMap.get(num) || 0) + 1)
}
// Filter duplicates
for (const [num, count] of frequencyMap.entries()) {
if (count > 1)
result.push(num)
}
// Sort ascending
result.sort((a, b) => a - b)
return result
}
export default findDuplicatesComplexity Analysis
Time
- Counting frequencies:
- Filtering duplicates:
- Sorting duplicates: , where is the number of duplicates
- Total:
Space
- Frequency
Map: up to - Result array: up to
- Total:
Edge Cases and Considerations
- Empty array → returns
[] - All unique → returns
[] - All equal → returns
[value] - Negative numbers, zeros, and positives → supported
- Large arrays → efficient
Reflections and Learnings
- Efficient use of
Mapfor counting - Filtering and numeric sorting
- Edge case validation