Given a nonempty array of positive integers, "increment" it once as follows:

  • If all the array elements are equal, append a 1 to the end of the array. For example:

    [1] -> [1, 1]
    [2] -> [2, 1]
    [1, 1] -> [1, 1, 1]
    [3, 3, 3, 3, 3] -> [3, 3, 3, 3, 3, 1]
  • Else, increment the first element in the array that is the array's minimum value. For example:

    [1, 2] -> [2, 2]
    [2, 1] -> [2, 2]
    [3, 1, 1] -> [3, 2, 1] -> [3, 2, 2] -> [3, 3, 2] -> [3, 3, 3]
    [3, 4, 9, 3] -> [4, 4, 9, 3] -> [4, 4, 9, 4] -> [5, 4, 9, 4] -> [5, 5, 9, 4] -> ...

(Each -> represents one increment, which is all your program needs to do.)

Output the resulting incremented array.

The shortest code in bytes wins.

  • \$\begingroup\$ Does 0 count as positive integer \$\endgroup\$
    – Downgoat
    Commented Nov 28, 2016 at 23:14
  • 33
    \$\begingroup\$ @Downgoat 0 is not ever positive on PPCG. If 0 was allowed, the term would be "non-negative" \$\endgroup\$ Commented Nov 28, 2016 at 23:23

57 Answers 57


Jelly, 8 7 bytes


Try it online! or verify all test cases.

How it works

‘;ṀỤḢṬ+  Main link. Argument: A

‘        Increment all elements of A.
  Ṁ      Yield the maximum of A.
 ;       Concatenate both results. Note that the appended maximum will be the 
         minimum of the resulting array if and only if all elements of A are equal.
   Ụ     Grade up; yield the indices of the resulting array, sorted by their
         corresponding values in that array.
    Ḣ    Head; extract the first index, which is the index of the first occurrence
         of the minimum. For an array of equal elements, this will be the index
         of the appended maximum.
     Ṭ   Untruth; for index i, yield an array of i-1 zeroes, followed by a 1.
      +  Add this array to A, incrementing the minimum or appending a 1.

Python 3, 62 53 51 50 bytes

Function which modifies the list passed to it (allowed by meta).

def F(a):a+=1//len({*a})*[0];a[a.index(min(a))]+=1

Try on repl.it!

-9 bytes thanks to Lynn for spotting that, because the array will be of positive integers, I can append '0' to the end of the array and have that incremented.

Special thanks to mbomb007 for golfing len(set(a)) to len({*a}), and Dennis for the floordiv trick!

  • \$\begingroup\$ Hmm. "Output the resulting incremented array". Does this qualify? \$\endgroup\$
    – Yytsi
    Commented Nov 28, 2016 at 20:02
  • \$\begingroup\$ I can't quite remember where, but I remember seeing a meta post that modifying a given list in place is allowed by default. I'll have a look for it @TuukkaX \$\endgroup\$
    – FlipTack
    Commented Nov 28, 2016 at 20:04
  • \$\begingroup\$ @TuukkaX I'm not entirely sure. It seems ok but I'll defer to the meta concensus about modifying arrays in place, if there is one. \$\endgroup\$ Commented Nov 28, 2016 at 20:04
  • 1
    \$\begingroup\$ In Python 3, you can use len({*L})<2 to find if all elements of a list are equal. \$\endgroup\$
    – mbomb007
    Commented Nov 28, 2016 at 21:20
  • 2
    \$\begingroup\$ a+=1//len({*a})*[0] should save a byte. \$\endgroup\$
    – Dennis
    Commented Nov 29, 2016 at 0:17

Mathematica, 70 57 55 bytes

Virtually all of the improvement is due to Martin Ender, who kicks my ass at pattern matching approaches! Also JHM came up with essentially the same solution at essentially the same time. (byte count uses ASCII encoding)

±{p:x_ ..}:={p,1};±{x___,y_,z___}/;y≤x~Min~z:={x,y+1,z}

