Start learning free

LESSON 13 OF 70 · PROJECTS: COMMAND-LINE TOOLS

grep v1 in Scala: Substring Match with contains

Practice Read the full explanation

Build a tiny version of the Unix grep command. Given a list of lines and a search pattern, return all lines that contain pattern as a substring (case-sensitive), joined by newline characters (\n).

Function signature:

def grep(lines: Array[String], pattern: String): String

Example:

Input:
pattern = "err"
lines = ["error: foo", "warning", "another error", "ok"]

Output: "error: foo\nanother error"

When printed:
error: foo
another error

If no lines match, return the empty string "".

Note: real grep treats the pattern as a regular expression by default (grep -F matches plain text). Here the pattern is always plain text: just look for it literally, so characters such as . or * mean nothing special.


Iterate over the lines, keep the ones where line.contains(pattern) is true, then return result.mkString("\n").

The full solution:
class Solution {
    def grep(lines: Array[String], pattern: String): String = {
        val result = scala.collection.mutable.ArrayBuffer[String]()
        for (line <- lines) {
            if (line.contains(pattern)) {
                result += line
            }
        }
        return result.mkString("\n")
    }
}

STEP 1 OF 5
    Ctrl + Enter to check

    SCALA · PROJECTS: COMMAND-LINE TOOLS

    Grep V1 in Scala, explained

    Problem overview

    This first grep version filters lines. grep(lines: Array[String], pattern: String): String returns every line that contains pattern as a substring, in the original order, joined by newline characters (\n) into one string. The match is case-sensitive, and when no line matches the result is the empty string.

    With pattern = "err" and lines = ["error: foo", "warning", "another error", "ok"], the lines "error: foo" and "another error" contain err, so the result is "error: foo\nanother error". Printed, that is two lines.

    The pattern is always plain text. Real grep reads its pattern as a regular expression by default, but here characters such as . and * mean nothing special and are searched for literally.

    Approach

    Go through the lines once, keep the ones that pass a test, and glue the kept lines together at the end. The test is the string method contains, which looks for the pattern anywhere in the line, not only at the start. Because contains takes the text literally, no escaping is needed for special characters: "a.c".contains("a.c") is true, while "abc".contains("a.c") is false.

    The kept lines go into a growable collection. An Array has a fixed size, and the number of matches isn't known in advance, so the lesson uses a mutable ArrayBuffer. Scala's default collections are immutable, so the full name scala.collection.mutable.ArrayBuffer says explicitly that this one can grow.

    Finally, mkString("\n") joins the buffer's items with a newline between each two. It puts the separator only between items, never after the last one, so the result has no trailing newline. For an empty buffer it returns the empty string, which is the result the statement asks for when nothing matches.

    Step by step

    1. Create the buffer. A val named result holds an empty ArrayBuffer[String]. A val is enough, since lines are added to the buffer and the buffer is never replaced.
    2. Loop over the lines with for (line <- lines).
    3. Test each line with line.contains(pattern) inside an if.
    4. Keep the match. Inside the if, result += line appends the line to the buffer.
    5. Join and return. After the loop, result.mkString("\n") produces the answer.

    The solution in Scala

    class Solution {
        def grep(lines: Array[String], pattern: String): String = {
            val result = scala.collection.mutable.ArrayBuffer[String]()
            for (line <- lines) {
                if (line.contains(pattern)) {
                    result += line
                }
            }
            return result.mkString("\n")
        }
    }
    

    Details worth knowing:

    • ArrayBuffer[String]() creates an empty buffer without writing new. The element type in the brackets is what lets += accept only strings.
    • result += line changes the buffer in place. It works on a val because the reference stays the same while the contents change.
    • contains is case-sensitive, so "Error".contains("err") is false.
    • An empty pattern is contained in every string, so pattern = "" keeps all the lines.

    Complexity

    Each line is tested once, and a substring search costs time proportional to the line's length times the pattern's length in the worst case. With n lines the work is proportional to the total size of the input. The buffer can hold every line, so the extra space is O(n) references to lines that already exist, plus the joined result string.

    Edge cases and common mistakes

    • No matches. The buffer stays empty and mkString returns "". No special case is needed.
    • Adding a newline after every line. That leaves a trailing newline. Let mkString place the separators.
    • Treating the pattern as a regular expression. Searching with contains keeps . and * literal, as the lesson requires.
    • Matching only at the start. startsWith would reject "another error" for the pattern err.
    • Case. "ERR" finds nothing in "error: foo". Ignoring case is a separate feature.

    Testing

    linespatternResult
    Array("error: foo", "warning", "another error", "ok")"err""error: foo\nanother error"
    Array("a.c", "abc", "a*")"a.c""a.c"
    Array("a.c", "abc", "a*")"a*""a*"
    Array("x", "y")"z"""
    Array("x", "y")"""x\ny"
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free