Skip to main content

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

Published 1 min readMarkdown
Part of seriesCoding Memories

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.

About the author

  • 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?

No comments yet. Be the first to comment.

More from this blog