Skip to the content

The necklace both threads share

Problem

Rosalba strings bead necklaces at the street market and writes each one down in her notebook using the first letter of every bead's color: b for blue, p for purple, r for red, g for green, w for white. So "brgpb" is a thread of five beads. Today she was asked for two similar necklaces, and she wants to measure how alike they are with this rule: how long is the longest necklace she can build by taking beads off both threads. What she measures is that necklace, the one left over, not how many beads she had to take off.

Write a function that takes one and other, two strings of lowercase letters of at most 12 beads each (they may be empty). Return, as a whole number, how many beads the longest necklace that comes out of both has. Taking a necklace out of a thread means removing whichever beads you want: the ones that stay do not move, so they keep the same order, and they did not have to be next to each other on the thread.

With "brgpb" and "bgpb" you return 4: take the r off the first one and both are left as "bgpb". With "bprgbg" and "rbgpgb" you also return 4: "bpgb" comes out of both by removing beads, and no necklace of five beads comes out of both.

If they share no color at all, or if either thread is empty, you return 0.

Examples

  • The example

    "brgpb", "bgpb" → 4

  • Beads come off both threads

    "bprgbg", "rbgpgb" → 4

  • They share no color

    "bbp", "rrg" → 0

  • The beads were not next to each other

    "brgwp", "bwp" → 3

  • Both necklaces are the same

    "bpgrb", "bpgrb" → 5

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

You start with this

Python

def shared_necklace(one, other):
    pass

JavaScript

function sharedNecklace(one, other) {
}
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 →