call(back)
Algorithms & Data StructuresmediumSign in to star problems

Grep With Context Lines

Implement the core of grep -B before -A after: given the lines of a file and a pattern, return the output lines. A line matches when it contains pattern. Each match is shown with up to before lines above and after lines below; groups of lines that overlap or touch are merged, every line is shown at most once, and non-adjacent groups are separated by a line --.

grep(["a", "b", "match", "c", "d", "e", "match", "f"], "match", 1, 1)
  ->  ["b", "match", "c", "--", "e", "match", "f"]

Hints

Hint 1

Map every matching line index i to the range [i − before, i + after], clipped to the file. Ranges that overlap or sit next to each other merge into one group.

Hint 2

Emit each group's lines in order, with "--" before every group except the first.

Asked at