Bitpath

Boss lesson · Unit 03

Palindromes and anagrams

Two ends moving inward, and counting letters

12 exercisesabout 3 min

What you practise

  • Two ends moving inward
  • Anagram by sorting O(n log n) vs counting O(n)

Try a question from this lesson

Pick one

A palindrome reads the same in both directions, like "level". How many letter comparisons are enough to check a 1,000-letter word?

The idea

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Anagrams: same letters, new order

"listen" and "silent" are anagrams: every letter appears the same number of times in both.

Two ways to check. Sort both words and compare, which costs O(n log n). Or count the letters of both and compare the counts: O(n).

def is_anagram(a, b):
    return sorted(a) == sorted(b)
const key = (s) => [...s].sort().join("");

function isAnagram(a, b) {
  return key(a) === key(b);
}
const key = (s: string) =>
  [...s].sort().join("");

function isAnagram(a: string, b: string) {
  return key(a) === key(b);
}

Python notesorted(a) returns a list of the characters, and Python compares two lists item by item.

JavaScript noteTwo arrays are never === unless they are the same array, which is why the sorted letters are joined back into a string.

TypeScript note[...s] spreads a string into a string[] of its characters, which is what .sort() needs.

10 more exercises in the app

  • 1× order the lines
  • 1× type the answer
  • 1× fill the blanks
  • 5× multiple choice
  • 1× true or false
  • 1× match the pairs

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy