Grep with context lines
Implement a simplified grep. You get a list of text lines, a search string target, and a non-negative integer k. Return every line that contains target, together with up to k lines before it and up to k lines after it.
def grep_with_context(lines: list[str], target: str, k: int) -> list[str]: ...
Rules:
- A line matches if
targetappears anywhere in it as a case-sensitive substring, including inside a longer word."log"matches"catalog"but not"LOG". - Context windows stop at the start and end of the input.
- Each line appears at most once in the result, even if it is in the context of several matches.
- The result keeps the original line order.
Constraints: 0 <= len(lines) <= 10^5, each line up to 10^3 characters, 0 <= k <= 10^5.
Example 1
lines = ["boot ok", "disk warn", "net ok", "cpu ok", "fan warn", "done"]
target = "warn", k = 1
output = ["boot ok", "disk warn", "net ok", "cpu ok", "fan warn", "done"]
The windows are lines 0-2 and 3-5. Together they cover every line, each once.
Example 2
lines = ["a", "bx", "c", "d", "e", "fx", "g"]
target = "x", k = 0
output = ["bx", "fx"]
Be ready for follow-ups: different before/after counts, a -- separator between groups, and input too large to hold in memory.
Reconstructed from the reported question; details may differ from what interviewers ask.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.

