912. Sort an Array
Intuition
We can use a counting sort approach with bucket sort, which is efficient for this specific range of numbers.
Approach
- Create a bucket array of size 100001 (to accommodate numbers from -50000 to 50000)
- Count the frequency of each number by adding 50000 to the index (to handle negative numbers)
- Reconstruct the sorted array by iterating through the bucket array and placing numbers back in their original positions
Complexity
- Time complexity: O(n + k)
- Space complexity: O(k)
Keywords
- Sorting
- Counting Sort
- Bucket Sort