Defines a function ± taking one list argument. If that list argument contains some number of copies of the same element (detected by x_.. and named p), then output the list with a 1 appended. Otherwise, if that list argument has a special element y (with x being the zero or more elements before y, and z being the zero or more elements after y) which is at most the minimum of the other elements, then output the list with that y incremented. Any instance of the minimum element of the list will be matched by y, but fortunately Mathematica chooses the first one to act upon.

  • \$\begingroup\$ Because ± is a 2-byte character, your code is 59 bytes long. Also, there must be a space between x_ and .. because Mathematica interprets x_.. as x_. . (which throws errors). Plus, the infix form of Min (x~Min~z) would make this 2 bytes shorter (which makes this solution identical to one of mine :p ...) Welp you can take the credit because my edit was later than yours.... \$\endgroup\$ Commented Nov 29, 2016 at 1:08
  • \$\begingroup\$ Nah, Martin Ender gets most of my credit anyway. Why is ± two bytes? \$\endgroup\$ Commented Nov 29, 2016 at 3:31
  • \$\begingroup\$ @GregMartin ± in UTF-8 (Mathematica uses UTF-8 by default; try $CharacterEncoding) is a two-byte character (U+00B1). \$\endgroup\$ Commented Nov 29, 2016 at 4:12
  • \$\begingroup\$ @JHM UTF-8 is not the default character encoding on Windows. Mathematica can read source files in a single-byte code page that includes ±. \$\endgroup\$ Commented Nov 29, 2016 at 5:49
  • 2
    \$\begingroup\$ @ASimmons My fresh Mathematica installation on Windows, which has $CharacterEncoding set to WindowsANSI which is CP1252 (which is sufficiently compatible with ISO 8859-1 for ± and · to be usable for a single byte). \$\endgroup\$ Commented Nov 29, 2016 at 18:30

JavaScript (ES6), 61 bytes

a=>new Set(a).size>1?++a[a.indexOf(Math.min(...a))]:a.push(1)

Outputs by modifying its argument. I can't find a way to determine whether an array has only one unique item in less that 17 bytes, but suggestions are welcome.

Test snippet

f=a=>new Set(a).size>1?++a[a.indexOf(Math.min(...a))]:a.push(1)
g=a=>0 in a?console.log("Input:",`[${a}]`,"Output:",`[${f(a),a}]`):console.log("Invalid input")

<input id=I value="1,2,2,3"><button  onclick="g(I.value.match(/\d+/g)||[])">Run</button>

Other attempts

Here are a few alternate ways of deciding whether the array has more than one unique input:


Both of the somes can be replaced with find as well. .sort would be shorter for finding the minimum, if the default sort wasn't lexicographical (why, JS, why?):

a=>new Set(a).size>1?++a[a.indexOf(a.sort()[0])]:a.push(1)
// Instead we have to do:
a=>new Set(a).size>1?++a[a.indexOf(a.sort((x,y)=>x-y)[0])]:a.push(1)

I tried recursion to find the minimum, but it turned out way longer:


And here's a string-based solution which seemed like a good idea at first: (input is given in array format in a string, e.g. "[1,2,3]")

  • \$\begingroup\$ Is using a.find(n=>n==Math.min(...a)) shorter? \$\endgroup\$
    – Downgoat
    Commented Nov 28, 2016 at 23:13
  • \$\begingroup\$ @Downgoat I'm not sure how I'd use that, as it returns the item rather than the index \$\endgroup\$ Commented Nov 28, 2016 at 23:15
  • \$\begingroup\$ yeah >_> whoops, I missed your ++ and didn't realize you needed a reference \$\endgroup\$
    – Downgoat
    Commented Nov 28, 2016 at 23:16

05AB1E, 21 20 16 bytes

Saved 4 bytes thanks to Adnan.


Try it online!


                      # input = [3,2,1] used as example
