Skip to main content

Command Palette

Search for a command to run...

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

Updated
1 min read
R

South Korean, master's degree of AI. A research focused AI specialist, and a rogrammer for LLM. I am seeking opportunities worldwide. I used to live in Frankfurt, Moscow, Pretoria, Baguio. Where to next?

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.

More from this blog

R

Ramieeee's IT blog

36 posts

Algorithms, IT news, my thoughts note