It's become somewhat of a tradition in PPCG that some users temporarily change their names by an anagram (a new name formed by reordering the letters of the old).

Sometimes it gets difficult to find out who is who. I could use a program or function to tell if two phrases are anagrams of each other.

The challenge

The program or function should take two strings and produce a truthy result if they are anagrams of each other, and falsy otherwise.


  • Input will only contain letters (ASCII 65 to 90 and 97 to 122), digits (ASCII 48 to 57) or space (ASCII 32).
  • The anagram relation is independendent of case. So "Arm" and "RAM" are anagrams.
  • Spaces don't count either. So "keyboard" and "Barked Yo" are anagrams
  • All builtins allowed
  • Input format is flexible (two strings, an array of two strings, a string containing both phrases with a suitable separator ...)

Code golf. Fewest bytes wins.

Test cases


Lynn, Nyl N
Digital Trauma, Tau Digital Arm
Sp3000, P S 3000
Manage Trash So, Those anagrams


Calvins Hobbies, Helka Homba
Android, rains odd
In between days, bayed entwine
Code golf, cod elf got
  • 8
    \$\begingroup\$ Related but different (only letters, no case, no spaces) \$\endgroup\$
    – Luis Mendo
    Commented Feb 25, 2016 at 16:09
  • 5
    \$\begingroup\$ This question's title is very perplexing to someone who's not had enough coffee. +1 :D \$\endgroup\$
    – cat
    Commented Feb 25, 2016 at 17:36
  • 1
    \$\begingroup\$ @DonMuesli I would argue that this is still a dupe. The slight changes are very trivial. \$\endgroup\$
    – user45941
    Commented Feb 25, 2016 at 17:59
  • 16
    \$\begingroup\$ Manage Trash So, Those anagrams. Nice. \$\endgroup\$
    – mbomb007
    Commented Feb 25, 2016 at 20:13
  • 3
    \$\begingroup\$ So, the anagrams... \$\endgroup\$
    – Leaky Nun
    Commented May 21, 2016 at 17:23

36 Answers 36


Retina, 25


Try it Online! Additionally, you can run a modified multi-line version.

Delete letters from before the comma along with their matches after the comma. If we have no letters left then it was an anagram.

  • \$\begingroup\$ For Retina, if a positive number could be considered a failure, and zero be considered success, this could be three bytes shorter by using \w as the last stage. \$\endgroup\$ Commented Feb 25, 2016 at 20:20
  • \$\begingroup\$ \W will not work for the case of: Calvins Hobbies, Calvin's Hobbies \$\endgroup\$ Commented Feb 26, 2016 at 0:34
  • \$\begingroup\$ @dev-null "Input will only contain letters (ASCII 65 to 90 and 97 to 122), digits (ASCII 48 to 57) or space (ASCII 32)" \$\endgroup\$ Commented Feb 26, 2016 at 2:36

05AB1E, 9 8 bytes




l         # Lowercase the strings
 vy   }   # Map over the list, for each...
   ð-     #   remove spaces
     {    #   and sort
       Q  # Check equality

Try it online!

  • \$\begingroup\$ ... but 2 bytes less! Well done! \$\endgroup\$
    – Luis Mendo
    Commented Feb 25, 2016 at 16:28
  • \$\begingroup\$ It's lvyðK{}Q now. \$\endgroup\$ Commented Jun 23, 2017 at 16:38
  • \$\begingroup\$ -2 bytes lεá{}Ë. 5+ years later.. ;) \$\endgroup\$ Commented Nov 18, 2022 at 13:02

Pyth, 11 10 bytes

Thanks to @FryAmTheEggman for teaching me the power of ;!


Try it here!

Takes a list of two strings as input.


qFmSr-d;0Q    # Q = input

  m      Q    # map Q with d as lambda variable
     -d;      # filter spaces out of the string
    r   0     # convert to lowercase
   S          # sort all characters in string
qF            # Unfold resulting list and check for equality

Python 2, 63 61 bytes

lambda*l:len({`sorted(s.lower())`[2::5].strip()for s in l})<2

An anonymous function that, in fact, takes n arguments and determines if all n of them are mutual palindromes! f("Lynn", "Nyl N") returns True.

This set comprehension trick is by xnor. It saved two bytes, but the old approach looked very neat:

