Ctrl K

Closest Card on the Ring

Easy
Word cards are laid out in a circle: the list cards wraps around, so the first card follows the last one. With n = len(cards), the neighbours of card i are (i + 1) % n and (i - 1 + n) % n. You stand at the card with index start, and each step takes you to a neighbouring card, in either direction. Return the fewest steps needed to reach a card showing the word wanted. If no card shows that word, return -1.
Example 1
cards=['sun', 'moon', 'star', 'comet', 'moon', 'sky'], wanted='sky', start=1 → 2

From position 1, "sky" (position 5) is 4 steps forward, but only 2 steps backward around the ring: 1 → 0 → 5.

Example 2
cards=['red', 'blue', 'red'], wanted='red', start=2 → 0

The wanted word is right at the starting position, so no moves are needed.

Example 3
cards=['one', 'two'], wanted='three', start=0 → -1

"three" is not on the ring at all, so the answer is -1.

Constraints
  • 1 ≤ len(cards) ≤ 100
  • 1 ≤ length of each word in cards and of wanted ≤ 100
  • All words consist of lowercase English letters
  • 0 ≤ start < len(cards)
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTwo Words, Closest Apart EasyOne-Row Typing EasyDinner for Two EasyPhrases with Synonyms EasyWord from a License Plate Easy
loading Python…
Input
cards=['sun', 'moon', 'star', 'comet', 'moon', 'sky'], wanted='sky', start=1
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 245 tests on the server, hidden ones included.