This problem is from Five programming problems every Software Engineer should be able to solve in less than 1 hour which itself is an interesting read. The first few problems are trivial, but the fourth one can be a bit more interesting.

Given a list of integers separated by a single space on standard input, print out the largest and smallest values that can be obtained by concatenating the integers together on their own line.

For example:


5 56 50



Various points of order:

  • The order of the results are smallest then largest.
  • Only the smallest and largest values may be printed out (iterating over all the variations and printing them out isn't valid).
  • There will always be two or more integers in the list.
  • It is possible for the largest and smallest results to be the same. In the case of input 5 55, the number 555 should be printed twice.
  • The integers are not necessarily distinct. 5 5 is valid input.
  • Leading 0s on integers are not valid input. You will not need to account for 05 55.

As this is code golf, shortest entry wins.

  • \$\begingroup\$ If one of the input numbers contain a leading 0 (like 05), do we consider it as 05 or simply 5 ? \$\endgroup\$ – Optimizer May 8 '15 at 22:23
  • \$\begingroup\$ @Optimizer leading zeros are not valid input. \$\endgroup\$ – user12166 May 8 '15 at 22:25
  • \$\begingroup\$ Are leading 0s allowed in output? \$\endgroup\$ – Tim May 9 '15 at 8:58
  • \$\begingroup\$ @Tim Where would those come from if there are no leading zeroes in the input? \$\endgroup\$ – Martin Ender May 9 '15 at 9:40
  • \$\begingroup\$ @MartinBüttner oh yes, being silly! \$\endgroup\$ – Tim May 9 '15 at 9:40

13 Answers 13


CJam, 14 13 bytes


Pretty straight forward. This is how it works:

qS/                  e# Split the input on spaces
   e!                e# Get all permutations of the input numbers
     :s              e# Join each permutation order into a single string
       $             e# Sort them. This sorts the strings based on each digit's value
        (N@W=        e# Choose the first and the last out of the array separated by '\n'

Try it online here

  • 1
    \$\begingroup\$ OK, I give up. I didn't now e! existed (doesn't even appear in the wiki yet). \$\endgroup\$ – Dennis May 8 '15 at 22:18
  • 5
    \$\begingroup\$ @Dennis there you go \$\endgroup\$ – Optimizer May 8 '15 at 22:18
  • 1
    \$\begingroup\$ Sweet read. Lots of useful new stuff. \$\endgroup\$ – Dennis May 8 '15 at 22:22
  • \$\begingroup\$ It might be useful to update Tips for golfing in CJam with these additional tricks. \$\endgroup\$ – user12166 May 9 '15 at 16:24
  • 1
    \$\begingroup\$ @MichaelT tips generally are not supposed to contain answer which explain the in built features of a language. A couple of answer might need updating as they might benefit from these new features though. \$\endgroup\$ – Optimizer May 9 '15 at 17:18

Pyth, 14 13 bytes


Generates all permutations and sorts them, printing the first and last element.

  • \$\begingroup\$ Assign J inline: hJSmsd.pcz)eJ \$\endgroup\$ – isaacg May 9 '15 at 6:47
  • \$\begingroup\$ @isaacg Good one! I just knew we wouldn't be inferior to that filthy filthy CJam! \$\endgroup\$ – orlp May 9 '15 at 7:59

Python 2, 104 99 bytes


from itertools import*;z=[''.join(x)for x in permutations(raw_input().split())];print min(z),max(z)

Edit: thanks to xnor for -5 bytes!

  • 1
    \$\begingroup\$ The comprehension inside sorted works without brackets, but you also can avoid sorting and just take min and max. \$\endgroup\$ – xnor May 9 '15 at 0:32
  • \$\begingroup\$ hah, yes. thank you! \$\endgroup\$ – sirpercival May 9 '15 at 1:04

Mathematica, 64 58 bytes


This defines an unnamed function taking a string and printing the two lines. It's pretty straightforward as the others: get all permutations, join them together, sort them and print the first and last result.

