Dataford
Interview QuestionsInterview GuidesExperiencesCoaching
New
Pricing
Get started
Dataford
Popular roles
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Browse
Browse All RolesEvery role hub, from analyst to MLBrowse All CompaniesCompany-specific interview loopsAll Interview GuidesThe full guide library
Top questions by role
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Top questions by skill
SQLPythonStatisticsMachine LearningA/B TestingSystem DesignGenerative AIProduct SenseMetricsBehavioral
Browse all questions →Try a mock interview
ExperiencesCoaching
New
Practice
Mock InterviewsTimed interview simulations with feedbackSuccess PathYour 6-week structured planModulesCurated lessons by topicWebinarsTalks from ex-Big Tech data leadsPlaygroundA free-form scratch editor
Learn
BlogInterview strategy and career adviceTech Job Market ReportHiring trends across data and AI rolesFor UniversitiesDataford for career centersAbout DatafordWho we are and how we build
Pricing
Get started
First Occurrence of a Word
00:00
5 left

First Occurrence of a Word

EasyPython

Problem

Find the first occurrence of a word in a sentence, e.g. sentence 'can a cat eat grass cat?', pet 'cat' returns 6.

Asked in the round 3 stage. Implement the function using zero-based character indexing. Treat pet as a case-sensitive contiguous substring, including occurrences inside longer words.

Input and Output

find_first_occurrence(sentence, pet) receives two strings and returns the starting index of the first occurrence, or -1 if pet does not occur. If pet is empty, return 0.

Constraints

  • 0 <= len(sentence) <= 5,000
  • 0 <= len(pet) <= 500
  • Matching is case-sensitive
  • Return a character index, not a word index
  • An empty pet returns 0

Function Signature

def find_first_occurrence(sentence, pet):
Interviewer

Your question is First Occurrence of a Word. Start with the requirements in the Question tab.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.
Code
Sign up free to run your codeLog inLn 2
Run your code to see test output here.