← Questions

Grep with context lines

0
GoogleSnowflakeCodingLast asked Feb 2026

A coding interview question asked in Snowflake's coding round and at Google, last asked Feb 2026. It tests arrays, intervals and strings.

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 target appears 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.

Clarifying questions

  • Is an empty target a match on every line?
  • Should overlapping or touching windows simply merge into one run?
  • Is the output just the lines, or also their line numbers?

What a strong answer covers

  • Scans once, finds matches with the in substring test, and tracks the furthest line already emitted so each line appears once.
  • For each match, emits lines from max(last_emitted + 1, i - k) to min(i + k, len - 1), in order: O(total characters) and never O(matches * k).
  • Stops windows at the start and end of the input.
  • Keeps matching case-sensitive and inside longer words (log in catalog).
  • Tests both examples, k = 0, overlapping windows, k larger than the input and no matches.

Follow-ups

  • Different counts before and after (-B and -A).
  • Print -- between groups that do not touch.
  • Input too large for memory: stream lines with a buffer of the last k.

Where it's asked

  • Snowflake · Coding · Last asked Feb 202660 min · Live coding; senior loops may agree a small storage component together, then build it
  • Google

What it tests

arrays · intervals · strings · streaming

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding