Dataford
Popular roles
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Browse
Browse All RolesEvery role hub, from analyst to MLBrowse All CompaniesCompany-specific interview loopsAll Interview GuidesThe full guide library
Top questions by role
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Top questions by skill
SQLPythonStatisticsMachine LearningA/B TestingSystem DesignGenerative AIProduct SenseMetricsBehavioral
Browse all questions →Try a mock interview
ExperiencesCoaching
New
Practice
Mock InterviewsTimed interview simulations with feedbackSuccess PathYour 6-week structured planModulesCurated lessons by topicWebinarsTalks from ex-Big Tech data leadsPlaygroundA free-form scratch editor
Learn
BlogInterview strategy and career adviceTech Job Market ReportHiring trends across data and AI rolesFor UniversitiesDataford for career centersAbout DatafordWho we are and how we build
Pricing
Start free
Online Grep With Context
00:00
5 left

Online Grep With Context

HardPython

Problem

Verily Study Watch ingestion logs can be too large to load into memory. Implement an online grep-style function that scans an iterable of log lines, selects lines matching a regular expression, and returns surrounding context while merging overlapping match regions.

Formal Specification

Implement grep_context(lines, pattern, before, after), where lines is an iterable of strings, pattern is a valid regular expression, and before and after are nonnegative integers. Return a list of match blocks. Each block is a list of [line_number, line] pairs, using one-based line numbers. Include up to before preceding lines and up to after following lines for every matching line. A line must appear at most once in a block. Merge blocks whose context ranges overlap or touch.

The function must process lines in one forward pass. Do not convert the input iterable to a list or assume it supports random access. The implementation may buffer only the context needed to decide whether a later match extends the current block.

Constraints

  • 0 <= before, after <= 10^4
  • 0 <= number of input lines <= 10^7
  • Each line contains at most 10^4 characters
  • pattern is a valid regular expression
  • Matching uses re.search independently for each line

Function Signature

def grep_context(lines, pattern, before, after):
Interviewer

Whenever you're ready, walk me through your approach or go straight to the code. The requirements are in the Question tab.

Sign up free to run or submit. Log in
Code
Sign up free to run your code. Your draft is saved.Run with a free accountLog inLn 2
Run your code to see test output here.