Deleted questions on Stack Overflow sometimes make for great golf material.

Write a function that takes a nonnegative integer as input, and returns true if all the digits in the base 10 representation of that number are unique. Example:

48778584 -> false
17308459 -> true

Character count includes only the function.

If you choose to answer in C or C++: no macros, no undefined behaviour; implementation-defined behaviour and compiler warnings are fine.

  • \$\begingroup\$ I'd still be interested in other C or C++ solutions as per the question that inspired this one. \$\endgroup\$
    – Thomas
    Commented May 21, 2014 at 19:59
  • 11
    \$\begingroup\$ Why no C or C++ macros or undefined behavior? That's oddly limiting to just two languages. \$\endgroup\$
    – dfeuer
    Commented Apr 14, 2019 at 2:05

92 Answers 92


Zsh, 28 24 bytes

If output is 0, the digits are unique. Otherwise, there are dupes


Try it Online! 28 bytes


Haskell, 32 bytes


Try it online!

Repeats each character once per each character that equals it, and checks that this gives the original digits string.


C 151

Bytes = 181 or 151 without newline chars. Program keeps a tally of digits and exits if greater than 1.

#include <stdio.h>
int i,j[10],r;
int main()
if(j[r]>1){printf("false");return 0;}
return 0;

C# 72 characters

var a=i.ToString().ToCharArray();
return a.Distinct().Count()==a.Count();
  • \$\begingroup\$ ".ToCharArray()" is unnecessary since there's String.Distinct. \$\endgroup\$
    – Helix Quar
    Commented May 22, 2014 at 1:37
  • \$\begingroup\$ I think that not including the required using System.Linq; in your character count is cheating a bit. @helix That's Enumerable.Distinct, not String.Distinct. MSDN is a bit confusing by showing extension methods too. But indeed, ToCharArray() is not necessary. \$\endgroup\$
    – hvd
    Commented May 22, 2014 at 7:13
  • \$\begingroup\$ you could also do i+"" instead of i.ToString(). But this question is asking for a function, you just gave 2 lines of code \$\endgroup\$
    – mnsr
    Commented May 26, 2014 at 0:25

Julia, 44

  • \$\begingroup\$ This doesn't work - it only returns true if n is one digit long, as length(Set(d))=1 for any integer. For the same approach idea, perhaps use unique(d)==d? \$\endgroup\$
    – Glen O
    Commented May 22, 2014 at 16:11
  • \$\begingroup\$ julia> f(123456) true julia> f(1234566) false It seems to work. julia> length(Set(1,2)) 2 Perhaps the definition of length(x::Set) changed recently? I'm running 0.3 prerelease. \$\endgroup\$
    – gggg
    Commented May 22, 2014 at 16:27
  • \$\begingroup\$ That might make a difference - I'm running 0.2.1. I get length(Set(1,2))=2, but length(Set([1,2]))=1. \$\endgroup\$
    – Glen O
    Commented May 22, 2014 at 16:36

Cobra - 109

def f(n) as bool
    for i in m,for j in m,if i==j,l+=1
    return if(l>m.length,false,true)

Makes me wish that LINQ would work properly in Cobra.


C# 72 69 67 characters (no libraries needed)

for(;d>0;d/=10)for(int f=d/10;f>0;f/=10)if(d%10==f%10) return true;


for (; d > 0; d /= 10)
    for (int f = d / 10; f > 0; f /= 10) 
        if (d % 10 == f % 10) 
            return true;

I'm just using simple maths here.(i.e. number 1231):

  • Take the last digit (1)
  • Iterate through the quotient (123)
  • If the number is equal to our digit (1), then return true
  • 3 == 1, 2 == 1, 1 == 1 - found it!

Ruby(47 characters)


Example usage

=> true

C# (44 - 64)


As a lambda (44):


alt lambda (also 44):


As a Func (63):

Func<int, bool> f=y=>(y+"").GroupBy(x=>x).All(x=>x.Count()==1);

As a method (64):

bool f(int y){return (y+"").GroupBy(x=>x).All(x=>x.Count()==1);}

Extended BrainFuck: 100

not included the unnecessary linefeed.



%> beef ebf.bf < unqiue.ebf > unqiue.bf
%> echo 48778584 | beef unique.bf 
-> false
%> echo 17308459 | beef unique.bf 
-> true

VBA (145)

Function jkl(f As String) As Boolean
For i = 1 To Len(f)
jkl = InStr(1, f, Left(Mid(f, i), 1)) <> i
If jkl = True Then Exit Function
End Function

Calling the function and output with opposite of the result:

Sub jj()
Dim f As String
f = "1234256789"
MsgBox Not (jkl(f))
End Sub

PHP 74 Chars

<?php $a=str_split($argv[1]);var_dump(count($a)==count(array_unique($a)));

