Word Matcher and File System Implementation
Data Structure DesignModel answerLast 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
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Both problems require careful contract clarification before coding. Strong candidates state their assumptions explicitly and confirm edge-case behavior.
Part 1: Keyword Finder
Approach
The core challenge is distinguishing whole words from substrings. Using Python's in operator would incorrectly match "data" inside "database". Instead:
-
Normalize and tokenize: Extract sequences of alphanumeric characters from both the text and each keyword, converting everything to lowercase. A regex like
[a-z0-9]+works well. -
Build n-grams: Generate all contiguous sequences of tokens from the text, up to the length of the longest keyword. Store these as tuples in a set for O(1) lookup.
-
Match keywords: For each keyword, tokenize it and check if its token tuple exists in the n-gram set. Track which token sequences you've already matched to avoid duplicates.
This approach correctly handles punctuation (which creates token boundaries), case differences (through lowercasing), and multi-word phrases (through n-gram matching).
Clarifications to make
- Case sensitivity: Treating matches as case-insensitive is typical
- Word definition: Alphanumeric sequences separated by any non-alphanumeric characters
- Multi-word handling: Phrases must appear with consecutive words in order
- Duplicate handling: Return each matching keyword once, preserving the input order
- Empty keywords: Skip keywords that contain no alphanumeric characters
Complexity
Let n be the number of tokens in the text, k be the maximum keyword length in tokens, and m be the total number of tokens across all keywords.
- Time: O(n·k) to build n-grams plus O(m) to check all keywords = O(n·k + m)
- Space: O(n·k) for storing n-grams
For single-word keywords only, this simplifies to O(n + m).
Code
import re
from typing import List
def find_keywords(text: str, keywords: List[str]) -> List[str]:
"""Return keywords that appear as whole words in text."""
def tokenize(s: str) -> tuple:
"""Extract lowercase alphanumeric word sequences."""
return tuple(re.findall(r'[a-z0-9]+', s.lower()))
# Tokenize input text
text_tokens = tokenize(text)
# Build set of all n-grams from text
keyword_tokens = [tokenize(kw) for kw in keywords]
max_length = max((len(kt) for kt in keyword_tokens), default=0)
ngrams = set()
for i in range(len(text_tokens)):
for length in range(1, min(max_length + 1, len(text_tokens) - i + 1)):
ngrams.add(text_tokens[i:i+length])
# Find matching keywords, preserving order and avoiding duplicates
result = []
seen = set()
for keyword, tokens in zip(keywords, keyword_tokens):
if tokens and tokens not in seen and tokens in ngrams:
result.append(keyword)
seen.add(tokens)
return result
Example: find_keywords("The database uses Machine-Learning; data matters!", ["data", "base", "machine learning", "DATA"]) returns ["data", "machine learning"].
Common mistakes
- Using substring search or
str.contains() - Not handling punctuation consistently between text and keywords
- Treating
"machine learning"as two independent single-word matches - Forgetting to deduplicate when the same keyword appears multiple times
Part 2: File System
Design choices
Data structure: Represent the file system as a tree where each node corresponds to one path component. Each node contains:
children: dictionary mapping child names to child nodes (for directories)is_file: boolean flag distinguishing files from directoriescontent_parts: list of strings (for files), supporting efficient append
A dictionary of children provides O(1) lookup per path segment. Storing content as a list avoids repeated string concatenation overhead.
Path parsing: Split on / and filter out empty strings to handle the root path, trailing slashes, and consecutive slashes uniformly.
API behavior
Confirm these behaviors during the interview:
mkdircreates all missing parent directories (likemkdir -p)writecreates the file and parents if they don't exist, and appends to existing fileslson a file returns a single-element list with the filename; on a directory returns sorted children- Attempting to traverse through a file as if it were a directory should raise an error
- Reading a non-existent file should raise an error
Complexity
For a path with d components:
mkdir: O(d)write: O(d + content_length)read: O(d + file_size)lson directory withcchildren: O(d + c log c) due to sorting
Space is O(total nodes + total file content).
Code
from typing import List, Dict
class Node:
def __init__(self):
self.children: Dict[str, Node] = {}
self.is_file = False
self.content_parts: List[str] = []
class FileSystem:
def __init__(self):
self.root = Node()
def _parse_path(self, path: str) -> List[str]:
"""Split path into components, handling edge cases."""
return [part for part in path.split('/') if part]
def _navigate(self, components: List[str], create_missing: bool) -> Node:
"""Walk the tree, optionally creating missing nodes."""
current = self.root
for name in components:
if current.is_file:
raise ValueError(f"Cannot traverse through file: {name}")
if name not in current.children:
if not create_missing:
raise FileNotFoundError(f"Path not found: {name}")
current.children[name] = Node()
current = current.children[name]
return current
def mkdir(self, path: str) -> None:
"""Create directory and any missing parents."""
components = self._parse_path(path)
if not components:
return # root already exists
node = self._navigate(components, create_missing=True)
if node.is_file:
raise ValueError(f"Cannot mkdir: {path} is a file")
def write(self, path: str, content: str) -> None:
"""Write to file, creating it and parents if needed. Appends if file exists."""
components = self._parse_path(path)
if not components:
raise ValueError("Cannot write to root")
# Navigate to parent, creating as needed
parent = self._navigate(components[:-1], create_missing=True)
filename = components[-1]
if filename not in parent.children:
parent.children[filename] = Node()
node = parent.children[filename]
if not node.is_file:
if node.children:
raise ValueError(f"Cannot write: {path} is a directory")
node.is_file = True
node.content_parts.append(content)
def read(self, path: str) -> str:
"""Read file contents."""
components = self._parse_path(path)
node = self._navigate(components, create_missing=False)
if not node.is_file:
raise ValueError(f"Cannot read: {path} is not a file")
return ''.join(node.content_parts)
def ls(self, path: str) -> List[str]:
"""List directory contents or return filename."""
components = self._parse_path(path)
node = self._navigate(components, create_missing=False)
if node.is_file:
return [components[-1]] if components else []
return sorted(node.children.keys())
Extensions to discuss
- Relative paths and
./..: Use a stack while parsing; push component names and pop on.. - Deletion: Add a
deletemethod that recursively removes nodes - Metadata: Track creation time, modification time, size, permissions
- Concurrent access: Discuss lock granularity (per-node vs. global) for thread safety
- Persistence: Serialize the tree to disk; consider delta-based approaches for efficiency
Edge cases to handle
- Operating on the root path
/ - Paths with trailing slashes like
/a/b/ - Multiple consecutive slashes like
//a///b - Calling
mkdiron an existing directory (should be idempotent) - Writing to
/a/b/cwhen/adoesn't exist (should auto-create parents) - Trying to create
/a/bwhen/ais a file (should error)
Interview tips
-
Clarify first: Don't assume the spec. Ask about case sensitivity, punctuation, duplicates, error handling, and expected API contracts.
-
Start simple: Solve for single-word keywords or flat file systems first, then extend to multi-word phrases or nested directories.
-
Test as you go: Walk through examples including edge cases. For the file system, test root operations, nested paths, and appending to files.
-
Discuss trade-offs: Mention alternative approaches (regex with word boundaries, sorted containers for
ls) and their implications for complexity and behavior. -
Time management: Aim to complete a working solution to both parts in 45 minutes, leaving time for testing and discussion.