# Determine whether strings are anagrams

## Challenge

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

## Example

Input

word, wrdo

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

Input

word, wwro

This returns false.

Input

boat, toba

This returns true

## Rules

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

• 9 answers in 13 views... wow! Commented Mar 8, 2011 at 16:44
• Title request: Cod Elf, Go!
– user54200
Commented Jul 9, 2016 at 12:48
• "Falcon Rage, go mad!" Commented Oct 6, 2016 at 17:25
• My name suggestion: "are they anagrams" → "manage the arrays" Commented Oct 31, 2017 at 4:32
• Suggested test case: aaab, bbba = false Commented Aug 3, 2022 at 23:56

# Perl 5, 27 + 3 (-lF) = 30 bytes

@{$.}=sort@F}{say"@1"eq"@2"  Try it online! • The -l option is not needed. It would still count as +3 though since you must count the space too (since you cannot bundle the -F with -E. You can however do the final match using @1~~@2 saving 4 bytes (or 3 if you add an extra X option letter to supress the warning). Very neat solution by the way. Have a +1 Commented Feb 4, 2018 at 11:43 # Pyth, 4 bytes _ISM  Try it Online ### Explanation _ISM SMQ Sort both (implicit) inputs. _I Check if the result is invariant under reversing.  # Lua, 140 chars t={io.read():match"(%w+), (%w+)"}T=table for k=1,2 do w={t[k]:byte(1,-1)}T.sort(w)t[k]=T.concat{string.char(unpack(w))}end print(t[1]==t[2])  ... like driving a screw with a light weight hammer, at least for code-golfing # Python 2, 79 bytes I thought I would add a different Python approach: import sys for l in sys.stdin: not reduce(cmp,map(sorted,l.strip().split(',')))  Or as a function: def f(*v): return not reduce(cmp,map(sorted,v))  ## Scala, 84 characters object A{def main(a: Array[String]){println(a(0).sortWith(_<_)==a(1).sortWith(_<_))}}  This one's slightly longer, but doesn't use sorting (92 characters): object A{def main(a:Array[String]){print((a(0)diff a(1)).isEmpty&&(a(1)diff a(0)).isEmpty)}}  • You can use sorted instead of sortWith. I posted another reply with sorted as well as REPL and function versions. Commented Mar 9, 2011 at 6:15 • @ebruchez Thanks, I'm just learning Scala at the moment and these make good exercises. :-) Commented Mar 9, 2011 at 10:19 • Still learning myself ;) Commented Mar 9, 2011 at 16:17 # Common Lisp, 50 bytes (lambda(a b)(string=(sort a'char<)(sort b'char<)))  Try it online! # Japt, 1095 4 bytes á øV  Try it á øV :Implicit input of strings U & V á :Permutations of U øV :Contains V?  # SmileBASIC, 49 bytes INPUT A$,B$WHILE""<A$B$[INSTR(B$,POP(A$))]=" WEND  Throws an error when the strings aren't anagrams. # Symja, 26 bytes f(x_,y_):=Sort(x)==Sort(y)  Try It Online! Try With Changeable Tests Assumes strings are given as a list of characters. # Java 16, 85 bytes a->b->a.chars().sorted().boxed().toList().equals(b.chars().sorted().boxed().toList())  Java 16 added the Stream#toList method. # Java 8, 88 bytes a->b->java.util.Arrays.equals(a.chars().sorted().toArray(),b.chars().sorted().toArray())  Try it online! ## PHP7.4 (45 chars) The function$f will return the answer using count_chars :

$f=fn($a,$b)=>($x='count_chars')($a)==$x($b);  Try it Online - in PHP4 the XOR cipher passes all tests using 48 chars : function f($a,$b){return$a==chop($a.$b^$b^$b);};


## C gcc (69 chars)

The function f compute the product of both string and implicitly return the comparison :

i;j;f(char*a,char*b){i=j=1;for(;*a;i*=*a++);for(;*b;j*=*b++);a=i==j;}


Try it Online

C version isn't shaved up to 65 chars by XOR cipher due to some ae == bf misses :

i;f(char*a,char*b){i=1;for(;*a;i^=*a++);for(;*b;i^=*b++);a=i==1;}

• You can put the \$f= into the header, as as long as the function does not reference itself, you can drop the function name from the char count. like this Commented Apr 7, 2022 at 23:18
• also you can remove the quotes around count_chars. it will spout all sorts of stuff to stderr, but who cares Commented Apr 7, 2022 at 23:20
• 68 bytes Commented Apr 10, 2022 at 18:36

# Julia, 26 bytes

!a=sort([a...])
a\b=!a==!b


Try it online!

# C - 115 Bytes

a[127],b[127],i,o=1;f(char*s,char*z){for(;*s;a[*s++]++);for(;*z;b[*z++]++);for(;i++<128&&o;o=a[i]==b[i]);return o;}


Ungolfed

a[127], b[127], i, o = 1;

f(char* s, char* z)
{
for(; *s; a[*s++]++);
for(; *z; b[*z++]++);
for(; i++ < 128 && o; o = a[i] == b[i]);

return o;
}


Alternative way (By @ceilingcat)

*a,*b,i,o;f(char*s,char*z){for(a=calloc(i=128,8);*s;a[*s++]++);for(b=a+i;*z;b[*z++]++);for(;i--&&(o=a[i]==b[i]););return o;}


Explanation

A function that receives two ASCII character strings with arbitrary length and checks if one is an anagram of the other.

To accomplish this, both entire strings are iterated over and the number of matches for each character is stored in a list for each string; later it is checked if both lists have the same number of matches, if so, then the strings are anagrams and true (1) is returned, otherwise false (0) is returned.

• Fixed some bugs 124 bytes Commented Apr 11, 2022 at 7:59
– user111743
Commented Apr 11, 2022 at 13:09

# TI-Basic, 83 bytes

Prompt Str1,Str2
"seq(inString(Str1+Str2,sub(Ans,I,1)),I,1,length(Ans→u
Str1
u→A
SortA(ʟA
Str2
u→B
SortA(ʟB
0
If dim(ʟA)=dim(ʟB
min(ʟA=ʟB
Ans


Output is stored in Ans and displayed. Outputs 1 if the inputs are anagrams, otherwise 0.

# Alice, 11 bytes

/@Mn/
\MOX\


Try it online!

Prints Jabberwocky if the two words are anagrams

## Flattened

MM       Reads the two arguments
X      Compute their symmetric difference
n     Empty string becomes Jabberwocky, anything else becomes empty string
O    Print it out
@   Bye


# R, 47 bytes

\(x,y)all(table(strsplit(paste0(x,y),""))%%2==0)

• Fails for aab + bcc: try it. Commented Nov 18, 2022 at 23:20

# BQN, 3 bytes

≡○∧


Anonymous tacit function that takes two strings; returns 1 if they are anagrams, 0 otherwise. Try it at BQN online!

### Explanation

≡    Are the strings identical
○   when both of them
∧  are sorted?


# J-uby, 17 bytes

:*&(A|:sort)|+:==


Attempt This Online!

## Explanation

:* & (A | :sort) | +:==

:* & (         )         # Map with...
A | :sort          #   convert to character array, then sort
| +:==  # then compare


# Nekomata + -e, 2 bytes

↕=


Attempt This Online!

↕       Check if any permutation of the first string
=      is equal to the second string


# Labyrinth, 23 bytes

1
,:#
* 0
1;/----+}=-!@


Try it online!

Takes two words separated by a newline. For each word, computes the product of c * 10 + 1 for each char c, and compares the two values. Prints 0 for true and a nonzero integer for false.

Such product is unique for lowercase words up to permutation, since the counts of 25 out of 26 letters can be recovered from the exponents of 25 unique prime factors:

971 is prime
981 = 109 * 3 * 3
991 is prime
1001 = 7 * 11 * 13 (no unique prime factor)
1011 = 337 * 3
1021 is prime
1031 is prime
1041 = 347 * 3
1051 is prime
1061 is prime
1071 = 17 * 7 * 3 * 3
1081 = 47 * 23
1091 is prime
1101 = 367 * 3
1111 = 101 * 11
1121 = 59 * 19
1131 = 29 * 13 * 3
1141 = 163 * 7
1151 is prime
1161 = 43 * 3 * 3 * 3
1171 is prime
1181 is prime
1191 = 397 * 3
1201 is prime
1211 = 173 * 7
1221 = 37 * 11 * 3


Therefore this approach works for arbitrary length inputs.

Since a lowercase letter has value of 97 or higher, the newline has value 10, and -1 is pushed on EOF, a three-way branch is possible via dividing the input value by any number between 11 and 97 inclusive.

By a little bit of planetary alignment, letting the IP reflect on newline (instead of creating a 4-way junction) magically sets up the stack for the second word. This part works because the words are guaranteed to be nonempty.

1    push 1 on empty stack

,:#  loop: compute the value of word1 until newline
* 0    ,:   getchar, dup  [word1 c c]
1;/    #0/  divide by 30  [word1 c c/30]
if positive:
;1*  drop, multiply 10c+1  [word1']
if zero: reflect

1    [word1 10 0]
,:#  0#:  push some garbage [word1 10 0 3 3]
0  ,    getchar (1st char of word2)
1    times 10 plus 1
[word1 10 0 3 3 word2]
enter the loop again to compute the value of word2
same flow as first loop, except that # gives 8 and
IP turns left on EOF
[word1 10 0 3 3 word2 -1 -1]
----+}=-!@  clean up the stack and compare word1 and word2
----+ [word1 10 word2]
}=    [word1 word2 | 10]
-!@   print the difference and halt


# C# 118 chars

using System.Linq;namespace A{class P{static void Main(string[] a){System.Console.Write(!a[0].Except(a[1]).Any());}}}


using System.Linq;

namespace A
{
class P
{
static void Main(string[] a)
{
System.Console.Write(!a[0].Except(a[1]).Any());
}
}
}

• You can remove an extra character: string[]a You also don't need a namespace.
– ICR
Commented Dec 7, 2011 at 13:54

# C#

bool IsJumbledPair(string a, string b) {
if(a.Length!=b.Length) return false;
foreach(char c in a.ToCharArray()) {
int i = b.IndexOf(c);
if(i<0) return false;
b = b.Remove(i,1)
}
return (b.Length==0);
}


Readable, and does not require sorting.

Another method:

bool IsJumbledPair(string a, string b) {
string c;
while {
if(a.Length!=b.Length) return false;
if(a.Length==0) return true;
c = a.Chars(0).ToString();
b = b.Replace(c, "");
a = a.Replace(c, "");
}
}


The above version works better when the strings contain a number of duplicated characters, as each distinct character is only compared once using the relatively fast Replace() method.

# VB.NET

Same as the first C# example, slightly simpler using Replace() method, but doesn't short-cut like the C# version:

Function IsJumbledPair(a As String, b As String) As Boolean
If a.Length <> b.Length Then Return false
For Each(c As Char In a.ToCharArray())
b = Replace(b, c.ToString(), "", 1, 1)
Next
Return (b.Length=0)
}

• It is likely that the downvotes are because you have made no effort to golf (see the tag?) your solutions, or because you have mixed several distinct solutions in one answer. Commented Mar 9, 2011 at 22:50
• Meh. If I play real golf, it's for socializing or beer, not score-keeping. Guess I should have actually been playing to win... :) Commented Mar 11, 2011 at 6:17
• People generally respond well to solutions in wordy languages (I play in Fortran 77 from time to time), as long as you make an effort to write aggressively compacted <wordy language>, and especially if your languages supports a interesting trick (i.e. fortran has computed branches). Commented Mar 11, 2011 at 16:10

F# (59 chars)

let f a b=(Seq.sort>>Seq.toArray)a=(Seq.sort>>Seq.toArray)b


Very annyoying that sequences can' be directly compared.

## Ada 2005 - 314 218

type V is array(Character)of Natural;function A(L,R:String)return Boolean is
C,D:V:=(others=>0);begin
for I in L'Range loop
C(L(I)):=C(L(I))+1;end loop;for I in R'Range loop
D(R(I)):=D(R(I))+1;end loop;return C=D;end;


# C - 79 90 chars (using strchr & strlen)

r(char*s,char*t){int i=0;for(;*s&&strchr(t,*s++);i++);return i==strlen(t)?1:0;}


Ungolfed...

r( char *s, char *t )
{
int i=0;
for (; *s && strchr(t, *s++); i++)
;
return i == strlen(t) ? 1 : 0;
}


# C - 115 110 chars (brute with histogram)

int k,u[256];ρ(char*s,char*t){char*v=s;for(;*s;)u[*s++]++;for(;*t;)u[*t++]--;while(*v&&!(k=u[*v++]));return k?0:1;}


Ungolfed...

int k, u[256];
r(char *s, char*t)
{
char *v = s;

for (;*s;)
u[*s++]++;
for (;*t;)
u[*t++]--;

while(*v && !(k=u[*v++]) )
;
return k ? 0 : 1;
}


EDIT: fixed bug in brute version.

EDIT: added brute version (no library functions).

• You use the table 256 char; if you call that function more that one time it is necessary make that 256 table 0.
– user58988
Commented Oct 7, 2016 at 10:48

# Coffee Script (52)

a=(b,c)->b.split('').sort()==c.split('').sort()+''


# usage

console.log a 'god', 'dog'


# Python 121 Characters

It's not a winner wrt length, but I didn't use sorted!

from sys import argv as s
for i in s[1]+s[2]:
if not s[1].count(i)==s[2].count(i):
print 'False'
break
else:
print 'True'

• You can save 2 characters by changing the import to from sys import* (newline) s=argv. Commented Sep 13, 2011 at 14:45
• Algorithm fails with s[1]='the',s[2]='them'. Commented Sep 13, 2011 at 14:54
• You could avoid the need to dereference s by from sys import* (newline) _,a,b=argv. Commented Sep 13, 2011 at 17:19

# Groovy, 46

b={args[it].toList().sort()}
print b(0)==b(1)


## Groovy, 54

print args[0].toList().sort()==args[1].toList().sort()

• I've fixed up the formatting for you. Stack Exchange site use MarkDown (though they do accept a subset of html). THe sidebar on the edit page has some hints, the edit toolbar has common operations, and there is a detailed help page. Commented Mar 9, 2011 at 22:46

## Java, 173 chars

import java.util.*;class C{public static void main(String[]a){byte[]d,f;Arrays.sort(d=a[0].getBytes());Arrays.sort(f=a[1].getBytes());System.out.print(Arrays.equals(f,d));}}


It's the same that Guus one but changing a couple of methods.

• So it's no shorter but it is buggier? Commented Dec 7, 2011 at 14:04
• Hmmm... Why buggier? Commented Dec 7, 2011 at 14:34
• Maybe this? "The behavior of this method when this string cannot be encoded in the default charset is unspecified." :P Commented Dec 7, 2011 at 14:36
• My bad, forgot to check the spec. I was thinking about characters in the range \u0080 to the end of the BMP, which become more than one byte, and which would allow collisions. Commented Dec 7, 2011 at 15:08