VB.NET - 189 184

Function U(I As Integer) As Boolean
    U = True
    Dim D(9)
    Dim S = I.ToString
    For Each E As Char In S
        If IsNumeric(E) Then If D(Val(E)) + 1 > 1 Then U = False Else D(Val(E)) += 1
End Function

First code-golf attempt. I'm aware it's an unsuitable language and poor result, but I wanted to try.

  • \$\begingroup\$ I counted 189 characters even without necessary whitespace. Please be aware that, unless explicitly stated in the question, we usually count necessary whitespaces in answers. However, you can reduce your source size by removing unnecessary whitespaces (spaces around assignment operators, indentations etc) and using one-character identifier names, e.g. U instead of Unique, i instead of IA etc. Also, I cannot test it now but I think you can skip the type definitions of your variables/function (i.e. using only Dim D(9),i()=I.ToString.ToCharArray) \$\endgroup\$
    – user12205
    Commented May 24, 2014 at 15:17
  • \$\begingroup\$ So your first line may become something like Function U(I). Your function can then return integers 0 and 1 instead of false/true. Then your second line can be changed to U=1 and your Return False can be changed to U=0. Finally, I'm not sure whether it works but perhaps making IA a string instead of a char array can save you a lot of bytes. \$\endgroup\$
    – user12205
    Commented May 24, 2014 at 15:22
  • \$\begingroup\$ I used an online tool out of laziness, I may have to write a character-counting function instead. Do you count line returns and tabs as characters? \$\endgroup\$
    – Lou
    Commented May 24, 2014 at 15:23
  • \$\begingroup\$ Visual Studio 2012 religiously enforces spacing and indentation, even correcting it before beginning a debug - I don't see a way I can cut them out. \$\endgroup\$
    – Lou
    Commented May 24, 2014 at 15:24
  • \$\begingroup\$ Also, how do I count bytes in code? Sorry, I looked in Meta and the Help Centre but I couldn't find an answer. \$\endgroup\$
    – Lou
    Commented May 24, 2014 at 15:27

Clojure - (42 - 52)

As a named function (52):

(defn f[i](let[s(str i)](=(count s)(count(set s)))))

As an anonymous function (42):

#(let[s(str %)](=(count s)(count(set s))))


Cheating with library functions (29/12 characters):

def t(i:String)=i==i.distinct

Scala version of the GolfScript version (36/19 characters):

def t(i:String)=i.intersect(i).size>0

Doing the counting work manually (91/74 characters):

def t(i:String)=(Map.empty[Char,Int]/:i)((m,c)=>m+(c->(m.getOrElse(c,0)+1))).forall(_._2<2)

PHP - 44 33


Or Proper function 42 Characters

function(){return max(count_chars($n))<2;}

UPDATE : Thanks for @scrblnrd3 pointed out for shorter solution.

  • \$\begingroup\$ You could cut out a few chars by doing <2 instead of the ternary operator \$\endgroup\$
    – scrblnrd3
    Commented May 23, 2014 at 19:49
  • \$\begingroup\$ <2 in PHP, DO you have some reference page, how it used in php as I never seen this. \$\endgroup\$ Commented May 26, 2014 at 5:20
  • 1
    \$\begingroup\$ I mean you could use var_dump(max(count_chars($n))<2); instead \$\endgroup\$
    – scrblnrd3
    Commented May 26, 2014 at 13:19
  • 1
    \$\begingroup\$ <?=max(count_chars($argn))<2); 30+1 bytes: run as pipe with -F, prints 1 for true, nothing for false \$\endgroup\$
    – Titus
    Commented Nov 2, 2017 at 20:58

Haskell (41)

import Data.List
f x=show x==nub(show x)

About 23 characters shorter than the other Haskell answer and a fair bit more intuitive I think. Basically the same process but using Haskell's built-in list functions is much easier and shorter.

  • \$\begingroup\$ I don't think you're required to count the last newline. \$\endgroup\$
    – seequ
    Commented Jun 3, 2014 at 17:42

C - 62

int m[10];f(int a){while(m[a%10]++?0:a/=10);return m[a%10]<2;}

I've included the count of the globally declared array (which ensures initialisation to 0).

As a bonus, here is a much shorter technically correct answer:

f(int a){return 1}

The question does not state that non-unique digits should return false. Therefore I claim the current lead for C code with 18 characters, although I expect to be beaten by a scripting language with an answer like:

  • 1
    \$\begingroup\$ Welcome to Programming Puzzles and Code Golf. I think the OP states quite clearly that a number with duplicate digits should return false. Perhaps you could explain why you think differently? And explain how an undefined function performs the requested task, and how a singly character can do so in any scripting language. \$\endgroup\$ Commented May 23, 2014 at 17:24
  • 1
    \$\begingroup\$ @David Wilkins One of the examples returns false; the actual OP just states that unique digits should return true, which the C program I added in jest certainly does. \$\endgroup\$
    – Alchymist
    Commented May 27, 2014 at 7:40
  • \$\begingroup\$ Also, if I knew golfscript, for example, I would have written a function returning true in that rather than describing an unspecified "scripting language" \$\endgroup\$
    – Alchymist
    Commented May 27, 2014 at 7:59

