easy Find the Index of the First Occurrence in a String
Problem Statement
Given two strings str1 and str2, return the index of first occurrences of the str2 string in str1. If str2 doesn't exists in str1 string, return -1.
Examples
-
Example 1:
- Input:
str1 = "algorithms", str2 = "rith" - Expected Output:
4 - Justification: The substring
"rith"begins at index 4 in the string"algorithms".
- Input:
-
Example 2:
- Input:
str1 = "openai", str2 = "ai" - Expected Output:
4 - Justification: The substring
"ai"starts at index 4 in the string"openai".
- Input:
-
Example 3:
- Input:
str1 = "challenge", str2 = "test" - Expected Output:
-1 - Justification: The substring
"test"does not appear in the string"challenge", hence the output is -1.
- Input:
Try it yourself
Try solving this question here:
✅ Solution Find the Index of the First Occurrence in a String
Problem Statement
Given two strings str1 and str2, return the index of first occurrences of the str2 string in str1. If str2 doesn't exists in str1 string, return -1.
Examples
-
Example 1:
- Input:
str1 = "algorithms", str2 = "rith" - Expected Output:
4 - Justification: The substring
"rith"begins at index 4 in the string"algorithms".
- Input:
-
Example 2:
- Input:
str1 = "openai", str2 = "ai" - Expected Output:
4 - Justification: The substring
"ai"starts at index 4 in the string"openai".
- Input:
-
Example 3:
- Input:
str1 = "challenge", str2 = "test" - Expected Output:
-1 - Justification: The substring
"test"does not appear in the string"challenge", hence the output is -1.
- Input:
Solution
To solve this problem, we'll adopt a straightforward search approach. We iterate through the main string (str1) and for each position, we check if the following characters match the target substring (str2).
This method is effective because it directly compares segments of the str1 with the str2, ensuring that no possible starting point is overlooked. The key to this approach's effectiveness lies in its meticulous examination of each potential match point, guaranteeing that as soon as the str2 is found, its starting index is immediately returned, optimizing for both clarity and efficiency.
Step-by-step Algorithm
- Start by checking if the str2 is empty. If it is, return 0, as an empty string is considered to be found at the beginning.
- Loop through the str1 string starting from index 0.
- For each index in the str1, compare the substring that starts at this index and spans the length of the str2 with the str2 itself.
- If a match is found, return the current index as the starting point of the str2 in the str1.
- If no match is found by the end of the loop, return -1 to indicate the str2 was not found in the str1.
Algorithm Walkthrough
Using the input str1 = "algorithms", str2 = "rith":
-
Initialization: We start with
str1 = "algorithms"andstr2 = "rith". The goal is to find the first occurrence ofstr2instr1. -
Check for Empty
str2: First, check ifstr2is empty. Sincestr2is not empty, we proceed to the next step. -
Start Looping Through
str1:- We initiate a loop that starts from index 0 of
str1and will go up tostr1.length - str2.lengthto ensure we can compare the full length ofstr2without going out of bounds.
- We initiate a loop that starts from index 0 of
-
Index 0 (
i = 0):- Compare
str1.substring(0, 4)("algo") withstr2("rith"). - The substring does not match
str2. Move to the next index.
- Compare
-
Index 1 (
i = 1):- Compare
str1.substring(1, 5)("lgor") withstr2. - The substring does not match
str2. Move to the next index.
- Compare
-
Continue Looping Until Index 4:
- At each index, we are slicing
str1from the current indexitoi + str2.lengthand comparing it withstr2.
- At each index, we are slicing
-
Index 4 (
i = 4):- At index 4, the substring of
str1isstr1.substring(4, 8)("rith"). - This substring matches
str2exactly.
- At index 4, the substring of
-
Match Found:
- Since the substring starting from index 4 matches
str2, we return 4 as the index wherestr2first occurs instr1.
- Since the substring starting from index 4 matches
Code
public class Solution {
// Method to find the first occurrence of str2 in str1
public int findFirstOccurrence(String str1, String str2) {
if (str2.isEmpty()) return 0; // If str2 is empty, return 0
for (int i = 0; i <= str1.length() - str2.length(); i++) {
// Check if the substring of str1 starting at i matches str2
if (str1.substring(i, i + str2.length()).equals(str2)) {
return i; // Return the index if a match is found
}
}
return -1; // Return -1 if no match is found
}
public static void main(String[] args) {
Solution solution = new Solution();
// Test the method with example inputs
System.out.println(solution.findFirstOccurrence("algorithms", "rith")); // Expected output: 4
System.out.println(solution.findFirstOccurrence("openai", "ai")); // Expected output: 4
System.out.println(solution.findFirstOccurrence("challenge", "test")); // Expected output: -1
}
}
Complexity Analysis
`
- Time Complexity:
, where nis the length of the str1 andmis the length of the str2. In the worst case, we need to check each substring of the str1 that has the same length as the str2. - Space Complexity:
, as we only use a few variables for iteration and comparison, regardless of the input size.
🤖 Don't fully get this? Learn it with Claude
Stuck on Find the Index of the First Occurrence in a String? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Find the Index of the First Occurrence in a String** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Find the Index of the First Occurrence in a String** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Find the Index of the First Occurrence in a String**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Find the Index of the First Occurrence in a String**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.