In this post, we will solve HackerRank Big Sorting Problem Solution.
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.
Example
unsorted = [‘1’, ‘200’, ‘150’, ‘3’]
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, n, the number of strings in unsorted.
Each of the n subsequent lines contains an integer string, unsorted[i].
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
unsorted = [31415926535897932384626433832795, 1, 3, 10, 3, 5]. When we order each string by the real-world integer value it represents, we get:
1335 1031415926535897932384626433832795
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 C Solution
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int cmp(const void *a, const void *b){
char *sa=*(char **)a;
char *sb=*(char **)b;
// cannot do simple strcmp, need to account also for strlen
int la=strlen(sa), lb = strlen(sb);
if(la==lb)
return strcmp(sa,sb);
else
return la<lb ? -1 : la>lb;
}
int main(){
// Enter your code here. Read input from STDIN. Print output to STDOUT
int n;
scanf("%d",&n);
char **s=malloc(n*sizeof(char *));
char stemp[1000001];
for(int i=0;i<n;i++){
scanf("%s",stemp);
s[i]=(char *)malloc((strlen(stemp)+1)*sizeof(char));
strcpy(s[i],stemp);
}
qsort(s,n,sizeof(char *),cmp);
for(int i=0;i<n;i++){
printf("%s\n",s[i]);
}
return 0;
}
Big Sorting C++ Solution
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <map>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n;
cin >> n;
map<int,vector<string>> m;
while(n--){
string s;
cin >> s;
m[s.length()].push_back(s);
}
for(auto& v : m){
sort(v.second.begin(),v.second.end());
}
for(auto& v : m){
for(auto& x : v.second){
cout << x << '\n';
}
}
return 0;
}
Big Sorting C Sharp Solution
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics;
class Solution {
static void Main(String[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
String [] S = new String[n];
for(int i = 0; i < n; i++) S[i] = Console.ReadLine().Trim();
Array.Sort(S, StringAsIntegerCompare);
Console.WriteLine(string.Join(Environment.NewLine, S));
}
void BigSortingUsingInBuiltQuickSortOP()
{
int n = Convert.ToInt32("6");
string [] S = { "2", "1", "3", "10", "3", "5" };
Console.WriteLine(string.Join(" ", S));
Array.Sort(S, StringAsIntegerCompare);
Console.WriteLine(string.Join(" ", S));
}
static int StringAsIntegerCompare(String s1, String s2)
{
if(s1.Length > s2.Length) return 1;
if(s1.Length < s2.Length) return -1;
for(int i = 0; i < s1.Length; i++)
{
if((int)s1[i] > (int)s2[i]) return 1;
if((int)s1[i] < (int)s2[i]) return -1;
}
return 0;
}
}
Big Sorting Java Solution
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
class Result {
/*
* Complete the 'bigSorting' function below.
*
* The function is expected to return a STRING_ARRAY.
* The function accepts STRING_ARRAY unsorted as parameter.
*/
public static List<String> bigSorting(List<String> unsorted) {
Map<Integer, List<String>> coll = new TreeMap();
for(String s: unsorted){
Integer key= s.length();
if(coll.containsKey(key)){
coll.get(key).add(s);
}else{
List<String> list= new ArrayList<>();
list.add(s);
coll.put(key, list);
}
}
List<String>result= new ArrayList<>();
for(var entry: coll.entrySet()){
Collections.sort(entry.getValue());
result.addAll(entry.getValue());
}
return result;
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int n = Integer.parseInt(bufferedReader.readLine().trim());
List<String> unsorted = IntStream.range(0, n).mapToObj(i -> {
try {
return bufferedReader.readLine();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
})
.collect(toList());
List<String> result = Result.bigSorting(unsorted);
bufferedWriter.write(
result.stream()
.collect(joining("\n"))
+ "\n"
);
bufferedReader.close();
bufferedWriter.close();
}
}
Big Sorting JavaScript Solution
process.stdin.resume();
process.stdin.setEncoding('ascii');
var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;
process.stdin.on('data', function (data) {
input_stdin += data;
});
process.stdin.on('end', function () {
input_stdin_array = input_stdin.split("\n");
main();
});
function readLine() {
return input_stdin_array[input_currentline++];
}
/////////////// ignore above this line ////////////////////
function main() {
var n = parseInt(readLine());
var unsorted = [];
for(var unsorted_i = 0; unsorted_i < n; unsorted_i++){
unsorted[unsorted_i] = readLine();
}
// your code goes here
unsorted.sort(function(a,b) {
if (a.length > b.length) {
return 1;
} else if (a.length == b.length) {
var aChars = a.split('');
var bChars = b.split('');
for (var iter = 0; iter < a.length && iter < b.length; iter++) {
var currentANum = parseInt(aChars[iter]);
var currentBNum = parseInt(bChars[iter]);
if (currentANum > currentBNum) {
return 1;
} else if (currentANum < currentBNum) {
return -1;
} else {
// Do nothing so that we fall to the next character position comparison
}
}
return 0;
} else {
return -1;
}
});
unsorted.forEach(function(currentItem) {
console.log(currentItem);
});
}
Big Sorting Python Solution
#!/bin/python3
import sys
n = int(input().strip())
ordem = {}
unsorted_i = 0
for unsorted_i in range(n):
unsorted_t = str(input().strip())
size = len(unsorted_t)
if size in ordem:
ordem[size].append(unsorted_t)
else:
ordem[size] = [unsorted_t]
tamanhos = sorted(ordem)
for t in tamanhos:
l = sorted(ordem[t])
for n in l:
print(n)
Other Solutions
Good blog you have got here.. It’s difficult to find quality writing like yours nowadays. I truly appreciate individuals like you! Take care!!
Very nice article. I absolutely appreciate this site. Keep it up!
Hello there! This post couldn’t be written any better! Reading through this article reminds me of my previous roommate! He continually kept preaching about this. I will forward this information to him. Pretty sure he will have a good read. Thanks for sharing!
I blog quite often and I genuinely thank you for your information. This article has really peaked my interest. I will bookmark your website and keep checking for new information about once per week. I opted in for your RSS feed too.
That is a great tip especially to those new to the blogosphere. Short but very precise information… Many thanks for sharing this one. A must read article!
This website was… how do you say it? Relevant!! Finally I’ve found something that helped me. Appreciate it!
Good post. I’m dealing with many of these issues as well..
I really like reading a post that can make men and women think. Also, thanks for allowing me to comment.
May I simply say what a relief to find somebody that really knows what they’re discussing online. You actually understand how to bring an issue to light and make it important. More and more people really need to read this and understand this side of your story. It’s surprising you’re not more popular because you most certainly have the gift.
bookmarked!!, I really like your blog.
Oh my goodness! Awesome article dude! Thank you so much, However I am experiencing troubles with your RSS. I don’t understand why I am unable to subscribe to it. Is there anybody else getting identical RSS problems? Anybody who knows the solution can you kindly respond? Thanks.
Hello there, I do believe your website could possibly be having browser compatibility problems. When I look at your website in Safari, it looks fine however, when opening in I.E., it’s got some overlapping issues. I merely wanted to provide you with a quick heads up! Apart from that, excellent website!
You’re so interesting! I do not believe I’ve read through anything like this before. So nice to find another person with some original thoughts on this subject. Really.. thank you for starting this up. This website is one thing that is needed on the internet, someone with a bit of originality.