Pattern Finder
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 92 of 93.
Challenge
MediumWrite 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 withinpattern(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
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic InputPractice on your own: Kotlin playground