DEV Community


Posted on

HackerRank Big Sorting challenge

I love to take HackerRank challenges. Those are great to practice programming and improving your overall skills.
I do them quite often - just like today, on Monday, before actually starting my daily work...

It was easy challenge called Big Sorting.
Difficulty: Easy
Max Score: 20

You have to implement the function that receives array of strings where each element in an array can have length between 1 and 106.

Consider an array of numeric strings where each string is a positive number with anywhere from 1 to 106 digits. Sort the array's elements in non-decreasing, or ascending order of their integer values and return the sorted array.

I immediately though I have to use JS' BigInt to sort those arrays because standard number (Integer type) will "corrupt" values.
This is because:

In JavaScript, the Number type cannot safely represent integer values larger than 253

-- Smashing magazine

Alright, my first idea was to go with:

function bigSorting(unsorted) {
    return unsorted
        .sort((a, b) => BigInt(a) - BigInt(b));
Enter fullscreen mode Exit fullscreen mode

Well it was working. Kind of. Just for example cases.
It didn't pass all the Test cases of submission because it hit Time limit exceeded.

I've realized BigInt has to be slow. This is because it uses lot more memory to store values and that's why it's slower than e.g. Number or String while comparing.

So I sit back and had to make new solution for this problem.
Almost immediately I realized that when we sort string values that have different number of digits we don't have to convert those values to BigInt - it's enough to compare them by string length.

My final solution was:

function bigSorting(unsorted) {
    return unsorted
        .sort((a, b) => {
            if (a.length === b.length) {
                return BigInt(a) - BigInt(b);
            return a.length - b.length;
Enter fullscreen mode Exit fullscreen mode

And it worked like a harm 🎉

Of course it can be further improved by checking if string length is longer than Number actually can accept and only then convert string to BigInt otherwise convert to Number.

That's right that was easy challenge but even though required some thinking 🤔.

Great to start new week 👨‍💻

Top comments (1)

robencom profile image

Your post was helpful, it helped me figure out this solution for PHP:

usort($unsorted, function($a, $b) {
$strlenA = strlen($a);
$strlenB = strlen($b);
if ($strlenA != $strlenB) {
return $strlenA - $strlenB;
} else {
return strcoll($a, $b);