Julia - 29 28


Old version:


F# - 82

let f i =
    let s = i.ToString() 
    s |> Set.ofSeq|> Seq.length = s.Length;;

COBOL 66 with Object Cobol extensions

Microfocus Cobol (721 659 592)

       method-id u.
       local-storage section.
       77  i pic s9(9) comp.
       77  c pic 9 occurs 10 value 0.
       77  g pic 9.
       01  s pic 9(9).
       01  t redefines s pic 9 occurs 9.
       linkage section.
       77  n pic s9(9) comp.
       77  d pic x.
       88  f value is 'y'.
       procedure division using by value n returning d.
           move n to s. move 'n' to d. perform p varying i from 1 by 1 until i greater than 9 or f. goback.
       p.  move t (i) to g. if c (g) is not zero then move 'y' to d. add 1 to c (g).
       end method.

Hmmm, I think I should go back to pitch & putt :(



C++ 82

this code is at least legitimate

int a(uint32_t i,uint32_t r=0,uint32_t h=0)
{return i?r&h?0:a(i/10,r|h,1<<i%10):1;}        // thanks to DreamWarrior

C 47

this works if you compile it in debug mode or provide two more arguments set to 0

a(i,r,h){return i?r&h?0:a(i/10,r|h,1<<i%10):1;}

Regular Expression 17 bytes


Original expression taken from https://stackoverflow.com/a/12870549.


Clojure, 23

#(=(distinct x)(seq x))

Usage: (#(=(distinct x)(seq x)) "23563462464543")


Candy, 13 bytes

This is a late post, but...


Invokation with -I , which is actually for string parameters.

The long form:

while    # while we are still consuming characters from the stack
  setSP  # pop the next stack-id from the stack.  It's the ord of the digit
  stackSz  # test for empty stack
    digit1 setSP  # goto stack #1, and push the true indicator on
    retSub        # and halt
    digit0    # mark the stack as having been visited
digit0    # push the false indicator if we got this far

Prolog, 49 bytes




p(N):-number_codes(N,L), % Convert int to list (of charcodes)
      sort(L,S),         % Sort list and remove duplicates
      msort(L,T),        % Sort list and keep duplicates
      S=T.               % Check if lists are equal




05AB1E, 2 bytes


Try it online!

-1 thanks to Kaldo

{   # Sort.
 ¥  # Consecutive differences.
  P # Product.

Works on negatives, though OP never specified...

  • \$\begingroup\$ ÙQ for 2 bytes. \$\endgroup\$ Commented Apr 5, 2018 at 15:25

rSNBATWPL, 45 bytes


A (probably golfable) approach, which looks for duplicate characters. Instead of a costly cast.string, I use norm, which applies Unicode normalization, which is a no-op here. I use rdc as an expensive hack to iterate over pairs. The most important part of the solution is d=d*a!b (I use d=d*... rather than d*=... since *= requires whitespace to prevent ambiguity), which multiplies d (initially 1) by a!b, which after being cast to an int will be 1 only if a and b aren't equal.


Thunno 2, 2 bytes


Attempt This Online!


U=  # Implicit input
U   # Uniquify the input
 =  # Does it equal the input?
    # Implicit output

Pascal, 142 bytes

This function requires a processor compliant with Extended Pascal, ISO standard 10206. In particular the card function must be available.

function f(x:integer):Boolean;var d:set of 0..9;w:integer;begin d:=[];w:=0;repeat d:=d+[x mod 10];x:=x div 10;w:=w+1 until x=0;f:=w=card(d)end


        { This will permit a proper `function` domain restriction. }
        integerNonNegative = 0..maxInt;
    { Returns `true` if `x` as decimal number contains no duplicate digits. }
    function hasUniqueDecimalDigits(x: integerNonNegative): Boolean;
            { The decimal digits that appear in `x`. }
            digits: set of 0‥9 value [];
            { The total width of a decimal representation of `x`. }
            width:  integer    value 0;
            { If there are as many distinct decimal `digits` as
              the total `width` of the decimal number,
              we can tell that no digit appears twice. }
                digits ≔ digits + [x mod 10];
                x      ≔ x div 10;
                width  ≔ width + 1;
            until x = 0;
            { `card` returns the cardinalty of a set,
              that is the number of members in a set. }
            hasUniqueDecimalDigits ≔ card(digits) = width;

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.