Skip to content
Algorithms for Beginners

Problems / Hashing and counting

Letter twins

easy

New here? How this page works
  1. Read the Problem tab. Read it twice. Look at the examples: what goes in, what should come out.
  2. Open Break it down. Answer the questions in your own words. This is your plan.
  3. Write code on the right. Start small. Stuck on a blank page? Press “Write my plan as comments”.
  4. Press Run examples. See which examples pass. Red ones show what your code gave and what was expected.
  5. Stuck? Use Hints, one at a time. Still stuck after all of them? Read the Walkthrough. That's learning, not cheating.
  6. Press Submit. It runs hidden tests too. Pass them all, and it's solved.

Two words are letter twins if you can make one by rearranging all the letters of the other, using every letter exactly once. For example, listen and silent are letter twins.

Given two words, first and second, return true if they are letter twins, and false if they are not.

Examples

  1. Example 1

    Input
    first = "listen", second = "silent"
    Output
    true

    Both have one each of e, i, l, n, s and t.

  2. Example 2

    Input
    first = "apple", second = "paple"
    Output
    true

    Both have two p's and one each of a, l and e.

  3. Example 3

    Input
    first = "aab", second = "abb"
    Output
    false

    Same letters, but different amounts of each: two a's against one.

Rules

  • Both words use only lowercase letters a to z.
  • Each word has between 0 and 50,000 letters.
  • A word counts as a letter twin of itself.
Words on this page, in plain English (1)Open if any word is new to you
Boolean (true or false)
A value that can only be true or false. Like a light switch: on or off.

Every word, explained simply

Your solution

JavaScript · Press Esc then Tab to leave the editor

function areLetterTwins(first, second) {
  // Return true or false.
}

Blank page fear? (uses your answers from Break it down; comments don’t run).

Results

Run the examples to check your code, then Submit to run every test.

Next steps in hashing and counting

  • Learn the hashing and counting pattern

    Remember what you have seen in a Map, so you never search for it twice.

  • First lonely letter

    Easy. Find the position of the first letter that appears only once in a piece of text.

  • Group the twins

    Medium. Sort a list of words into groups, where every word in a group uses exactly the same letters.

  • Longest run

    Medium. Find the length of the longest run of consecutive numbers hidden in an unsorted list.

  • Pair to target

    Easy. Find the two items whose prices add up to exactly the value of a gift card.

  • Spot a repeat

    Easy. Check whether any raffle ticket number was printed more than once.