KatInterview

Word Matcher and File System Implementation

Data Structure DesignModel answer
MediumModel answerData Structure Designstring-processingdata-structurestree

Last updated

Build a function to find whole-word keyword matches in text, then design an in-memory file system with directory and file operations.

You are asked to solve two independent problems that test your ability to handle string processing and design hierarchical data structures.

Part 1: Keyword Finder

Write a function that accepts a text string and a list of keywords, returning which keywords appear in the text as complete words. A keyword matches only when it occurs as a full word or sequence of words, not as a substring within a larger word.

Requirements:

  • Matching should ignore case differences
  • A keyword like "data" should match "Data" in the text, but not "database"
  • Punctuation marks separate words, so "data," or "(data)" should match the keyword "data"
  • Keywords can be multi-word phrases like "machine learning"
  • Each keyword should appear at most once in the output, even if it occurs multiple times in the text or keyword list
  • Return keywords in the order they appear in the input list

Part 2: File System

Design and implement an in-memory file system supporting these operations:

  • ls(path): If the path points to a file, return a list containing just that filename. If it points to a directory, return the names of all children sorted alphabetically.
  • mkdir(path): Create a directory at the given path, including any missing parent directories.
  • write(path, content): Write content to a file at the given path, creating the file and any missing parent directories if needed. If the file already exists, append the new content to it.
  • read(path): Return the complete contents of the file at the given path.

All paths are absolute (start with /) and use forward slashes as separators.

Discuss your choice of data structure, how you handle path parsing, and what happens with edge cases like creating nested directories or writing to non-existent paths.

Hints

Hint 1

For keyword matching, consider tokenizing both the text and keywords the same way so they can be compared directly

Hint 2

An n-gram approach lets you check multi-word phrases efficiently by building all possible word sequences from the text

Hint 3

For the file system, a tree where each node represents a path component works well—directories store child nodes, files store content

Hint 4

Think about whether to use a list or string for file content to make appends efficient