I tested my code fr several inputs like
592 593 0 59 592 7
n I’m getting right answer fr these…can someone who solved the problem tell me wt’s wrong with my code ? ?
The correct solution is to sort strings using comparator
bool cmp(string a, string b) {
return a+b > b+a;
}
Here a+b is the concatenation of strings. The intuitive proof: if we put numbers in some order and a and b some two consecutive strings in the list then if a+b < b+a it is advantageous to swap them. Indeed, if we swap them we exactly change substring a+b by b+a in the result.
But to get a complete proof one should prove that cmp is indeed the correct ordering. In particular one should prove transitivity property:
If a+b > b+a and b+c > c+b then a+c > c+a
Several years ago I spent several hours for this and wrote several pages of calculations to prove this
As @vidhant noted the trickiest cases are when some strings are prefixes of other strings.
It is possible to create even trickier test:
3 31 314
The optimal answer is 331431. So we take the shortest string then the largest and then the middle one.
n I gt my missing case in a lecture today
56 569 should be 56956 n 56569…so I had to compare larger string’s next digit with the short one’s 1st digit…missed that one…
@anton_lunyov thnxxx that’s probably the best solution…