exec"a=`sorted(input().lower())`[2::5].strip();a"*2;print a==aa
  • \$\begingroup\$ `sorted(input().lower())`.strip(" [',") is the same length :/ \$\endgroup\$
    – Sp3000
    Commented Feb 25, 2016 at 16:43
  • \$\begingroup\$ The exec thing is clever but seems too complex. You can do better with lambda*l:len({`sorted(s.lower())`[2::5].strip()for s in l})<2. \$\endgroup\$
    – xnor
    Commented Feb 25, 2016 at 16:45
  • 2
    \$\begingroup\$ Thanks! I'm a bit disappointed – it looked very cool. Keeping it in the post anyway. \$\endgroup\$
    – lynn
    Commented Feb 25, 2016 at 16:50

Jelly, 12 bytes


Try it online!

How it works

ḟ€⁶O&95Ṣ€QLḂ  Main link. Input: A (list of strings)

  ⁶           Yield ' '.
ḟ€            Filter it from each string.
   O          Apply ordinal to all characters.
    &95       Take bitwise AND with 95 to make the ordinals case-insensitive.
       Ṣ€     Sort each list of ordinals.
         Q    Deduplicate the list.
          L   Get the length.
           Ḃ  Compute the length's parity (1 -> 1, 2 -> 0).

Alternate version (9 bytes)

Jelly's uppercase atom had a bug, and Jelly still had no built-in to test lists for equality...


Try it online!

How it works

ḟ⁶ŒuṢµ€⁼/     Main link. Input: A (list of strings)

     µ€       Map the chain to the left over A.
 ⁶            Yield ' '.
ḟ             Filter it from the string.
  Œu          Cast to uppercase.
    Ṣ         Sort.
       ⁼/     Reduce by equality.

CJam, 11 12 14 bytes

3 2 bytes removed thanks to @FryAmTheEggman


Try it online!

{      }2*       e# do this twice
 l               e# read line as a string
  el             e# make lowercase
    S-           e# remove spaces from string
      $          e# sort
          =      e# compare strings
  • \$\begingroup\$ @FryAmTheEggman Thank you! \$\endgroup\$
    – Luis Mendo
    Commented Feb 25, 2016 at 16:56
  • \$\begingroup\$ @FryAmTheEggman Thanks again! I still have much to learn about CJam :-) \$\endgroup\$
    – Luis Mendo
    Commented Feb 25, 2016 at 16:59
  • 3
    \$\begingroup\$ Your code is secretly laughing. lel. \$\endgroup\$
    – Cyoce
    Commented Feb 27, 2016 at 21:12
  • \$\begingroup\$ Or is it a one? lel ==> 1e1 No one knows. It is a mystery. \$\endgroup\$
    – user48538
    Commented Mar 2, 2016 at 12:23

Javascript, 69 61 60 59 bytes

1 byte off thanks @ӍѲꝆΛҐӍΛПҒЦꝆ. 1 byte off with currying (pointed out by @apsillers)

n=>m=>(G=s=>[]+s.toLowerCase().split(/ */).sort())(n)==G(m)

        .split(/ */)

F=(n,m)=>document.body.innerHTML+=`<pre>f('${n}')('${m}') -> ${f(n)(m)}</pre>`

F('Luis Mendo','Don Muesli')
F('Calvins Hobbies','Helka Homba')
F('Android','rains odd')
F('In between days','bayed entwine')
F('Code golf','cod elf got')
F('Lynn','Nyl N')
F('Digital Trauma','Tau Digital Arm')
F('Sp3000','P S 3000')
F('Manage Trash So','Those anagrams')

  • 2
    \$\begingroup\$ Very nice, filtering out spaces and converting to an array at the same time! \$\endgroup\$
    – Neil
    Commented Feb 25, 2016 at 17:06
  • 2
    \$\begingroup\$ Very nice. You can save one byte using currying, which the community has decided is an acceptable form of arguments: n=>m=>... \$\endgroup\$
    – apsillers
    Commented Feb 25, 2016 at 17:23
  • \$\begingroup\$ Try n=>m=>(G=s=>[]+s.toLowerCase().split(/\S/).sort())(n)==G(m). Using split instead of match should save you a byte. \$\endgroup\$ Commented Feb 26, 2016 at 3:42
  • \$\begingroup\$ @ӍѲꝆΛҐӍΛПҒЦꝆ. No, because suppose s='db cz'... Now s.match(/\S/g).sort() results in ['b','c','d','z']... and s.split(/\s/).sort() results in ['cz','db'] \$\endgroup\$
    – removed
    Commented Feb 26, 2016 at 12:59
  • \$\begingroup\$ @ӍѲꝆΛҐӍΛПҒЦꝆ. But... looking into your idea, I changed it a bit and saved one byte... thanks! \$\endgroup\$
    – removed
    Commented Feb 26, 2016 at 13:05

