Lesson 6 of 8 · 12 min

Challenge: Climb the word ladder

Kuda's teacher puts a puzzle on the board every Friday: turn cold into warm, changing one letter at a time, and every step must be a real word.

cold
cord    (l became r)
card    (o became a)
ward    (c became w)
warm    (d became m)

The class hands in their answers on paper and the teacher has 40 to mark. Let's help with the checking part.

Your task

Write two functions:

  1. oneLetterApart(a, b) returns true if the two words have the same length and differ in exactly one position, otherwise false.
  2. isLadder(words) returns true if every word in the list is one letter apart from the word before it.
oneLetterApart("cold", "cord")   // true
oneLetterApart("cold", "warm")   // false  (4 letters differ)
oneLetterApart("cat", "cat")     // false  (nothing changed)
oneLetterApart("cat", "cart")    // false  (different lengths)

isLadder(["cold", "cord", "card", "ward", "warm"])   // true
isLadder(["cold", "cord", "warm"])                   // false
isLadder(["kombi"])                                  // true
isLadder([])                                         // false

Rules

  • Words are in lowercase.
  • Swapping letters around does not count: dog and god differ in two places.
  • You do not need to check that the words are real words, only the steps.
  • A single word is a ladder (there is nothing to break). An empty list is not.

Tips

  • In oneLetterApart, count the differences in a loop: if (a[i] !== b[i]) count++.
  • Write oneLetterApart first, then use it inside isLadder. Small functions that each do one job are easier to get right.
  • In isLadder, start the loop at i = 1 so that words[i - 1] is always the word before.
  • You can return false from inside a loop as soon as you find a bad step.
main.js
function oneLetterApart(a, b) {
  // TODO: same length, and exactly one position different
  return false;
}

function isLadder(words) {
  // TODO: check every step with oneLetterApart
  return false;
}

console.log(isLadder(["cold", "cord", "card", "ward", "warm"]));  // should print true

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…