Ctrl K

First Word With a Given Beginning

Easy
The string line is made of words separated by single spaces. You are also given a short pattern start. Find the first word in line that **begins** with start and return its number (words are numbered from 1). If several words qualify, return the smallest number. If none do, return -1. A word begins with start when its first len(start) letters equal start; the word itself counts too.
Example 1
line="we need more coffee", start="cof" → 4

"coffee" begins with "cof", and it is the fourth word.

Example 2
line="pass the paste please", start="pas" → 1

Both "pass" (word 1) and "paste" (word 3) begin with "pas". The smallest number wins: 1.

Example 3
line="cat dog", start="at" → -1

"at" occurs inside "cat", but no word begins with it.

Constraints
  • 1 ≤ len(line) ≤ 100
  • 1 ≤ len(start) ≤ 10
  • line consists of lowercase English letters with single spaces between words and none at the ends
  • start consists of lowercase English letters
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsWhere the Fragment Starts EasyCapitals Follow the Pattern MediumAnchor Near a Companion MediumWord Near an Anchor HardShortest Match for a Two-Star Pattern Hard
loading Python…
Input
line="we need more coffee", start="cof"
Expected
4

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