Introduction

Hello, and welcome to our analysis lesson. Today, we will be exploring a classic problem in the realm of string manipulations. We'll learn how to locate all occurrences of a substring within a larger string using Scala. The techniques you will learn can be utilized in scenarios such as text processing and data analysis. Are you ready to dive in? Let's get started!

Task Statement and Description

Here's our challenge: we have two lists of strings of the same length, one containing the "original" strings and the other containing the "substrings." Our task is to identify all occurrences of each substring within its corresponding original string and return a list of the starting indices of these occurrences. Remember, index counting should start from 0.

Example

If we take the following lists:
Original List: List("HelloWorld", "LearningScala", "GoForBroke", "BackToBasics")
Substring List: List("loW", "ear", "o", "Ba").

This will produce the following outputs:
In "HelloWorld", "loW" starts at index 3.
In "LearningScala", "ear" starts at index 1.
In "GoForBroke", "o" appears at indices 1, 3, and 7.
In "BackToBasics", "Ba" starts at indices 0 and 6.

So, if findSubStrings(List("HelloWorld", "LearningScala", "GoForBroke", "BackToBasics"), List("loW", "ear", "o", "Ba")) is called, the function should return

List(
    "The substring 'loW' was found in the original string 'HelloWorld' at position(s) 3.",
    "The substring 'ear' was found in the original string 'LearningScala' at position(s) 1.",
    "The substring 'o' was found in the original string 'GoForBroke' at position(s) 1, 3, 7.",
    "The substring 'Ba' was found in the original string 'BackToBasics' at position(s) 0, 6."
)
Step-by-Step Solution: Initializing the Output

First, we need to create a place to store the result of our findings. In Scala, we can use a ListBuffer to accumulate results, which can later be converted into an immutable List.

import scala.collection.mutable.ListBuffer

def solution(origStrs: List[String], substrs: List[String]): List[String] = {
    val resultArr = ListBuffer[String]()
Pairing Strings and Finding First Occurrence

We use Scala's zip method to create pairs of original strings and substrings. We then use the indexOf method to find the first occurrence of each substring in its related original string. The indexOf method in Scala returns the index of the first occurrence of the substring if found, or -1 if not found.

for ((original, substring) <- origStrs zip substrs) {
    var startPos = original.indexOf(substring)
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal