#28
Easy Algorithms Find the index of the first occurrence in a string
Two Pointers String String Matching
46.3% acceptance
Jan 12, 2026
7515
571
Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Solution
Rust
Time O(n²)
Space O(1)
impl Solution {
pub fn str_str(haystack: String, needle: String) -> i32 {
if needle.is_empty() {
return 0;
}
let haystack_bytes = haystack.as_bytes();
let needle_bytes = needle.as_bytes();
let haystack_len = haystack_bytes.len();
let needle_len = needle_bytes.len();
if needle_len > haystack_len {
return -1;
}
for i in 0..=(haystack_len - needle_len) {
let mut found = true;
for j in 0..needle_len {
if haystack_bytes[i + j] != needle_bytes[j] {
found = false;
break;
}
}
if found {
return i as i32;
}
}
-1
}
}