Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

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
Topics
String
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions