GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • LeetCodeJavascript.com
  • Star on GitHub

This view

  • Original page
  • New address

GeezerVison is showing leetcodejavascript.com — #912 - Sort an Array - LeetCode JavaScript Solutions

Back to all solutions

#912 - Sort an Array

Medium • View on LeetCode • View on GitHub
Array Sorting Heap Priority Queue Divide and Conquer Merge Sort Counting Sort Bucket Sort Radix Sort

Problem Description

Given an array of integers nums, sort the array in ascending order and return it.

You must solve the problem without using any built-in functions in O(nlog(n)) time complexity and with the smallest space complexity possible.

Solution

/**
 * @param {number[]} nums
 * @return {number[]}
 */
var sortArray = function(nums) {
  if (nums.length <= 1) {
    return nums;
  }

  const min = Math.min(...nums);
  const max = Math.max(...nums);
  const count = new Array(max - min + 1).fill(0);

  nums.forEach(n => count[n - min]++);

  for (let i = 0, j = 0; i < count.length; i++) {
    while (count[i]-- > 0) {
      nums[j++] = i + min;
    }
  }

  return nums;
};
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.