[LeetCode] Top Interview 150 Problems Solving # 28 Find the Index of the First Occurrence in a String

Ramhee YeonRamhee Yeon
1 min read

Understanding the Problem

There are two strings given as haystack and needle. needle is the string that could be included in haystack or not included. If it is included, return the first index that needle occurs. If it is not included in haystack, return -1.

For example, if haystack = "sadbutsad" and needle = "sad", the string ”sad” occurs at the index 0 and 6, so return 0.

Approach

My approach is to check whether needle is in haystack, then find the first index.

Solution

  1. Check if needle is in haystack by if needle in haystack clause

  2. If it exists in haystack, then use find() method to get the first index of the needle and return it

  3. If it does not exist in haystack, return -1

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        return haystack.find(needle) if needle in haystack else -1

Reflection

I was wondering if I should use two pointers to solve this problem, but no need for that, as there are internal functions and methods to use.

0
Subscribe to my newsletter

Read articles from Ramhee Yeon directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ramhee Yeon
Ramhee Yeon

South Korean, master's degree of AI. Programmer for LLM, app and web development. I am seeking opportunities to go to the USA and Canada, and Europe. I used to live in Frankfurt, Moscow, Pretoria, Baguio. Where to next?