MATL, 11 bytes


EDIT (May 20, 2016) The code in the link uses Xz instead of Xv, owing to recent changes in the language.

Try it online!

2:"     ]       % do this twice
   j            % read input line as a string
    k           % convert to lowercase
     Xv         % remove spaces
       S        % sort
         X=     % are they equal?
  • 3
    \$\begingroup\$ Did you just change your name for that challenge? \$\endgroup\$
    – Denker
    Commented Feb 25, 2016 at 16:34
  • 3
    \$\begingroup\$ @DenkerAffe I had been thinking about it for some time. I just made it coincide with the challenge :-) \$\endgroup\$
    – Luis Mendo
    Commented Feb 25, 2016 at 16:36
  • 1
    \$\begingroup\$ Don Muesli lol. So you are the Lord of Muesli Luis!? Is this how you keep your healthy complexion? \$\endgroup\$
    – rayryeng
    Commented Feb 25, 2016 at 21:00
  • \$\begingroup\$ @rayryeng Heyyy! Good to see you here, Ray! Get back to golfing! \$\endgroup\$
    – Luis Mendo
    Commented Feb 25, 2016 at 21:22
  • \$\begingroup\$ I promise I will :) once this course ends... I see you are learning CJam now too. Very nice! \$\endgroup\$
    – rayryeng
    Commented Feb 25, 2016 at 21:32

Seriously, 11 9 bytes


Try It Online!

Everyone seems to be using the same algorithm. Here it is yet again.

2`    `n          Do it twice
  ,               Read a string
   ù              Make it lowercase
    S             Sort
     ô            Strip spaces.
        =         Check equality.

Edit: realized sorting does work correctly on strings, and sorts spaces to the front so strip() will work.


C, 165 bytes

#define d(x) int x(char*a,char*b){
#define n(x) for(qsort(x,strlen(x),1,(__compar_fn_t)q);*x<33;x++);
d(s)n(a)n(b)return strcasecmp(a,b);}

Readable and in working context,

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

