Biggest number concatenation

Problem


Given a list of integers, find the highest value obtainable by concatenating these together.
For example, given numbers, {1000, 898, 77, 55,8989}, 898989877551000 will be the biggest number that can be produced. 

Roughly, we can sort the integers in descending order and concatenate them. This will run in O( N log N), where N is the number of integers in the input list.

It is very simple isn't it? Then, why is this problem marked as Medium difficulty?
Should "89" come before "1000" during the sorting?
How about 998 and 9989? Which should come first?

It is so easy to overlook the problem and get it all wrong. Remember, you need to finish writing the complete code less than 30 mins. We can't afford this kind of mistake.

I would not explain in details about the comparison algorithm since it is quite straightforward.
If you still have doubt after seeing the code, please let me know. I will add further explanation.

Here is the complete code running in O ( N log N).

#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
bool compare(string prev, string next)
{
int lpos = 0, rpos= 0;
while (lpos < prev.length() && rpos < next.length())
{
if (prev[lpos] > next[rpos])
return true;
else if (prev[lpos] < prev[rpos])
return false;
lpos++;
rpos++;
}
if (rpos < next.length())
return ( prev[lpos-1] > next[rpos]);
else if (lpos< prev.length())
return (prev[lpos] > next[rpos-1]);
return true;
}
string produce_biggest_number(vector<string> & input)
{
string result ="";
sort(input.begin(), input.end(), compare);
for (int i =0; i< input.size(); i++)
{
cout <<input[i]<<endl;
result += input[i];
}
return result;
}
int main ()
{
vector<string> input;
input.push_back("1000");
input.push_back("898");
input.push_back("77");
input.push_back("55");
input.push_back("8989");
cout<<compare("898", "8989")<<endl;
cout<<"biggest number is = "<<produce_biggest_number(input)<<endl;
}

Practice statistics
21.56 mins : to write up the code but made seriously logical mistake in the compare function.
18.00 mins : to find the bug through the compilation. This should not happen.


Comments

Popular posts from this blog

Planting flowers with no adjacent flower plots

Find the shorted path from the vertex 0 for given list of vertices.