Menu
Coddy logo textTech

Pattern Finder

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 92 of 93.

challenge icon

Challenge

Medium

Write a function findPattern that takes text and pattern and returns the starting index of the first occurrence of the pattern within the text.

Search through the text to find where the pattern first appears. If found, return its 0-based starting index. If the pattern doesn't exist in the text, return -1.

Logic:

  • Iterate through possible starting positions in the text
  • At each position, check if the substring matches the pattern
  • Return the index as soon as a match is found
  • If no match is found after checking all positions, return -1

Parameters:

  • text (String): The text to search within
  • pattern (String): The pattern to find

Returns: The 0-based index where the pattern first appears, or -1 if not found (Int)

Input constraints: An empty pattern matches at index 0. A pattern longer than the text has no match.

Try it yourself

fun findPattern(text: String, pattern: String): Int {
    // Write code here
}

All lessons in Fundamentals

Practice on your own: Kotlin playground