Start learning free

LESSON 14 OF 70 · PROJECTS: COMMAND-LINE TOOLS

grep -i in TypeScript: Case-Insensitive Match

Practice Read the full explanation

Build the -i flag of the Unix grep command. Given a list of lines and a search pattern, return all lines that contain pattern as a substring, ignoring letter case. Return the matching lines joined by newline characters (\n).

Function signature:

grepCaseInsensitive(lines: string[], pattern: string): string

Example:

Input:
pattern = "ERR"
lines = ["Error: 1", "ok"]

Output: "Error: 1"

When printed:
Error: 1

The matching is case-insensitive but the original line (preserving its original casing) is returned. If no lines match, return the empty string "". The lines contain only ASCII characters.


Compute pattern.toLowerCase() once. For each line, run lines[i].toLowerCase().includes(lowerPattern). If true, push the ORIGINAL line.

The full solution:
class Solution {
    grepCaseInsensitive(lines: string[], pattern: string): string {
        let result: string[] = [];
        let lowerPattern: string = pattern.toLowerCase();
        for (let i = 0; i < lines.length; i++) {
            if (lines[i].toLowerCase().includes(lowerPattern)) {
                result.push(lines[i]);
            }
        }
        return result.join("\n");
    }
}

STEP 1 OF 6
    Ctrl + Enter to check

    TYPESCRIPT · PROJECTS: COMMAND-LINE TOOLS

    Grep V2 in TypeScript, explained

    Problem overview

    This version adds the -i flag of grep. The method grepCaseInsensitive(lines: string[], pattern: string): string returns all the lines that contain pattern as a substring, ignoring letter case, joined by newline characters. The lines come back exactly as they were, with their original capitals. If nothing matches, the result is "". The lines are ASCII text.

    With pattern = "ERR" and lines = ["Error: 1", "ok"], the result is "Error: 1": the capitals in the pattern do not matter, and the line keeps its own E.

    Approach: compare in lowercase, return the original

    The previous version tested lines[i].includes(pattern). To ignore case, both sides of the comparison must be in the same case. Lowercase is the usual pick. The key detail is to use the lowercase text only for the test and to keep the original line for the answer. If you lowercased the line and pushed that, "Error: 1" would come back as "error: 1".

    The pattern is the same for every line, so lowercase it once before the loop. Each line has to be lowercased inside the loop, because each line is different.

    Step by step

    1. Create the result: an empty string[] named result.
    2. Lowercase the pattern once. let lowerPattern: string = pattern.toLowerCase() runs once, before any line is looked at. Repeating it per line would give the same answer with wasted work.
    3. Loop by position with i from 0 while i < lines.length.
    4. Compare in lowercase. The test is lines[i].toLowerCase().includes(lowerPattern). Both sides are lowercase now, so ERR finds Error. The expression creates a lowercase copy of the line for the test, and lines[i] itself is not changed.
    5. Push the original. result.push(lines[i]) keeps the capitals.
    6. Join with newlines and return: result.join("\n").

    The solution in TypeScript

    class Solution {
        grepCaseInsensitive(lines: string[], pattern: string): string {
            let result: string[] = [];
            let lowerPattern: string = pattern.toLowerCase();
            for (let i = 0; i < lines.length; i++) {
                if (lines[i].toLowerCase().includes(lowerPattern)) {
                    result.push(lines[i]);
                }
            }
            return result.join("\n");
        }
    }

    Language details:

    • Strings are immutable in JavaScript. toLowerCase() never changes the string it is called on: it returns a new one. That is why lines[i] still has its capitals when it is pushed, and why calling pattern.toLowerCase() without using the result would do nothing.
    • The lowercase copy of each line is a temporary value. It is not stored anywhere and is discarded after the includes call.
    • toUpperCase() on both sides would work equally well for ASCII text. What matters is using the same conversion on both.
    • For non-ASCII text, case conversion has special cases in some alphabets. The lesson's lines are ASCII, so toLowerCase is enough here.

    Complexity

    Each line is lowercased and searched once, so the running time is proportional to the total number of characters, ignoring the cost of the substring search itself. Each line's lowercase copy takes space proportional to that line, and the result array can hold all the lines, so the extra space is at most the size of the input.

    Edge cases and common mistakes

    • Lowercasing only one side. If only the pattern is lowercased, "Error: 1" would never match, because the line still has a capital letter. Both sides need the same case.
    • Returning the lowercase line. The answer for ["Error: 1", "ok"] with "ERR" is "Error: 1", not "error: 1".
    • Mixed case in the lines. With ["Error: 1", "ok", "eRRor"] and "err" both "Error: 1" and "eRRor" match, and the result is "Error: 1\neRRor".
    • No match. ["ok"] with "ERR" gives "", because joining an empty array gives the empty string.

    Testing

    linespatternResult
    ["Error: 1", "ok"]"ERR""Error: 1"
    ["Error: 1", "ok", "eRRor"]"err""Error: 1\neRRor"
    ["ok"]"ERR"""

    The next version builds on this one.

    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free