Skip to the content

Spelling with elements

Problem

For the science fair, Ms. Nkechi Obi came up with a game: her students have cards with chemical element symbols, and they spell words by placing them side by side. Each card can be used as many times as needed. What she wants to know is how many different ways each word can be spelled.

Write a function that takes word, a lowercase string with no spaces and at least one letter, and symbols, a list of lowercase strings, each one letter or longer and with no repeats (it may be empty). Return a whole number: how many ways the whole word, from start to end, can be split into consecutive pieces that are all symbols from the list; the same symbol can be used more than once. Two ways are different if they cut the word in different places.

With "bones" and ["b", "o", "n", "es", "ne", "s"] there are 2 ways: b o n es and b o ne s. With "lux" and ["lu", "u", "l"] there are none, because no symbol has the x: return 0.

Examples

  • The example

    "bones", ["b", "o", "n", "es", "ne", "s"] → 2

  • It can't be spelled

    "lux", ["lu", "u", "l"] → 0

  • Three ways

    "boss", ["b", "o", "s", "bo", "os"] → 3

  • A card is used more than once

    "sos", ["s", "o", "os"] → 2

Besides these, the challenge has hidden tests that are revealed when you submit your solution.

You start with this

Python

def ways(word, symbols):
    pass

JavaScript

function ways(word, symbols) {
}
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(2ⁿ) challenges

See all challenges →