Six bytes saved thanks to alephalpha.

  • \$\begingroup\$ {#&@@#,Last@#}=>#[[{1,-1}]] \$\endgroup\$ – alephalpha May 9 '15 at 7:30
  • \$\begingroup\$ @alephalpha Sometimes simpler is better. Thanks! :D \$\endgroup\$ – Martin Ender May 9 '15 at 9:37

JavaScript (ES6) 54 72 85

That's easier than it seems. Just sort them lexicographically. The good news is: that's exactly how plain javascript sort works.Well ... no, that's wrong ... still a (more convoluted) lexicograph compare can do the job.

Note: having a and b numeric, a+[b] is a shortcut for a+''+b, as we need a string concatenation and not a sum.
Note 2: the newline inside `` is significant and must be counted

Edit Don't argue with a moderator (...just kidding)

Edit2 Fixed I/O format using popups (see Default for Code Golf: Input/Output methods)

// Complete program with I/O
// The sorting function is shorter as input are strings

alert((l=prompt().split(' ')).sort((a,b)=>a+b>b+a).join('')+`

// Testable function (67 chars)
// With an integer array parameter, the sorting function must convert to string 


Test In Firefox / FireBug console

F([50, 2, 1, 9])






  • 1
    \$\begingroup\$ I think your input format is wrong. Should be "integers separated by a single space on standard input". \$\endgroup\$ – nimi May 9 '15 at 12:19
  • \$\begingroup\$ @nimi you're right.Fixed \$\endgroup\$ – edc65 May 9 '15 at 12:59

J, 34 36, 42 bytes

simple brute force:

h=:3 :'0 _1{/:~;"1":&.>y A.~i.!#y'

h 5 50 56

h 50 2 1 9

Haskell, 98 bytes

import Data.List
g=sort.map concat.permutations.words
h i=unlines[g i!!0,last$g i]
main=interact h

Split input string at spaces, concatenate every permutation and sort. Print first and last element.


Julia, 77 bytes

v->(Q=extrema([int(join(x)) for x in permutations(v)]);print(Q[1],"\n",Q[2]))

This creates an unnamed function that accepts a vector as input and prints the minimum and maximum of the permutations of the joined elements. To call it, give it a name, e.g. f=v->....

Ungolfed + explanation:

function f(v)
    # Create an integer vector of the joined permutations using comprehension,
    # then get the minimum and maximum as a tuple using extrema().

    Q = extrema([int(join(x)) for x in permutations(v)])

    # Print the minimum and the maximum, separated by a newline.
    print(Q[1], "\n", Q[2])

Suggestions are welcome!


Javascript (ES6) 134

Sadly, there's no built-in permutation function in JS :(

f=(o,y,i,a)=>y?o.concat(a[1]?a.filter((k,j)=>j^i).reduce(f,[]).map(z=>y+z):y):(q=o.split(' ').reduce(f,[])).sort().shift()+`
<!-- Snippet Demo (Firefox only) -->

<input id="input" value="5 56 50" />
<input type="button" onclick="output.innerHTML=f(input.value)" value="Run" />
<pre id="output"></pre>


R, 59 bytes

  • 1
    \$\begingroup\$ Nice work. You can save a byte by using just two colons though, i.e. combinat::permn. \$\endgroup\$ – Alex A. May 11 '15 at 15:59
  • \$\begingroup\$ I thought :: required the package to be loaded (via library or require) but not :::. I could be wrong; need to read a little more about it. Thanks. \$\endgroup\$ – flodel May 11 '15 at 23:03
  • \$\begingroup\$ If the library is loaded, you don't need the colons at all; you can just call the function directly since the package is attached to the namespace. If the package is installed but not loaded, you can reference functions in a particular package with two colons. \$\endgroup\$ – Alex A. May 11 '15 at 23:08
  • \$\begingroup\$ So 58 it can be. I would not allow myself using permn directly without a library(combinat). \$\endgroup\$ – flodel May 11 '15 at 23:10
  • \$\begingroup\$ Yeah, because you have to load the library with library(combinat) before you could use permn anyway. ;) \$\endgroup\$ – Alex A. May 11 '15 at 23:18

Ruby 75

Not my 'native' language, but one I thought I'd give a try at... thus this could (possibly) use some golfing tips. Still, not a bad entrant.

puts STDIN.read.split(" ").permutation.map{|x|x.join}.sort.values_at(0,-1)

I wouldn't say it is elegant other that everything is built in to the language. It should be fairly obvious exactly how this works.


Perl, 79 70B (68+2)

use Math::Combinatorics;say for(sort map{join'',@$_}permute@F)[0,-1]

Call with echo 13 42 532 3 6|perl -M5.10.0 -an scratch.pl. There's a +2 byte penalty for -an. Shame about the length of the module name...


JavaScript (ES6), 85 bytes

F=a=>(c=a.split(" ").sort((b,a)=>b+a-(a+b)),`${c.join("")}


F("50 2 1 9")
  • 1
    \$\begingroup\$ Don't fall in love with template strings. a+` `+b is shorter than `${a} ${b}` \$\endgroup\$ – edc65 May 10 '15 at 0:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy