First Occurrence In A String
Medium Acceptance 50.08% Points 30.00
You are given two strings, text and pattern. Determine the first index in text where pattern appears as an exact substring.
- If pattern exists in text, return the starting index of its first occurrence.
- If pattern does not exist in text, return -1.
Examples
Example 1
Example 1
Input: text = "helloworld", pattern = "world"
Output: 5
Explanation: In the string "hello world", the substring "world" starts at index 5 (0 based indexing)..
Hints
Hint 1
Expected Time Complexity: O(|text| * |pattern|)
Hint 2
Expected Space Complexity: O(1)
Constraints
- 1 <= |text|,|pattern| <= 10^3
- text and pattern consists of lowercase alphabets.
Companies
Amazon Walmart TCS Infosys Wipro
Track your submissions
Please log in to review your progress and explore code submissions from other participants.
Unlock the full solution
Please log in to access detailed answers and explanations.
Join the discussion
Please log in to join conversations with other participants.