D                     # duplicate input
 Ùgi                  # if all elements are equal
    0¸«}              # append 0
        Ð             # triplicate list
                      # STACK: [3,2,1], [3,2,1], [3,2,1]
         Wk           # index of minimum element
                      # STACK: [3,2,1], [3,2,1], 2
           s          # swap top 2 elements of stack
                      # STACK: [3,2,1], 2, [3,2,1]
            g         # length of list
                      # STACK: [3,2,1], 2, 3
             Ý        # range [0 ... length]
                      # STACK: [3,2,1], 2, [0,1,2,3]
              Q       # equal
                      # STACK: [3,2,1], [0,0,1,0]
               +      # add
                      # OUTPUT: [3,2,2]
  • \$\begingroup\$ I think that DÙgi0¸«}ÐWksgÝQ+ also works. \$\endgroup\$
    – Adnan
    Commented Nov 28, 2016 at 20:47
  • \$\begingroup\$ @Adnan: Aah, nice idea using ÝQ with k. Thanks! \$\endgroup\$
    – Emigna
    Commented Nov 28, 2016 at 21:16
  • \$\begingroup\$ 11 bytes \$\endgroup\$ Commented Jan 12, 2022 at 10:17

C++14, 178 176 174 155 142 135 bytes


[](auto&l){auto e=end(l),b=begin(l);l.size()^count(b,e,*b)?++*min_element(b,e):(l.push_back(1),0);};


std::list<int> s = {4, 4, 9, 4};

//invoke like this
auto i = [](auto&l){auto e=end(l),b=begin(l);l.size()^count(b,e,*b)?++*min_element(b,e):(l.push_back(1),0);};

//or like that
[](auto&l){auto e=end(l),b=begin(l);l.size()^count(b,e,*b)?++*min_element(b,e):(l.push_back(1),0);}(s);


#include <list>
#include <algorithm>
#include <iostream>
using namespace std;

void i(list<int>& l) {
    auto e = l.end(), b = l.begin();
    if (l.size() == count(b, e, l.front())) {
    } else {
        ++*min_element(b, e);

int main() {
    list<int> s = {4, 4, 9, 4};

    //invoke like this
    for (auto o:s)
        std::cout << o << ' ';
    std::cout << std::endl;

This is my first time playing golf, help is appreciated.

EDIT: forgot to mention you have to compile it with at least -std=c++11 -std=c++14

EDIT2: I realized i can leave out the space in the includes #include <list>

EDIT3: saved two more bytes by replacing l.begin() by begin(l)

EDIT4: saved another 19(!) bytes thanks to @Quentin (see his comment)

EDIT5: Quentin shaved off 13 more bytes, thanks!

EDIT6: as TuukkaX pointed out, unnamed lambdas/functions suffice so i removed the auto i= in the bytecount

  • 5
    \$\begingroup\$ I can't help you with C++, but I can say: Welcome to PPCG! \$\endgroup\$
    – Zgarb
    Commented Nov 29, 2016 at 10:25
  • 2
    \$\begingroup\$ I think you don't need the spaces in the #include lines. \$\endgroup\$ Commented Nov 29, 2016 at 10:29
  • \$\begingroup\$ Oh thank you I just realized it myself :) \$\endgroup\$
    – neop
    Commented Nov 29, 2016 at 10:30
  • 1
    \$\begingroup\$ Replacing the function with a lambda (auto i=[](auto&l){...};) saves one byte (more if we count the return type you forgot ;) ), using ^ instead of == and swapping the operands saves another. std::list's iterators are certainly std:: classes, so you can drop std:: from both std::count and std::min_element thanks to ADL (-10). l.front() is also *b (-7). I end up with a 120-byte auto i=[](auto&l){auto e=end(l),b=begin(l);l.size()^count(b,e,*b)?void(++*find(b,e,*min_element(b,e))):l.push_back(1);}; :) \$\endgroup\$
    – Quentin
    Commented Nov 30, 2016 at 19:50
  • 1
    \$\begingroup\$ While we're at it, the documentation for std::min_element states that it returns the first smallest element, so the find() is superfluous, that's 11 bytes. In the conditional, using a pair of parentheses and the comma operator to coerce the right expression to int is shorter than casting the left one to void by 2 bytes. This leads to auto i=[](auto&l){auto e=end(l),b=begin(l);l.size()^count(b,e,*b)?++*min_element(b,e):(l.push_back(1),0);};, 142 bytes :) \$\endgroup\$
    – Quentin
    Commented Dec 1, 2016 at 9:03