// start of comparison
int q(char *a, char *b){
     return ((*a)&0xdf)-((*b)&0xdf); // case-insensitive
int s(char *a, char *b){
    for(qsort(a,strlen(a),1,(__compar_fn_t)q); *a<33; a++) /**/;
    for(qsort(b,strlen(b),1,(__compar_fn_t)q); *b<33; b++) /**/;
    return strcasecmp(a,b);
// end of comparison

int main(int i, char **v){
    printf("'%s' '%s'", v[1], v[2]);
    printf("=> %d\n", s(v[1], v[2])); // 0 if equalish
    return 0;

zsh, 85 bytes

[ $(for x in $@;{tr -d \ <<<$x|tr A-Z a-z|fold -1|sort|paste -sd x}|uniq|wc -l) = 1 ]

Input as command line arguments, output as return code.

The for syntax makes this Bash-incompatible.

[               # test...
$(for x in $@;  # map over arguments
{tr -d \ <<<$x  # remove spaces
|tr A-Z a-z     # lowercase
|fold -1        # put each character on its own line
|sort           # sort lines
|paste -sd x    # remove all newlines except last
}|uniq          # take only unique lines
|wc -l          # how many lines remain?
) = 1 ]         # if only 1 line left, it must have been an anagram

Japt, 12 bytes

N®v ¬n ¬xÃä¥

Test it online!

How it works

        // Implicit: N = array of input strings
N®    Ã // Take N, and map each item Z to:
v ¬n    //  Take Z.toLowerCase(), split into chars, and sort.
¬x      //  Join and trim off whitespace.
ä¥      // Reduce each pair of items (that's exactly one pair) X and Y to X == Y.

Bash + GNU utilities, 51

f()(fold -1<<<${@^^}|sort)
f $1|diff -qBw - <(f $2)
  • Define a function f() which:
    • ${@^^} converts all parameters to upper case
    • fold -1 splits chars - one per line
    • sorts lines
  • call diff with -q to suppress full diff output and -Bw to ignore whitespace changes

GNU Sed, 33

Score includes +2 for -rn options to sed.

This is almost a direct port of @FryAmTheEggman's Retina answer:




Perl, 34 33 + 1 = 34 bytes


Requires the -n flag and the free -M5.010|-E:

$ perl -M5.010 -ne's/(.)(.*,.*)\1/$2/i?redo:say!/\w/' <<< 'hello, lloeh'

How it works:

                                   # '-n' make a implicit while loop around the code
 s/(.)(.*,.*)\1/$2/i               # Remove a letter that occurs on both sides of the comma.
                     redo:         # Redo is a glorified goto statement that goes to the top of the while loop
                          say!/\w/ # Check to see if any letter is left

Thanks to msh210 for suggesting using ternary operators to save one byte


Zsh, 51 bytes

Try it Online!

g()<<<${(j::)${(os::)1:l}// }
<<<${$(g $1)/$(g $2)}

Similar to my other anagram solution, again using Zsh's gnarly parameter expansion. Added a few bits to lowercase everything and parse out spaces.


Arturo, 33 bytes

$=>[=do map&=>[tally--lower&` `]]

Try it!

Takes input as a list of two strings.

$=>[               ; a function where input is assigned to &
    map&=>[        ; map over input, assign current elt to &
        lower&     ; lowercase current elt
        -- _ ` `   ; remove spaces
        tally      ; create dictionary of occurrences
    ]              ; end map
    do             ; put the pair on the stack
    =              ; are they equal?
]                  ; end function

Cyborg Hal, 9 8 bytes


Try it online!

Truthy/falsy output is achieved through predicate success/failure, this being Brachylog.

Previously saved a byte using cṇ₁cḷḍ instead of {ṇ₁cḷ}ᵐ under the assumption that the two input strings would be the same length minus whitespace, but I realized that it would succeed where it should fail on Ah Hass, haha.

{     }ᵛ    For both strings in the input,
 ṇ₁         split on spaces,
   c        concatenate,
    ḷ       lowercase,
     o      and sort.
       ᵛ    Are the results the same?

PHP, 109 94 bytes

function f($x){return str_split((trim($x));}function g($x,$y){return array_diff(f($x),f($y));}

Blech, the two function/returns are killing me here.

Returns the difference between two string inputs as an array of characters. PHP considers [] falsy, satisfying the return requirements.

  • 3
    \$\begingroup\$ function($x,$y){$S=str_split;return array_diff($S(trim($x)),$S(trim($y)));} --> 75 bytes. Creates an anonymous function that returns the result. I've removed that long function and replaced the calls to str_split with an assignmed variable, to shorten it up. \$\endgroup\$ Commented Feb 25, 2016 at 16:52
  • \$\begingroup\$ Nice. I was tweaking it to reduce it to the one function, this is two steps ahead of that, well done. \$\endgroup\$
    – ricdesi
    Commented Feb 25, 2016 at 16:56

Pyke (commit 30, noncompetitive), 9 bytes



F      )  -  for _ in eval_or_not(input())
 l1       -     ^.lower()
   dk:    -    ^.replace(" ", "")
      S   -   sorted(^)
        q - ^==^

Mathematica, 77 76 bytes

StringMatchQ[##,IgnoreCase->1>0]&@@(""<>Sort[Characters@#/." "->""]&/@{##})&

The first part is actually one of my answers to another question!


Pike, 54 112 109 109 96 bytes

#define a(x) sort((array)replace(lower_case(x)," ",""))
int s(mixed i){return a(i[0])==a(i[1]);}

mixed happens to be shorter than array(string).

s returns 1 if its arguments are anagrams.


APL, 31 chars

{≡/{x[⍋x←('.'⎕R'\u0')⍵~' ']}¨⍵}

To be used so:

    {≡/{x[⍋x←('.'⎕R'\u0')⍵~' ']}¨⍵}'Sp3000' 'P S 3000' 

In English:

  • { ... }¨⍵: for each of the two elements of the argument
  • x←('.'⎕R'\u0')⍵~' ': transform to uppercase (using a regex...) the string without the spaces and assign the temporary result to x
  • x[⍋x]: sort x
  • ≡/: compare the two results of the sorting: if they match, return 1.
  • \$\begingroup\$ Is it possible to try it online? I tried with this but I don't really know how to use it \$\endgroup\$
    – Luis Mendo
    Commented Jun 28, 2016 at 11:49
  • \$\begingroup\$ Sure. Here: definition after which you can just type f 'first avatar' 'second avatar' \$\endgroup\$
    – lstefano
    Commented Jun 28, 2016 at 12:56
  • \$\begingroup\$ Thanks! Maybe add that to the answer? So that people can try \$\endgroup\$
    – Luis Mendo
    Commented Jun 28, 2016 at 13:28
  • \$\begingroup\$ –9: ≡/{x[⍋x←0~⍨32|⎕UCS⍵]}¨ \$\endgroup\$
    – Adám
    Commented Jun 28, 2016 at 15:27
  • \$\begingroup\$ @Adám: that won't work because ≡/{x[⍋x←0~⍨32|⎕UCS⍵]}¨'pp' '00' gives 1. \$\endgroup\$
    – lstefano
    Commented Jun 29, 2016 at 8:52

Java, 218 Bytes

First time I've ever written Java...


import java.util.Arrays;boolean M(String a,String b){char[]A=a.toUpperCase().replace(" ","").toCharArray();char[]B=b.toUpperCase().replace(" ","").toCharArray();Arrays.sort(A);Arrays.sort(B);return Arrays.equals(A,B);}


import java.util.Arrays;
public class ManageTrashSo {
    public boolean M(String a, String b) {
    char[] A = a.toUpperCase().replace(" ", "").toCharArray();
    char[] B = b.toUpperCase().replace(" ", "").toCharArray();
    return Arrays.equals(A, B);


    ManageTrashSo manageTrashSo = new ManageTrashSo();

    System.out.println(manageTrashSo.M("Lynn", "Nyl N"));
    System.out.println(manageTrashSo.M("Digital Trauma", "Tau Digital Arm"));
    System.out.println(manageTrashSo.M("Android", "rains odd"));
    System.out.println(manageTrashSo.M("In between days", "bayed entwine"));
  • \$\begingroup\$ I know it's been almost a year, but you can golf it by 32 bytes like this: boolean f(String...a){java.util.Arrays x=null;String[]A=g(a[0]),B=g(a[1]);x.sort(A);x.sort(B);return x.equals(A,B);}String[]g(String a){return a.replace(" ","").toUpperCase().split("");} (186 bytes) Or if you convert it to a Java 8 lambda, it can be: a->b->{java.util.Arrays x=null;String[]A=g(a),B=g(b);x.sort(A);x.sort(B);return x.equals(A,B);};String[]g(String a){return a.replace(" ","").toUpperCase().split("");} (167 bytes). Here is a TIO with test code. \$\endgroup\$ Commented Sep 27, 2017 at 11:48

Japt, 10 bytes

v á øVrS v

Try it


lyxaV, 5 bytes


Try it Online!

Or try a testsuite to verify the test cases.

Takes inputs as a list of strings.


ɽ     # Convert each string to lowercase
 ȧ    # Remove whitespace from each string
  vs  # Sort each string
    ≈ # Are they equal?

Thunno 2, 5 bytes


Try it online!

Input as a list of both strings.


Rw€Ṡạ  # Implicit input
R      # Uppercase the input
 w     # Remove all whitespace
  €Ṡ   # Sort each string
    ạ  # All equal?
       # Implicit output

Ruby, 50 bytes

def f;gets.upcase.chars.sort.join.strip;end
p f==f

Writing f=->{...} and f[]==f[] is just as long. :(


PowerShell, 81 bytes

param([char[]]$a,[char[]]$b)-join($a-replace' '|sort)-eq-join($b-replace' '|sort)

A slight rewrite of my answer on the linked Anagram challenge.

Takes input as char-arrays, performs a -replace operation to remove spaces, sorts them (which sorts alphabetically, not by ASCII value), then -joins them back into a string. The -eq in PowerShell is by default case-insensitive, but here it must be performed on strings, as [char]'a' is not equal to [char]'A', hence the reason for -join.


Perl, 35 bytes

Include +1 for -p

Somewhat abusive since it depends on the program being given on the commandline.

perl -pe'<>=~s%\S%*_=s/$&//i?_:0%reg;$_=!//'

Then give the strings as 2 consecutive lines on STDIN

A very abusive solution is 30 bytes:

perl -ne'<>=~s%\w%1/!s/$&//i%reg;1/!//'

This crashes if the strings are not anagrams and therefore gives a false exit code from the point of view of the shell. It also gives garbage on STDERR for that case. If the strings are anagrams the program is silent and gives a "true" exit code


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.