In this Big Sorting HackerRank solution, Consider an array of numeric strings where each string is a positive number with anywhere from to digits. Sort the array’s elements in non-decreasing, or ascending order of their integer values and return the sorted array.
Example
Return the array [‘1’, ‘3’, ‘150’, ‘200’].
Function Description
Complete the bigSorting function in the editor below.
bigSorting has the following parameter(s):
- string unsorted[n]: an unsorted array of integers as strings
Returns
- string[n]: the array sorted in numerical order
Input Format
The first line contains an integer, , the number of strings in .
Each of the subsequent lines contains an integer string, .
Constraints
- Each string is guaranteed to represent a positive integer.
- There will be no leading zeros.
- The total number of digits across all strings in is between and (inclusive).
Sample Input 0
6
31415926535897932384626433832795
1
3
10
3
5
Sample Output 0
1
3
3
5
10
31415926535897932384626433832795
Explanation 0
The initial array of strings is . When we order each string by the real-world integer value it represents, we get:
We then print each value on a new line, from smallest to largest.
Sample Input 1
8
1
2
100
12303479849857341718340192371
3084193741082937
3084193741082938
111
200
Sample Output 1
1
2
100
111
200
3084193741082937
3084193741082938
12303479849857341718340192371
Big Sorting HackerRank solution
I will Provide solution in Multiple programming languages for you. If you are not able to find the code in required language then please share in comments so that our team can help you.
Problem Solution in Python
def bigSorting(unsorted):
# Create a bucket D for each D-digit string.
buckets={}
for s in unsorted:
digits = len(s)
if digits in buckets:
buckets[digits].append(s)
else:
buckets[digits] = [s]
# Sort the buckets ascending. e.g. from the 1-digit to the N-digit bucket
buckets = dict(sorted(buckets.items()))
# For each bucket, sort its value and insert them into the final output
output = []
for b in buckets:
buckets[b].sort()
output.extend(buckets[b])
return output
Problem Solution in C++
vector<string> bigSorting(vector<string> u) {
sort(u.begin(), u.end(), [](string l, string r){
if(l.size() == r.size()) return l < r;
return l.size() < r.size();
});
return u;
}
Problem Solution in Java
public static List<String> bigSorting(List<String> unsorted) {
// Write your code here
unsorted.sort((a,b) -> {
if(a.length() != b.length()) return a.length() - b.length();
return a.compareTo(b);
});
return unsorted;
}
Problem Solution in JavaScript
function bigSorting(unsorted) {
let len = unsorted.length;
for(let i=0;i<len; i++) unsorted[i] = BigInt(unsorted[i]);
unsorted.sort((a,b) => {
if(a > b) return 1;
else if (a < b) return -1;
else return 0;
})
return unsorted;
}
Leave a Reply