Scratch, 25 34 blocks + 7 6 bytes


Takes input as a predefined array of integers. Note that arrays are 1-indexed in Scratch.

In Python, this would look like: (Note that unlike Scratch, Python is 0-indexed)

lowval = 0
hival = 0
n = 1
for i in range(len(input)):
    if(input[i] < input[lowval]):
        lowval = i
    if(input[i] > input[hival]):
        hival = i
    # No increment statement needed because python.
if(lowval == hival):
    input[lowval] += 1
  • \$\begingroup\$ Golfing comments please? \$\endgroup\$
    – AAM111
    Commented Nov 29, 2016 at 2:13
  • \$\begingroup\$ why do you declare fval? \$\endgroup\$
    – Christoph
    Commented Nov 29, 2016 at 6:47
  • 1
    \$\begingroup\$ It appears to me that Scratch is just Python in plain text with colors... \$\endgroup\$ Commented Nov 29, 2016 at 11:29
  • \$\begingroup\$ And 1-indexed arrays and no elif statements! \$\endgroup\$
    – AAM111
    Commented Nov 29, 2016 at 12:22
  • 1
    \$\begingroup\$ Good point @Christoph! It was part of an earlier version that got golfed out. Editing. \$\endgroup\$
    – AAM111
    Commented Nov 29, 2016 at 12:23

J, 25 22 bytes


Evaluates to an anonymous verb. Try It Online!


