LeetCode #28. Find the Index of the First Occurrence in a String

Time Complexity O(n*m)

Outer loop: runs n times (roughly haystack length)
Inside each iteration:

substring() = O(m) time (copies m characters)
.equals() = O(m) time (compares m characters)

Total: n iterations × m work per iteration = n*m


This content originally appeared on DEV Community and was authored by Giuseppe

Time Complexity O(n*m)

Outer loop: runs n times (roughly haystack length)
Inside each iteration:

substring() = O(m) time (copies m characters)
.equals() = O(m) time (compares m characters)

Total: n iterations × m work per iteration = n*m

Space Complexity O(m)

The space grows with needle size (m), not haystack size (n).

class Solution {
    public int strStr(String haystack, String needle) {

        for (int i = 0; i <= haystack.length() - needle.length(); i++) {
            if (haystack.substring(i, i + needle.length()).equals(needle)) {
                return i;
            }
        }
        return -1;
    }
}


This content originally appeared on DEV Community and was authored by Giuseppe


Print Share Comment Cite Upload Translate Updates
APA

Giuseppe | Sciencx (2025-08-21T10:36:50+00:00) LeetCode #28. Find the Index of the First Occurrence in a String. Retrieved from https://www.scien.cx/2025/08/21/leetcode-28-find-the-index-of-the-first-occurrence-in-a-string/

MLA
" » LeetCode #28. Find the Index of the First Occurrence in a String." Giuseppe | Sciencx - Thursday August 21, 2025, https://www.scien.cx/2025/08/21/leetcode-28-find-the-index-of-the-first-occurrence-in-a-string/
HARVARD
Giuseppe | Sciencx Thursday August 21, 2025 » LeetCode #28. Find the Index of the First Occurrence in a String., viewed ,<https://www.scien.cx/2025/08/21/leetcode-28-find-the-index-of-the-first-occurrence-in-a-string/>
VANCOUVER
Giuseppe | Sciencx - » LeetCode #28. Find the Index of the First Occurrence in a String. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/08/21/leetcode-28-find-the-index-of-the-first-occurrence-in-a-string/
CHICAGO
" » LeetCode #28. Find the Index of the First Occurrence in a String." Giuseppe | Sciencx - Accessed . https://www.scien.cx/2025/08/21/leetcode-28-find-the-index-of-the-first-occurrence-in-a-string/
IEEE
" » LeetCode #28. Find the Index of the First Occurrence in a String." Giuseppe | Sciencx [Online]. Available: https://www.scien.cx/2025/08/21/leetcode-28-find-the-index-of-the-first-occurrence-in-a-string/. [Accessed: ]
rf:citation
» LeetCode #28. Find the Index of the First Occurrence in a String | Giuseppe | Sciencx | https://www.scien.cx/2025/08/21/leetcode-28-find-the-index-of-the-first-occurrence-in-a-string/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.