Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Word Co-Occurrence in a Line

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Word Co-Occurrence in a Line. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Tessian Email Security analyses message text for suspicious language patterns. Given one line of text and a window size, count how often each pair of distinct words co-occurs within that many token positions.

Formal specification

Implement find_cooccurrences(line, window_size). Tokenize line by extracting contiguous alphanumeric sequences, convert tokens to lowercase, and ignore punctuation. For every pair of distinct words whose positions differ by at most window_size - 1, increment that pair's count once. Each pair must be represented in lexicographic order as [word1, word2, count]. Return all pairs sorted lexicographically by word1, then word2. Return an empty list when no pair co-occurs.

Repeated occurrences count separately. For example, the two occurrences of alert in alert alert review do not form a pair with each other, but both can co-occur with review when the window permits it.

Constraints

  • 1 <= len(line) <= 10^5
  • 1 <= window_size <= 100
  • The line contains only ASCII letters, digits, whitespace, and punctuation
  • Word matching is case-insensitive
  • Only pairs of distinct words are counted
  • Output pairs are sorted lexicographically

Function Signature

def find_cooccurrences(line, window_size):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output