(+~:*[=<./)@,0#~1=#@~.  Input is y.
                  #@    Is the length of
                    ~.   deduplicated y
                1=       equal to 1?
            ,0#~        Append that many 0s to y (one or none).
(         )@            Call the result z and apply this verb to it:
      =                  take the bit array of equality
     [                   between z
       <./               and its minimum element,
    *                    multiply that element-wise by
  ~:                     the bit array of first occurrences in z
 +                       and add the result to z.

C#, 123 121 120 79 77 bytes

using System.Linq;l=>{if(l.All(o=>o==l[0]))l.Add(0);l[l.IndexOf(l.Min())]++;}

Modifies the argument passed to the function.

Thanks to Cyoce for saving 3 bytes! -> !Any to All, +=1 to ++.

Thanks to TheLethalCoder for saving a whopping 43 bytes! -> Removed method signature code. Removed parenthesis around the parameter list.

  • \$\begingroup\$ could you replace !l.Any(o=>o!=l[0])) with l.All(o=>o==l[0])? \$\endgroup\$
    – Cyoce
    Commented Nov 28, 2016 at 20:33
  • \$\begingroup\$ @Cyoce It indeed does. I thought of the same thing, but wrote Any instead of All and was in the thought, that it doesn't work :D Thanks! \$\endgroup\$
    – Yytsi
    Commented Nov 28, 2016 at 20:43
  • 2
    \$\begingroup\$ Does C# not have ++? \$\endgroup\$
    – Cyoce
    Commented Nov 28, 2016 at 22:39
  • \$\begingroup\$ You can compile to a Action<List<int>> to remove all of the method signature code \$\endgroup\$ Commented Nov 30, 2016 at 9:26
  • 1
    \$\begingroup\$ @Stefan Hmm. I've also seen many people drop the necessary usings with C#, so I don't trust that it's legal to drop using System.Linq off. Unless I see an explicit statement that says this isn't necessary, I'll stay with this. Thanks for the suggestion though! :) \$\endgroup\$
    – Yytsi
    Commented Dec 1, 2016 at 16:23

R, 72 66 65 bytes


Try it online!

Increment is done using which.min which returns the first match. "[<-" allows to replace the value and returns the modified vector in one function call.

-7 bytes thanks to Giuseppe!

  • \$\begingroup\$ tio.run/##K/r/… \$\endgroup\$
    – Giuseppe
    Commented Jun 6, 2018 at 1:42
  • \$\begingroup\$ @Giuseppe I tried isTRUE and isFALSE with sd it isn’t golfier :( \$\endgroup\$
    – JayCe
    Commented Jun 6, 2018 at 2:16
  • \$\begingroup\$ heh, 65 bytes replacing != with -! \$\endgroup\$
    – Giuseppe
    Commented Jun 6, 2018 at 10:12
  • \$\begingroup\$ @Giuseppe of course! \$\endgroup\$
    – JayCe
    Commented Jun 6, 2018 at 20:26

APL (Dyalog Unicode), 48 bytes


Try it online!

Alternate versions of 1+@(⊃⍋⍵)⊢⍵: ⍵+(⍳≢⍵)=⊃⍋⍵, ⊢+⍳∘≢=⊃∘⍋. -2 thanks to @Adam and @Razetime.


 1≥≢∪⍵                   ⍝ if all elements are identical
       ⍵,1               ⍝ then yield ⍵ with 1 appended to the end.
          ⋄              ⍝ ... else,
              (⊃⍋⍵)      ⍝ index of the smallest value
           1+@     ⊢⍵    ⍝ increment the value from ⍵
  • \$\begingroup\$ =/1 2 2 gives 1. \$\endgroup\$
    – Adám
    Commented Apr 19, 2021 at 7:55
  • \$\begingroup\$ ⍵+(⍳≢⍵)=⊃⍋⍵1+@(⊃⍋⍵)⊢⍵ \$\endgroup\$
    – Adám
    Commented Apr 19, 2021 at 8:25
  • \$\begingroup\$ @Adám fixed; thanks \$\endgroup\$ Commented Apr 19, 2021 at 16:31
  • \$\begingroup\$ you don't need the \$\endgroup\$
    – Razetime
    Commented Apr 19, 2021 at 16:56

MATL, 16 bytes


Try it online! Or verify all test cases

How it works

t         % Take input implicitly. Duplicate
&=        % Matrix of all pairwise equality comparisons
?         % If all comparisons were true
  1h      %   Append 1 to the original copy ofthe array
}         % Else
  t       %   Duplicate array
  2#X<    %   Push minimum and index of its first occurrence
  wQw     %   Swap, increment, swap (adds 1 to the minimum)
  (       %   Assign the incremented minimum to that position
          % End if implicitly. Display implicitly

Perl 6, 46 bytes


(modifies the input Array, and returns it)


{     # bare block lambda with implicit parameter 「$_」

  .[      # use the following as an index into the array

      [==]( $_ )    # reduce the array with 「&infix:<==>」

    ??              # if they are equal

      .elems        # the value past the end ( 「.end+1」 would also work )

    !!              # else

      .first(       # find the first value
        * == .min,  # where the element is equal to the minimum
        :k          # return the key rather than the value

  ]++;              # increment it ( auto vivifies if it doesn't exist )

  $_                # return the modified array


Mathematica, 56 bytes

±{b:a_ ..}:={b,1};±a_:=a/.{p___,b:Min@a,q___}:>{p,b+1,q}

Uses named function ±. Uses ISO8859-1 encoding

Alternative solutions (58 bytes)

±{b:a_ ..}:={b,1};±{p___,b_,q___}/;b<=p~Min~q:={p,b+1,q}
(* @GregMartin and I both independently came up with this above solution *)

±{b:a_ ..}:={b,1};±a:{p___,b_,q___}/;b==Min@a:={p,b+1,q}


±{1, 1}

{1, 1, 1}

±{3, 4, 5}

{4, 4, 5}


Haskell, 71 70 62 bytes


@Zgarb saved 8 bytes, thanks!

When I started I hoped for some elegant tying-the-knot trickery, but @Zgarb's way is just as amazing.

  • \$\begingroup\$ Some restructuring, 62 bytes: f(a:b)|(x,y:z)<-span=<<(<).minimum$a:b++[0|all(a==)b]=x++y+1:z \$\endgroup\$
    – Zgarb
    Commented Nov 29, 2016 at 8:12
  • \$\begingroup\$ @Zgarb Just wow! \$\endgroup\$ Commented Nov 29, 2016 at 10:20
  • \$\begingroup\$ Ugh, my brain fails to infer the type for the monad instance of functions \$\endgroup\$
    – Angs
    Commented Nov 29, 2016 at 18:45
  • \$\begingroup\$ @Angs The Monad is (->)r, which applied to a type is (->)r a = r->a. Then from the types return:: a->r->a and (>>=)::(r->a)->(a->r->b)->(r->b) their implementation is (dare I say it?) obvious: return=const and m>>=f = \r->f(m r)r. The latter is exactly what is needed to express something like span(predicate_depending_on l)l while mentioning l only once. Now I only need to remember it when I need it. \$\endgroup\$ Commented Nov 29, 2016 at 19:14
  • \$\begingroup\$ @Angs You can find this trick, and many more, in our Haskell golf tips collection. \$\endgroup\$
    – Zgarb
    Commented Nov 29, 2016 at 21:21

AWK, 63 bytes


Try it online!

The code scans all the numbers presented on the input line and sets variable, d, to the position of the smallest number, or to the number of fields plus one if all values are equal. Then it increments the number at that position and prints everything. As a result it either adds a new field with a value of 1 or increments the smallest number in the given set of numbers.

The first condition/test is always true, and just does some initialization.


The code block is a for loop, which applies one statement to each number from the input line.


The check to continue iterating just increments the a "current field" variable and stops when it's gets a 0 (by running off the end of the list).


The body of the loop updates b such that it's always pointing to the position of the smallest number in the input. The code also has to save the previous position of the smallest number, stored in c, to deal with cases where the minimum is the last number on the line.


The "end of loop" statement sets variable d to the current field "plus one" if the current value matches the current minimum as well as the previous minimum, or to the position of the current minimum otherwise.


One the loop completes, the code increments whichever field d points to. If all the fields are the same, it will increment an uninitialized field, which in AWK will default to 0. Otherwise it will increment the first field with the smallest value.


The second condition/test just increments the number of fields in the input line, which will always evaluate to true. If all the fields were the same numeric value, that change in NF will cause a 1 to be appended to the list. And if it changed one of the presented fields the additional field printed as a result of incrementing NF will be an empty string.


Jelly, 9 bytes


Thanks to Dennis for the -2 bytes.

Body must be at least 30 characters; you entered ... .

  • 2
    \$\begingroup\$ If you have extra characters to enter in the body, it's always worth explaining the code, which helps everyone to understand it and makes the answer more interesting :) \$\endgroup\$ Commented Nov 30, 2016 at 14:27

Mathematica, 53 bytes 57 bytes 59 bytes

  • 7
    \$\begingroup\$ That's 57 bytes. and are a 3-byte characters. Also, your code does not work because {##,1} part implies that the input is separate integers (i.e. f[1, 2, 3]) but the x=# part implies that the input is a List (i.e. f[{1, 2, 3}]). A quick fix would be to change x=# to x={#} and accept raw integers as input, making your code 59 bytes long. \$\endgroup\$ Commented Nov 29, 2016 at 0:35
  • \$\begingroup\$ Good catch! I didn't realize the distinction between bytes and character count, I just saw this suggestion and figured it was valid. It seems there are a lot of answers that give the character count but if I save them in Notepad++ I get a higher byte count (for example the Jelly answer). I see your answer specifies an encoding, is there somewhere you'd recommend for me to learn about this? \$\endgroup\$
    – user61980
    Commented Nov 29, 2016 at 20:03
  • 1
    \$\begingroup\$ I think you mean Equal@#, although #==## is shorter. \$\endgroup\$ Commented Nov 30, 2016 at 9:39
  • \$\begingroup\$ You're right. I made a change per @JHM to accept multiple arguments rather than a list but didn't propagate the change everywhere. I've gone back to accepting a list since that is more in line with the prompt. \$\endgroup\$
    – user61980
    Commented Nov 30, 2016 at 19:04

Java 8, 85 + 38 = 123 bytes

Void lambda taking a List<Integer> (output is mutated input). Byte count includes lambda and required import.

import static java.util.Collections.*;

l->{if(min(l)==max(l))l.add(0);int i=0,n;while((n=l.get(i))>min(l))i++;l.set(i,n+1);}

Try It Online

This almost looks like Python with those method imports...


R, 63 bytes


Try it online!

Had a shot at this without peeking at the previous R answer first.

Although the overall approaches are pretty similar, this pleasingly comes-out 2 bytes shorter.

Here we use a code block (enclosed in curly brackets {}) as an expression, which allows us to adjust a chosen element of the input vector v, and let the expression evaluate to the new value of v.
Shorter, but less fancy than the previous approach of abusing the indexing operator [<- as a function (which definitely deserves an upvote anyway).

  • \$\begingroup\$ I believe the sd trick will fail with length-one input since sd(1) returns NA, which R complains can't be interpreted as a logical. \$\endgroup\$
    – Giuseppe
    Commented Apr 20, 2021 at 16:21
  • \$\begingroup\$ Thanks @Giuseppe - I didn't think of that. Rolled-back. \$\endgroup\$ Commented Apr 20, 2021 at 16:24

Vyxal aW, 21 18 bytes

-3 bytes by using the register instead of variables.


Try it Online With Equal Elements!

Try it Online With Unequal Elements!


                    # Implicit input; a flag takes input as list
:                   # Duplicate input
 ≈[1J               # If all elements are equal: append 1
     |:g£           # Else: save minimum value to the register
         (          # For every element in the input:
          n         # Duplicate current element n
           n¥=[     # If current element n == register value:
               ›0£  # Increment current element and clear the register
                    # Implicit output; W flag outputs full stack
  • \$\begingroup\$ Try it Online! in 10 bytes. I came up with my answer independently, but they are very similar. For the case of unequal numbers, finds the index and increment of the min, and then sets that position of the input to that. \$\endgroup\$
    – Underslash
    Commented Jul 6, 2021 at 9:22
  • \$\begingroup\$ @Underslash You should post that as your own answer! This is a much better method than I came up with at the time. \$\endgroup\$ Commented Jul 6, 2021 at 12:51

APL (Dyalog Unicode), 20 bytes


Try it online!

First we append a zero if the input is unique, then increment the first minimum (which will be the trailing zero in the unique case, as the numbers in the input are positive)

⊢~⊃ Input without all occurences of the first element.
⍬≡ Is this the empty vector? (are values in the input the same)
0~ 0 without the result of that (a single 0 if all values are the same, empty vector otherwise)
⊢, Append this to the input

{⍵+<\⍵=⌊/⍵} Increment the first minimum.
⌊/⍵ Minimum value
⍵= Boolean vector with 1's at all minima
<\ Less-than scan; only leaves the first 1
⍵+ Add this boolean vector to the previous vector


Brachylog, 20 17 bytes


Try it online!


The first case is easy. The second is less so.

=                  Assert that all elements are equal
 ,1                Append 1
   |               If that failed, try the following instead:
    iᶠ             Get a list of [value, index] pairs for every item in the array
      o            Sort: put smallest value first, and smallest index for equal values
       {   }ʰ      Apply this predicate to the first element of the resulting list:
        +₁ʰ          Add 1 to its first element (first occurrence of min value)
             tᵒ    Sort by the second element of each sublist (index)
               hᵐ  Head of each sublist (value)

Here's a worked example of the second branch:

               Input: [2,3,1,5,1]
iᶠ             [[2,0], [3,1], [1,2], [5,3], [1,4]]
  o            [[1,2], [1,4], [2,0], [3,1], [5,3]]
   {+₁ʰ}ʰ      [[2,2], [1,4], [2,0], [3,1], [5,3]]
         tᵒ    [[2,0], [3,1], [2,2], [5,3], [1,4]]
           hᵐ  [2,3,2,5,1]

Thunno 2, 11 bytes


Attempt This Online!


ạ?1a:MçȮ⁺Ẹȧ  # Implicit input
ạ            # Is it all equal?
 ?           # If it is:
  1a         #  Append a 1
    :        # Otherwise:
     M       #  Take the minimum
      ç  Ẹ   #  Parallely apply:
       Ȯ     #   Index of the minimum
        ⁺    #   Increment the minimum
          ȧ  #  Assign the new value
             # Implicit output

R, 45 bytes


Attempt This Online!

This would be 4 bytes longer as a full program, which is a fairer comparison to earlier answers that had been posted when backslash functions were not yet a thing, and full program was a golfier approach:

R, 49 bytes


Attempt This Online!

  • \$\begingroup\$ order appears to be stable so should be equivalent to rank \$\endgroup\$
    – Giuseppe
    Commented Nov 2, 2023 at 20:35

Ruby, 46 bytes


I feel like there's a better way to check if all elements are the same than a.uniq.size<2, but I'm too lazy to find it.

  • 6
    \$\begingroup\$ a.uniq[1] will be truthy iff there are distinct values. \$\endgroup\$
    – histocrat
    Commented Nov 28, 2016 at 22:50
  • \$\begingroup\$ You can save a byte by turning a[a.index(a.min)] into a[a.index a.min] \$\endgroup\$
    – Cyoce
    Commented Nov 29, 2016 at 5:58

Octave, 69 67 64 bytes

It was actually shorter to make this a complete named function than using both input and disp.

Saved 3 bytes thanks to Luis.

function x=f(x)
[a,b]=min(x);if any(x-a),x(b)++;else x=[x,1];end

Old answer, not using a function:

[a,b]=min(x=input(''));if any(x-a),x(b)++;else x(end+1)=1;end;disp(x)

R, 97 bytes


Too bad that the synthax x=+1 doesn't exist in R !

Ungolfed :


TI-Basic, 53 bytes

If min(not(ΔList(Ans
cumSum(1 or Ans

Matlab, 83, 77, 71 Bytes

function a=x(a)

I'm relatively new to code golf so please be kind! I tried to use anonymous functions but googling says you can't use if/else statements and matlab doesn't have ternary operators, so this is the best i felt I could do.

Edit: Corrected and shortened (twice!) thanks to stewie-griffin.

  • \$\begingroup\$ Welcome to PPCG! There are some flaws in this code. sum(a)/length(a)==a(1) doesn't guarantee that all elements are equal, it only shows that the average is equal to a(1). A simpler way to do this would be mean(a)==a(1). numel is one byte shorter than length, but since you know all values are positive, you can use nnz which is even shorter (it would still not give the correct result in this challenge, but it's shorter at least :P ). If you take the min(a) call in front of the loop, you may use both outputs from it and check is all elements of a are equal to min(a). \$\endgroup\$ Commented Nov 29, 2016 at 15:51
  • \$\begingroup\$ You are right! it fails when the mean is equal the number in the first element. I think my new one is correct though and also shorter. The logic is that if the remaining elements don't equal the first element, a(a~=a(1)) returns the remaining elements which by definition is greater than 0 in a non-same array. Then counting and not should give the correct logic I think. If it's still wrong please let me know, I've only been coding for a few years and I still have a long ways left. \$\endgroup\$ Commented Nov 29, 2016 at 18:05
  • \$\begingroup\$ ~nnz(a(a~=a(1))) is simply ~nnz(a-a(1)). Also, you don't need the parentheses. if ~nnz(a-a(1));a=[a,1];else[~,I]=min(a);a(I)=a(I)+1;end. This should be 5 bytes shorter (note: I haven't tested it). \$\endgroup\$ Commented Dec 6, 2016 at 15:55
  • \$\begingroup\$ You can save 3 bytes by using range(a) instead of nnz(a-a(1)) \$\endgroup\$
    – hwm
    Commented Dec 9, 2016 at 20:21
  • \$\begingroup\$ @boboquack, that code checks if the number of elements in a is equal to the lowest value in that vector. A vector a = [3 4 6] will result in true, and a vector a = [4 4 6] will result in false. I don't think that will be useful here...? \$\endgroup\$ Commented Dec 12, 2016 at 0:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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