Start learning free

LESSON 15 OF 70 · PROJECTS: COMMAND-LINE TOOLS

grep v3 in Scala: Invert Match with !contains

Practice Read the full explanation

Build the -v flag of the Unix grep command. Given a list of lines and a search pattern, return all lines that DO NOT contain pattern as a substring (case-sensitive). Return the remaining lines (the ones that do not contain the pattern), in their original order, joined by newline characters (\n).

Function signature:

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

Example:

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

Output: "ok\nfine"

When printed:
ok
fine

If every line contains the pattern, return the empty string "".


Same as grep v1 but flip the condition: keep the lines where !line.contains(pattern) is true, then return result.mkString("\n").

The full solution:
class Solution {
    def grepInvert(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 V3 in Scala, explained

    Problem overview

    This version adds the -v flag of grep. grepInvert(lines: Array[String], pattern: String): String returns the lines that do not contain pattern as a substring (case-sensitive), in their original order, joined by \n. If every line contains the pattern, the result is the empty string.

    With pattern = "err" and lines = ["error", "ok", "another error", "fine"], the lines "error" and "another error" contain err and are dropped. The result is "ok\nfine".

    Approach

    The first grep version kept the lines for which contains was true. This one keeps the lines for which it is false. The whole change is one character: a ! in front of the test.

    Everything else carries over. Loop over the lines, append the lines that pass the test to a growable ArrayBuffer, and join the buffer with mkString("\n") at the end. The order of the lines is kept because lines are appended as the loop reaches them. The result is empty when every line contains the pattern, because then nothing is ever appended, and joining an empty buffer gives "".

    Notice that "doesn't contain" is the exact complement of "contains": each line goes to exactly one of the two outputs. Running the previous function and this one on the same input would split the lines into two groups that together make up the whole input.

    Step by step

    1. Create the buffer. A val named result holds an empty scala.collection.mutable.ArrayBuffer[String].
    2. Loop over the lines with for (line <- lines).
    3. Negate the test. The if uses !line.contains(pattern), which is true when the pattern does not appear anywhere in the line.
    4. Keep the line. Append line to result with +=. Only lines without the pattern get here.
    5. Join and return with result.mkString("\n").

    The solution in Scala

    class Solution {
        def grepInvert(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 to notice:

    • ! is the logical NOT operator. It applies to the whole call that follows it, line.contains(pattern), and gives a Boolean.
    • The comparison is case-sensitive, so a line with "ERR" is not removed by the pattern "err".
    • An empty pattern is contained in every line, so with pattern = "" nothing survives and the result is "".
    • result += line works on a val because the buffer itself is modified, not reassigned.

    Complexity

    Each line is searched once, so the time is proportional to the total size of the input (and the pattern length in the worst case of each search). The buffer holds references to at most all n lines, so the extra space is O(n) plus the joined result.

    Edge cases and common mistakes

    • Forgetting the !. The code would then be the first version and return the matching lines.
    • All lines match. The result is "", not a blank line; the buffer is empty so mkString has nothing to join.
    • No line matches. Every line is kept and joined by newlines.
    • Case mix-ups. This version doesn't ignore case, so "Error" survives the pattern "err".
    • Changing the order. Keep lines in the order they appear; the loop does this naturally.

    Testing

    linespatternResult
    Array("error", "ok", "another error", "fine")"err""ok\nfine"
    Array("error", "another error")"err"""
    Array("a", "b")""""
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free