Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.


Given two strings, work out if they both have exactly the same characters in them.



word, wrdo

This returns true because they are the same but just scrambled.


word, wwro

This returns false.


boat, toba

This returns true


Here are the rules!

  • Assume input will be at least 1 char long, and no longer than 8 chars.
  • No special characters, only az
  • All inputs can be assumed to be lowercase

Test Cases

boat, boat = true
toab, boat = true
oabt, toab = true
a, aa = false
zzz, zzzzzzzz = false
zyyyzzzz, yyzzzzzy = true
sleepy, pyels = false
p,p = true
share|improve this question
9 answers in 13 views... wow! –  Tom Gullen Mar 8 '11 at 16:44
@Tom, because everyone wanted to prove that your comment about using a 64-bit integer was pointing in the wrong direction :P –  Peter Taylor Mar 8 '11 at 18:15
ARGH! Why is this question marked community wiki? –  Tom Gullen Mar 9 '11 at 10:39
@Martin, part of the fun of this site for me is the competition in collecting rep! –  Tom Gullen Mar 9 '11 at 11:27
@TomGullen As to “why”, you can see it in the post's history: “more than 60 answers”. Perhaps you should propose on Meta that that automatic rule should be removed for this site. –  Kevin Reid Jun 2 '12 at 14:43

93 Answers 93

Python - 32 chars

f=lambda a,b,S=sorted:S(a)==S(b)
share|improve this answer
@Debanjan, This is just the same as def f(a,b):return sorted(a)==sorted(b) The trade off is that you get to replace def+return with lambda in exchange for not using any statements –  gnibbler Mar 8 '11 at 22:23
@Debanjan, I think it only saves you one character. I have used a variation here, but it works out the same length as yours because I swap a newline for a comma –  gnibbler Mar 9 '11 at 0:09
I have one question,this approach does require calling of input and print and other stripping functions right? –  VelvetThunder Mar 9 '11 at 0:09
@Tomas, nonsense. The question doesn't specify complete program, so either a function or a complete program are acceptable. –  gnibbler Feb 2 '14 at 23:47
@Tomas, The majority of answers here fail to pass your criteria. Why not give an upvote to all those that do? –  gnibbler Feb 2 '14 at 23:56

Golfscript, 3 chars?










