DEV Community

loading...

HackerRank Big Sorting challenge

webit
Web developer πŸ’» Cycling addicted πŸš΄πŸΌβ€β™‚οΈ Making web since last century πŸ¦–
・2 min read

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 πŸ‘¨β€πŸ’»

Discussion (0)

Forem Open with the Forem app