Given an array of integers, received from stdin, function arguments, program arguments, or some other method:

Output only the minimum and maximum numbers in the array, through a return value, stdout, or other fitting methods.

Example session

> minmax( {0, 15, 2, 3, 7, 18, -2, 9, 6, -5, 3, 8, 9, -14} )
-14 18

Reference implementation

// C++14

void minmax(std::vector<int> v) {
    int min = v[0]; int max = v[0];
    for(auto it : v) {
        if (*it < min)
            min = *it;
        if (*it > max)
            max = *it;
    std::cout << min << ' ' << max << std::endl;


  • You may not use a built-in function to calculate the values.
  • Standard loopholes disallowed.
  • Creative implementations encouraged.
  • This is , shortest answer wins but will not be selected.


  • If the array contains 1 element you need to output it twice.
  • If the minimum and maximum values are the same, you need to output them both.
  • 12
    This is a do X without Y challenge, which aren't particularly interesting. – Mego Aug 23 '16 at 21:31
  • 5
    @DmitryKudriavtsev Try the sandbox next time. – Mego Aug 23 '16 at 21:38
  • 5
    Seriously, use the Sandbox. Your changes to the challenge have invalidated every single answer. – Mego Aug 23 '16 at 21:58
  • 1
    I encouraged creative methods No, you encouraged short solutions, by tagging it code golf – Luis Mendo Aug 24 '16 at 1:24
  • 1
    As said Luis Mendo Yes, everyone is just posting "i sort your array using a built-in and take first and last", in different languages, not really creative :x – Walfrat Aug 24 '16 at 11:15

50 Answers 50

Jelly, 3 bytes


Try it online!

Sort the array, and then takes the 0.5-th element.

Jelly uses 1-indexing, and floating points indexing means take its floor and its ceil.

So the 0.5-th element would give you the 0th element and the 1st element.

The 0th element is the last element.

  • 2
    Pretty Clever I'm wait for it.... Jelly! – Rohan Jhunjhunwala Aug 23 '16 at 22:45
  • Oh, so that would make finding the median trivial. – Adám Aug 24 '16 at 7:54
  • 1
    @KonradRudolph This. – Leaky Nun Aug 24 '16 at 10:31
  • 1
    Don't you want the first and last elements, rather than the first two elements? Or have I misunderstood your explanation? – Toby Speight Aug 24 '16 at 10:44
  • 1
    @TobySpeight In 1-based indexing the 0th element is the last element. – Leaky Nun Aug 24 '16 at 11:46

Python, 61 49 37 36 34 31 bytes

lambda s:s.sort()or[s[0],s[-1]]

-12 bytes thanks to RootTwo

Another -12 bytes thanks to chepner

-2 bytes thanks to johnLate

-3 bytes thanks to johnLate

  • 1
    I changed the heading to Python because it works in Python 3 also. – Leaky Nun Aug 23 '16 at 21:44
  • 1
    You can golf off a dozen bytes: use [::(len(s)-1)or 1] for the first subscript. And the second term can be shortened to s[:len(s)<2]. – RootTwo Aug 24 '16 at 6:45
  • At the cost of sorting the list twice, you can shave off another 12 bytes: lambda s:sorted(s)[:1]+sorted(s)[-1:]. – chepner Aug 25 '16 at 3:37
  • save 6 bytes by lambda s:sorted(s)[::len(s)-1] – Aaron Sep 12 '16 at 17:50
  • The current version (lambda s:sorted(s)[::len(s)-1]) does not work for arrays with one element (ValueError: slice step cannot be zero). A possible fix would be lambda s:sorted(s*2)[::len(s*2)-1] (34 bytes). – johnLate Sep 12 '16 at 19:42

Brain-Flak 220 218 bytes


Try It Online!


First it doubles the top value (in cast the list is only one long)


Then it uses my bubble sort algorithm:


Then it picks up the top value of the stack (i.e. the min)


Then it pops until the height of the stack is one:


JavaScript (ES6), 34 bytes


sort sorts in-place, so I can just refer to the [0] index for the lowest value and pop the highest value from the array, however it does a string sort by default so I have to pass a comparator.

  • I don't think you need the (x,y)=>x-y part, unless using sort() with the default algorithm counts as a builtin. – Scott Aug 24 '16 at 17:48
  • 1
    @Scott But I don't want a lexical sort... – Neil Aug 24 '16 at 20:00
  • Right... I didn't test it with numbers > 10 or < 0. I didn't know sort() internally treats everything as strings - sorry! – Scott Aug 24 '16 at 20:05

Mathematica, 18 bytes


Sorts the array and extracts the first and last values.

R, 31 bytes


Not that original, but hey !

ARM Machine Code, 26 bytes

Hex dump (little endian):

6810 4601 f852 cb04 4560 bfc8 4660 4561 bfb8 4661 3b01 d8f5 4770

This is a function, with no system call or library dependence. The encoding is Thumb-2, a variable (2 or 4 byte) encoding for 32-bit ARM. As one might imagine, there's no easy way to just sort and pick the first and last elements here. Overall there's nothing really that fancy going on here, it's more or less the same as the reference implementation.

Ungolfed assembly (GNU syntax):

.syntax unified
.global minmax
    @Input: @r0 and r1 are dummy parameters (they don't do anything)
    @r2 - Pointer to list of integers (int*)
    @r3 - Number of integers to sort (size_t)
    @Minimum of the list in r0 (int)
    @Maximum in r1 (int)
    ldr r0,[r2] @min=r2[0]
    mov r1,r0 @max=min
        @ip is intra-procedure call register, a.k.a. r12
        ldr ip,[r2],#4 @ip=*r2++
        cmp r0,ip
        it gt @if (r0>ip)
        movgt r0,ip @r0=ip
        cmp r1,ip
        it lt @if (r1<ip)
        movlt r1,ip @r1=ip
        subs r3,r3,#1
        bhi loop @while (--r3>0)
    bx lr @Return

Tested on the Raspberry Pi 3; here's the testing script (C99, input through argv):

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
//First 2 arguments are dummies.
uint64_t minmax(int,int,int* array,size_t size);

int main(int argc,char** argv) {
    int i;
    int array[argc-1];
    for (i=1;i<argc;i++) {
    uint64_t result = minmax(0,0,array,argc-1);
    printf("Minimum is %d, maximum is %d.\n",(unsigned)result,(unsigned)(result>>32));

Octave, 20 bytes


This sorts the input vector and outputs the first and last value.

Actually, 5 bytes


Try it online!


S      sort
 ;     dupe
  F    first element
   @N  and last element

05AB1E, 6 4 bytes



{     # sort list
 Â    # bifurcate
  ø   # zip
   ¬  # head

Try it online

Haskell, 27 bytes

f x=(`foldl1`x)<$>[min,max]

In Haskell, min and max give minimum and maximum of two arguments, not of a list. I couldn't tell whether this is disallowed (it seems that instead only minimum and maximum would be disallowed) so please let me know if they are and I'll promptly delete this answer.

  • @nimi FGITW effect, sadly... – ThreeFx Aug 25 '16 at 5:26

MATL, 4 bytes


Try it online!


S    % Implicitly input the array. Sort
5L   % Push [1 0]. When used as a (modular, 1-based) index, this means "first and last"
)    % Apply as an indexing vector into the sorted array. Implicitly display

Python, 29 bytes

lambda s:s[s.sort():1]+s[-1:]

Test it on Ideone.

C, 83 81 79 bytes

m,M;f(a,s)int*a;{for(m=M=*a;s--;++a)*a<m?m=*a:*a>M?M=*a:0;pr‌​intf("%i %i",m,M);}
  • 1
    the declaration can turn into ...f(a,s)int*a{... per this – cat Dec 6 '16 at 15:50
  • 1
    You can combine the ternary expressions to get another 2 bytes off: m,M;f(a,s)int*a;{for(m=M=*a;s--;++a)*a<m?m=*a:*a>M?M=*a:0;printf("%i %i",m,M);} – gastropner Dec 18 '17 at 22:02
  • In gcc you can replace *a>M?M=*a:0 with *a<M?:M=*a – ceilingcat Jan 4 at 18:52

Brachylog, 9 bytes


Try it online!

V, 12 bytes


Try it online!

Credit to DJMcMayhem for this.

  • 1
    \o/ Yay, I'm no longer the only person to have ever used this language! – DJMcMayhem Aug 23 '16 at 22:07
  • 1
    If the input is a single number, that number still has to be output twice – Luis Mendo Aug 24 '16 at 2:15
  • @LuisMendo hm, will work on that. – Riker Aug 24 '16 at 4:00

CJam, 10 9 bytes


Try it online.

I'm really not good at CJam.

q~          e# eval input
  $         e# sort
   _        e# duplicate
    (       e# pop first
     p      e# print
      ;     e# remove array
       W>   e# get last element
  • The usual way to get the first element of a list is 0= (but that unfortunately that doesn't save any bytes). Two other 9-byte solutions: 0W]q~$f=p or the unnamed block {$2*_,(%}. – Martin Ender Aug 24 '16 at 7:36
  • 8 bytes: q~$(p)p;. You can use ) to get the last element like you use ( to get the first. – Business Cat Aug 24 '16 at 13:30
  • @BusinessCat That's what I originally had, but it fails for single-element input. – Pietu1998 Aug 24 '16 at 13:30
  • @Pietu1998: Oh, you're right. I didn't notice that. – Business Cat Aug 24 '16 at 13:31

Python 2, 34 bytes

x=sorted(input());print x[0],x[-1]

C#, 60 bytes

n=>{System.Array.Sort(n);return new[]{n[0],n[n.Length-1]};};

A naïve method at 93 bytes:

n=>{var r=new[]{n[0],n[0]};foreach(int i in n){if(i<r[0])r[0]=i;if(i>r[1])r[1]=i;}return r;};

PHP, 44 bytes

function a($a){sort($a);echo $a[0].end($a);}

Processing, 59 52 bytes

void m(int[]x){x=sort(x);print(x[0],x[x.length-1]);}

Processing doesn't actually let me read from stdin that I've been able to find, and I don't know if its internal Java compiler supports lambdas (and its been so long since I've had to write serious Java that I don't remember how).

  • You can save bytes by removing spaces after int[] – Cows quack Dec 4 '16 at 18:33

Perl 6 13 bytes



my &min-max = *.sort[0,*-1];

say min-max 1;
# (1 1)
say min-max (0, 15, 2, 3, 7, 18, -2, 9, 6, -5, 3, 8, 9, -14)
# (-14 18)
  • Darn, you beat me there! – bb94 Aug 25 '16 at 1:23

POSIX Awk, 44 bytes

awk '{for(;NF-1;NF--)if($1>$NF)$1=$NF}1' RS=

Octave, 35 bytes

@(x)[x(all(t=x<=x')) x(sum(t)==1)]

This is an anoynymous function. Try it at ideone.

The code avoids using sorting. Namely, it does all pairwise "less than or equal" comparisons between elements of the input. The minimum is the element for which all comparisons are true. The maximum is that for which only one comparison is true.

Python, 35 34 bytes

lambda s:sorted(s+s[:1])[::len(s)]

Alternative version:

lambda s:sorted(s+s)[::len(s)*2-1]

Old version, 35 bytes.

lambda s:sorted(s+[s[0]])[::len(s)]

Fairly simple: take the input list, append the first element, sort it, then take the first and (length)th element of the resulting list. As the length of the input after appending an element is length + 1, this ends up taking the first and last element of said list, which are the minimum and maximum elements.

  • 1
    Though not the shortest answer in Python, this is very creative! +1 – mbomb007 Aug 24 '16 at 18:24
  • The 34-byte one doesn't work in Python 3; this works in both 2 and 3. Also, it was posted after this one. – TLW Aug 25 '16 at 0:59
  • @mbomb007 - fine, golfed. This is now tied for the shortest Python implementation, and as a bonus it works in both 2 and 3. – TLW Aug 25 '16 at 1:04

zsh, 22 bytes

(){echo $1 $_} ${(n)@}

defines a lambda function that prints its first arg ($1) and the last argument to the previous command ($_), and passes it $@ after sorting it so the previous command becomes the invocation of that lambda

zsh, 21 bytes

this only works fine if there's more than 1 argument :(

<<<"${${(n)@}/ * / }"

sorts $@, makes it a string and replaces everything from the first space to the last one with a single space, then passes it as input to cat with <<<


$ ./minmax 23 342 21 10
10 342

Scala, 55 bytes

print(s.head+" "+s.last)

To execute:

$ scala minmax.scala 1 2 3 4 5 6 7 8 9

Bash + coreutils, 30 bytes

tr \  \\n|sort -n|sed '$p;1!d'

The sed script prints, after the input is sorted, the first and last integers.

dc, 110 bytes


Help me, dcers! You are my only hope!

Thanks to @seshoumara for finding that bug!

I'll add an explanation later. Here it is broken up a bit:

?dd sM sm
zd sA sa
[z 1- :a z0<S]dsSx
[lQx la 1- dsa ;a l?x la0<N]dsNx
lA sa
 [la;a sm]sR
lm lM f
  • I didn't record how to invoke this, and now I can't remember. Whatever I'm doing now, I'm doing it wrong, because this is always returning 0 as the smallest element. – Joe Aug 27 '16 at 21:52
  • 1
    Pfew! It took some starring at it, but found the bug in your code. It's the first character (0) which you duplicate and initialize registers M and m. But if in the input list no number is smaller than m=0, or no number is greater than M=0, then you get an incorrect result, because you artificially added 0 to the sample numbers. The solution is to replace that first 0 with ?d, which reads the numbers and initializes M and m with the last number, thus making it a part of the sample. Then run the code like this: echo "8 _2 5"|dc -e "?ddsMsm....". – seshoumara Sep 8 '16 at 9:54
  • Wow, thanks, @seshoumara! I never would have noticed that! (I'd forgotten all about this question, too :P) – Joe Sep 12 '16 at 18:51

Java, 115 bytes

String f(int[]i){int t=i[0],a=t,b=t;for(int c=0;c<i.length;c++){a=i[c]<a?i[c]:a;b=i[c]>b?i[c]:b;}return""+a+" "+b;}


String f(int[] i) {
    int t=i[0], a=t, b=t; // assigns a and b to i[0]
    for (int c=0; c < i.length; c++) { // loop through the array
        a=(i[c]<a) ? i[c] : a;
        b=(i[c]>b) ? i[c] : b; // assignment with ternary operator
    return ""+a+" "+b; // returns a string

My first ever code "golf" solution.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.