share|improve this answer
This is an interesting interpretation of how to supply the input :) –  gnibbler Mar 9 '11 at 0:10
Explanation please :( –  st0le Mar 9 '11 at 5:41
@st0le, seriously? I don't know golfscript, but it's obviously $ (sort), $ (sort), = (compare) –  Peter Taylor Mar 9 '11 at 8:10
Isn't this cheating a little? I mean, it isn't variable input. It has to be hard-coded. In any case, I would add 4 to the character count for the quote (') characters. –  Thomas Eding Jul 30 '11 at 0:18
to correctly handle the input use something like ", "/~$/$= –  user1502040 Apr 4 '14 at 1:52

J, 8


Literaly, match (-:) on (&) sort up (/:~)

Sample use:

   'boat' -:&(/:~) 'boat'
   'toab' -:&(/:~) 'boat'
   'oabt' -:&(/:~) 'toab'
   'a' -:&(/:~) 'aa'
   'zzz' -:&(/:~) 'zzzzzzzz'
   'zyyyzzzz' -:&(/:~) 'yyzzzzzy'
   'sleepy' -:&(/:~) 'pyels'
   'p' -:&(/:~) 'p'

Where do the 64-bit integers come into play?

share|improve this answer
Is it not possible to write functions/subroutines in J? –  user475 Mar 8 '11 at 15:57
@Tim Nordenfur: they're called "verbs", and take either one argument on their right as in v arg (monads) or two on both sides as in arg1 v arg2 (dyads). The one I submitted is obviously a dyad. I didn't bother to name it, since it wasn't requested and is shorter this way. Should you really want to give it a name, you'd do that like this: is_anagram_of =: -:&(/:~) and then use as 'a' is_anagram_of 'aa'. –  J B Mar 8 '11 at 16:21
It felt a bit cheap to substitute the arguments into the code, but I see now that it's essentially a dyad. Never mind. –  user475 Mar 8 '11 at 16:26
J always looks like the remains of an emoticon factory explosion. –  st0le Mar 9 '11 at 6:58

Javascript - 192 157 152 147 125

Ok some of these languages are a lot more flexibile than I thought! Anyway this is the longer way I guess, but a different technique at least.


Thanks to Peter and David for squeezing more chars out!

for(a=[j=p=2];j<123;)a[j]?p%a[++j]<1&&p++&&(j=0):(a[j]=p,j=0);function b(c,i){return c[i=i||0]?a[c.charCodeAt(i)]*b(c,++i):1}

Then do:


Expanded Code

The compressed has had lots of changes, but this is the basic theory:

// Define dictionary of primes
a = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101];

// Returns the unique ID of the word (order irrelevant)
function b(c) {
    r = 1;
    for (i = 0; i < c.length; i++)
        r *= a[c[i].charCodeAt(0) - 97];
    return r

alert(b("hello") == b("hlleo"));
share|improve this answer
Great idea using primes. –  user475 Mar 8 '11 at 16:06
@Tim thanks! Got it down to 157 now. –  Tom Gullen Mar 8 '11 at 16:12
You can shave a couple of characters off the dictionary initialisation using the sieve. a=[2];for(p=3,j=0;j<26;)if(a[j]){if(p%a[j++]==0){p++;j=0}}else{a[j]=p;j=0} –  Peter Taylor Mar 8 '11 at 17:06
@Tom, depends on how well optimised the sorting routines are, given that you've limited inputs to 8 characters :P –  Peter Taylor Mar 9 '11 at 11:13
125 characters. Recursion and ternaries FTW: for(a=[j=p=2];j<123;)a[j]?p%a[++j]<1&&p++&&(j=0):(a[j]=p,j=0);function b(c,i){return c[i=i||0]?a[c.charCodeAt(i)]*b(c,++i):1} –  David Murdoch Mar 9 '11 at 14:03

Golfscript - 8 chars

This defines a function called A


Test cases

'boat' 'boat' A
'toab' 'boat' A
'oabt' 'toab' A
'a' 'aa' A
'zzz' 'zzzzzzzz' A
'zyyyzzzz' 'yyzzzzzy' A
'sleepy' 'pyels' A
'p' 'p' A
share|improve this answer

Haskell function - 31

import List

Haskell program - 81 58 55

import List


$ runghc anagram.hs
$ runghc anagram.hs
$ runghc anagram.hs

Kudos to lambdabot and its pointfree refactoring.

share|improve this answer
Can Haskell code that only does what's wanted under runghc, but not when compiled, still be called "program"? –  J B Mar 8 '11 at 21:29
@J B: Can Perl code that only does what's wanted under perl still be called a "program"? :-) –  Joey Adams Mar 8 '11 at 23:06
J B: Todays functional languages skew the meaning of a program making it a higher order abstraction. Rather than just a list of instruction to be executed, as haskell program can just be seen as a collection of functions, even if they are not called. –  Callum Rogers Mar 9 '11 at 17:45
@Callum Rogers: my point is: his code behaves differently whether run under runghc or compiled, in a problem-sensitive area. The "function" is fine. The "program" does not solve the problem under anything else than runghc, and runghc is not the only legitimate way to run Haskell programs. In that context, that makes the snippet a "runghc script", not a "Haskell program". --not that I'd consider the issue important, as I said, the function is fine anyway and it's shorter. –  J B Mar 9 '11 at 21:09
x#y=sort x==sort y is 1 character shorter –  Rotsor Aug 6 '11 at 10:58

Ruby 34

Using the IO scheme of Peter Taylors Perl solution:

p gets.chars.sort==gets.chars.sort
share|improve this answer
Throws an error: -e:1:in '<main>': undefined method 'chars' for nil:NilClass (NoMethodError) –  Tomas Feb 2 '14 at 22:53

C# (129 chars)

namespace System.Linq{class X{static void Main(string[]a){Console.Write(a[0].OrderBy(_=>_).SequenceEqual(a[1].OrderBy(_=>_)));}}}


namespace System.Linq
    class X
        static void Main(string[] a)
            Console.Write(a[0].OrderBy(_ => _)
                  .SequenceEqual(a[1].OrderBy(_ => _)));
share|improve this answer

C program - 118 necessary characters

share|improve this answer
Ever considered applying for IOCCC? –  Mateen Ulhaq Mar 9 '11 at 3:54
@muntoo: have you seen anything in the IOCCC? This is way too readable for that. –  R. Martinho Fernandes Mar 9 '11 at 5:39
@Martinho Yes, the IOCCC source codes are so beautiful. Symphonies. But he should at least try composing a small piece. :) –  Mateen Ulhaq Mar 9 '11 at 6:59
@muntoo: I didn't even know they were still active. –  Joey Adams Mar 9 '11 at 7:21
Just saw this one... Very nice. But can be shorter: t[256],i;main(c){for(;c+3;)(i=getchar())>10?t[i]+=c:(c-=2);for(i=257;--i&&!t[i-‌​1];);puts(i?"false":"true");} - that's 108 characters. Very importantly, your c initialization trick is still employed. –  ugoren Feb 29 '12 at 16:18

Perl (58)

(complete program, unlike the other Perl answer which is only a function)

($c,$d)=map{[sort split//]}<>;print"@$c"eq"@$d"?true:false

49 as a function

sub f{($c,$d)=map{[sort split//]}<>;"@$c"eq"@$d"}
share|improve this answer
of course you can save 4 chars in the program by removing the " around true and false, since without using strict/warnings a bareword is a string. –  Joel Berger Sep 17 '11 at 17:30
Thanks! –  Timwi Sep 17 '11 at 20:21
I prefer this as ($c,$d)=map{[sort split//]}@ARGV;exit("@$c"ne"@$d") (51 chars) so it can take command line arguments and use the command line exit codes. It'd be 48 chars retaining <> with a multi-line input. –  Adam Katz Aug 15 at 11:41

C++ (104 non-ws chars)

Based on counting sort. Note: Assumes strings of the same length, which seems to be implied (though not stated) by the question.

int u[123], i;

int a(char **c) {
    for(; c[0][i]; ) {

    while(i && !u[--i]);
    return !i;
share|improve this answer
In C, if you declare a variable in the global scope, it is initialized to zero. I guess this is also true for C++. –  Joey Adams Mar 8 '11 at 17:24
Local variables, on the other hand, are not initialized to zero automatically. –  Joey Adams Mar 8 '11 at 17:35
OK, I removed my caveat since I found ways to do without it. –  Matthew Read Mar 8 '11 at 18:09
Bzzzt. You pass the test cases, but "helle" and "hollo" are apparently the same. Easy fix: change one of the ++ to a --. Then just if (u[i++]) return 0; –  Dave Gamble Mar 9 '11 at 6:30
I haven't tested this, but the last three lines can be written as i=123;while(i&&u[--i]);return!i; –  st0le Dec 7 '11 at 4:38


Based on @zzzzBov's solution.

Comparison, 65 chars (40 without function)

function f(a,b){return a.split('').sort()==b.split('').sort()+""}

Comparator, 43 chars

function f(a){return a.split('').sort()+""}
share|improve this answer
Clever using the +"" to coerce to string. –  Casey Chu Jun 16 '11 at 6:01

Perl (62)

This function takes the strings as arguments and returns true or false.

sub f{my@a;for$.(1,-1){$a[ord]+=$.for split//,pop}!grep{$_}@a}

Stores the ASCII values in an array and checks if it evens out. Increments for the first word and decrements for the second word.

share|improve this answer

Perl - 77 75 chars

The I/O of the problem aren't well specified; this reads two lines from stdin and outputs true or false to stdout.

sub p{join'',sort split'',$a}$a=<>;$x=p;$a=<>;print$x eq p()?"true":"false"

(Thanks to Tim for 77 -> 75)

share|improve this answer
Something is wrong. $a=;? Also, you can skip the parens of sort and the space after print. –  user475 Mar 8 '11 at 16:00
@Tim, the genius who developed this platform for sharing code over the net decided that in code blocks people should have to escape less-than characters. But hey, no big deal: it's not as though anyone uses them in code, right? Keeps catching me out. –  Peter Taylor Mar 8 '11 at 16:32
Ok, I removed the downvote. You might want to use the code formatting in the future, i.e. indent code with four spaces. –  user475 Mar 8 '11 at 16:46
Ok, so there are three ways of formatting code (one inline and two block), and both the block ones are inconvenient in different ways. Sigh. –  Peter Taylor Mar 8 '11 at 18:13

PHP (command line, 87 characters)

function d($s){
    return array_count_values(str_split($s));

echo d($argv[1]) == d($argv[2]);
share|improve this answer

Clojure - 23 chars

As an anonymous function:

#(apply = (map sort %))

Test case example:

(#(apply = (map sort %)) ["boat" "boat"])
=> true
share|improve this answer
Cool, I like it. –  Chiron Dec 5 '11 at 23:48


88 characters

diff <(grep -o .<<<$1|sort) <(grep -o .<<<$2|sort)>/dev/null && echo true || echo false
share|improve this answer

Clojure REPL 41 chars

(= (sort (read-line)) (sort (read-line)))
share|improve this answer
Welcome to the Stack Exchange network. Formatting help here. –  dmckee Mar 10 '11 at 4:17

Python 3 (107)(97)(76)(64)

s=sorted;a,b=input().split(', ')

Obviously this can be shortened if we don't take the OP's wording literally and lowercase "true" and "false"...

share|improve this answer
You can shave off a few characters if you append ;s=sorted to the first line and then replace the two instances of sorted with s in the second line. Should save... 3 characters? –  Alex Van Liew Aug 6 at 17:58
Indeed. Python 3 also saves a bit of space, and is probably reasonable to use now, 5 years after this answer was posted. Also, the .strip() was redundant, given the specified inputs. –  Wooble Aug 10 at 12:55
Yeah, sorry. I didn't notice how old this question was when I commented, only that it was on the frontpage. ^^; –  Alex Van Liew Aug 10 at 22:39


Comparison function (78):

function a(b,c){return String(b.split('').sort())==String(c.split('').sort())}
alert(a('abc','bca')); //true

Comparator function (48):

function a(b){return String(b.split('').sort())}
alert(a('abc')==a('bca')); //true

Assumes String has split and Array has sort.

share|improve this answer

Python (32 bytes)

f=lambda a,b:p(a)==p(b)
share|improve this answer
Does nothing in python. Are you sure it is a complete program that takes the input and produces the output as requested? –  Tomas Feb 2 '14 at 23:48


A (very) slightly shorter version of @zzzzBov's solution, that uses .join() instead of String boxing:

function a(b,c){return b.split('').sort().join()==c.split('').sort().join()}
alert(a('abc','bca')); //true


function a(b){return b.split('').sort().join()}
alert(a('abc')==a('bca')); //true
share|improve this answer

Scala in REPL (32)


Scala function (43)

def f(a:String,b:String)=a.sorted==b.sorted

Scala program (61)

object A extends App{println(args(0).sorted==args(1).sorted)}

These leverage a neat feature of Scala whereby a String can also be treated as a sequence of characters (Seq), with all the operations on Seq being available.

share|improve this answer

Python (151 89)

Handles arbitrarily many inputs from stdin. Comma separated, one pair per line.

import sys
for l in sys.stdin:a,b=l.split(',');print f(a.strip())==f(b.strip())
share|improve this answer
Mwahaha, first time I see a Python solution longer than C# :) –  Timwi Mar 8 '11 at 16:05
Won't this return True for aab, bba? –  gnibbler Mar 8 '11 at 20:28
@gnibbler; Yes, it will, I wasn't thinking this morning. Fixed –  Hoa Long Tam Mar 9 '11 at 1:52

JavaScript (67)

function(a,b){return ""+a.split("").sort()==""+b.split("").sort()}
share|improve this answer
Wanted to post the same solution before I even saw yours –  dwana Jan 30 at 7:38


172 characters

wscript.echo "boat, boat         = " & s("boat, boat")
wscript.echo "toab, boat         = " & s("toab, boat")
wscript.echo "oabt, toab         = " & s("oabt, toab")
wscript.echo "a, aa              = " & s("a, aa")
wscript.echo "zzz, zzzzzzzz      = " & s("zzz, zzzzzzzz")
wscript.echo "zyyyzzzz, yyzzzzzy = " & s("zyyyzzzz, yyzzzzzy")
wscript.echo "sleepy, pyels      = " & s("sleepy, pyels")
wscript.echo "p,p                = " & s("p,p")

function s(a):b=split(replace(a," ",""),","):c=0:for x=1 to len(b(0)):if instr(b(1),mid(b(0),x,1)) then c=c+1 
next:if len(b(1))-c=0 then s=true else s=false
end function

I was kinda suprised I could get it under 200.

share|improve this answer
131 characters if I pass the values seperatly. function s(a,b):c=0:for x=1 to len(a):if instr(b,mid(a,x,1)) then c=c+1 next:if len(b)-c=0 then s=true else s=false end function –  user775 Mar 9 '11 at 14:40

Ruby (40)

share|improve this answer
I've formatted your code for you. The tool bar above the edit box has the most commonly used functions, and the sidebar has a link to more detailed info. –  dmckee Mar 9 '11 at 6:47

Another Ruby (46)

share|improve this answer

C function (147 chars), using brute-force

int c(char*x,char*y){int i=0,l=0;for(;y[l]&&x[l];l++);if(y[l]||x[l])return 0;
share|improve this answer


(everyone's favorite language apparently!)

173 chars:

import java.util.*;class g{public static void main(String[]p){String[]a=p[0].split(""),b=p[1].split("");Arrays.sort(a);Arrays.sort(b);System.out.print(Arrays.equals(a,b));}}

(Doesn't print newline char to save 2 chars from println)

Compile and run:

javac g.java
java -cp . g abcdef fedcba

Love to see a shorter one...

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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