Word Frequencies and Bag Intersection on a Minimal RDD
Easy · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Consider SimpleRDD, an in-memory toy model of a distributed dataset interface that exposes only four operations: flatMap, groupByKey, union, and collect.
from collections import defaultdict
class SimpleRDD:
def __init__(self, items):
self.items = items
def flatMap(self, func):
"""Run func on every element and concatenate the resulting sequences."""
new_items = []
for item in self.items:
new_items.extend(func(item))
return SimpleRDD(new_items)
def groupByKey(self):
"""Aggregate (key, value) tuples into (key, [values]) tuples."""
grouped = defaultdict(list)
for key, value in self.items:
grouped[key].append(value)
return SimpleRDD(list(grouped.items()))
def union(self, other_rdd):
"""Concatenate self and other_rdd into a fresh SimpleRDD."""
return SimpleRDD(self.items + other_rdd.items)
def collect(self):
"""Materialize a shallow Python list of all elements."""
return list(self.items)
Notice that convenience primitives such as map, filter, reduceByKey, and distinct are absent. Without calling collect() inside your implementations or mutating any input SimpleRDD, build two functions purely by composing flatMap, groupByKey, and union:
-
word_count(rdd: SimpleRDD) -> SimpleRDD- Given a
SimpleRDDof text lines, return aSimpleRDDof(token, frequency)tuples counting how often each token occurs across the entire dataset. - Tokenize each line on runs of whitespace (
str.split()), keeping letter case and attached punctuation untouched (so"Log","log", and"log:"count separately, and blank or whitespace-only lines yield zero tokens). - Returned
(token, frequency)tuples may appear in any order.
- Given a
-
intersect(rdd1: SimpleRDD, rdd2: SimpleRDD) -> SimpleRDD- Given two
SimpleRDDinstances holding hashable elements, return aSimpleRDDcontaining their multiset (bag) intersection. - Whenever an element occurs
atimes inrdd1andbtimes inrdd2, includemin(a, b)copies of that element in the outputSimpleRDD. - Returned elements may appear in any order.
- Given two
Examples
Example 1
lines = SimpleRDD([
"red blue red",
"blue green",
""
])
counts = word_count(lines)
counts.collect() # [("red", 2), ("blue", 2), ("green", 1)] (any order)
Explanation: Splitting on whitespace extracts "red", "blue", "red" from the first string, "blue" and "green" from the second string (ignoring consecutive spaces), and zero tokens from the empty string. Summing frequencies per distinct token gives 2 for "red", 2 for "blue", and 1 for "green".
Example 2
left = SimpleRDD([8, 2, 8, 8, 5])
right = SimpleRDD([2, 8, 9, 8])
shared = intersect(left, right)
shared.collect() # [8, 8, 2] (any order)
Explanation: 8 occurs three times in left and twice in right, so min(3, 2) = 2 copies of 8 remain. 2 occurs once on each side (min(1, 1) = 1), while 5 and 9 are missing from one input (min(1, 0) = 0 and min(0, 1) = 0) and are dropped.
Constraints
- Both functions must return a
SimpleRDDconstructed solely viaflatMap,groupByKey, andunion(never callcollect()insideword_countorintersect). - Input
SimpleRDDobjects must remain unmodified. - All elements in
rdd1andrdd2forintersectare hashable Python values (such as integers, strings, tuples, orNone). - Output element ordering is unconstrained.
- Inputs can contain up to
10^5repeated copies of a single element, so per-element linear list scans (O(n * m)) will time out.
Step-by-step walkthrough
Clarify the rules before writing code
An RDD (Resilient Distributed Dataset) is Apache Spark's abstraction for a read-only collection of items split across many machines, where you transform data step by step instead of mutating lists in place. Here we are given
SimpleRDD, a tiny single-machine version with just four methods—flatMap,groupByKey,union, andcollect—and asked to buildword_count(rdd)andintersect(rdd1, rdd2).Before writing any code in an interview, state your answers to the open clarifying questions out loud: - Never call
collect()inside transformations. Callingcollect()pulls an entire distributed dataset onto one machine's memory, which defeats the whole point of an RDD API. Both functions must chainflatMap,groupByKey, andunionand return a newSimpleRDD. - Output order does not matter. On a real cluster,groupByKeyshuffles keys across machines with no order guarantee. - Word splitting: Split on runs of whitespace (sentence.split()) and keep case and punctuation as-is ("Log","log", and"log:"are three distinct tokens). - Hashable items: Every word or item used as a key ingroupByKeyis hashable (strings, numbers, tuples,None). - Duplicate rule forintersect: If an item appearsatimes inrdd1andbtimes inrdd2, emit itmin(a, b)times.Express map and filter using flatMap
Notice that
SimpleRDDhas no.map()and no.filter(). That is fine becauseflatMap(func)callsfunc(item)on each element and splices the returned list into the output—so the length of the list you return controls what operation happens:Input item x ---> func(x) returns... ---> Effect in flatMap ---------------------------------------------------------------------- x ---> [f(x)] (1 element) ---> acts like map(f) x ---> [x] or [] (1 or 0) ---> acts like filter(pred) x ---> [y1, y2, y3] (0..k) ---> expands 1 item into manydef map_with_flatmap(rdd, f): def wrap_one(x): return [f(x)] return rdd.flatMap(wrap_one) def filter_with_flatmap(rdd, keep): def keep_or_drop(x): if keep(x): return [x] return [] return rdd.flatMap(keep_or_drop)Meanwhile,
groupByKey()is the only method that brings equal items together, and it expects(key, value)pairs. That gives both parts the same rhythm: useflatMapto create(key, value)pairs, callgroupByKey(), then useflatMapto turn each(key, [values])group into the final output.Build Part 1: word count
To count words across sentences, we chain three transformations: 1. Tokenize and pair (
flatMap): Split each sentence withsentence.split()and emit(word, 1)for every word. 2. Group by word (groupByKey): Collect all1s for the same word into(word, [1, 1, ...]). 3. Sum each group (flatMap): Turn(word, ones)into a one-element list[(word, sum(ones))]. Usingsum(ones)instead oflen(ones)also works cleanly if values ever represent partial counts rather than1s.def _words_to_pairs(sentence): """Split one sentence on whitespace into (word, 1) pairs.""" pairs = [] for word in sentence.split(): pairs.append((word, 1)) return pairs def _sum_group(group): """Convert one grouped item (word, [1, 1, ...]) into [(word, total_count)].""" word, ones = group return [(word, sum(ones))] def word_count(rdd): """Return a SimpleRDD of (word, count) pairs for the sentences in rdd.""" word_one_pairs = rdd.flatMap(_words_to_pairs) grouped_words = word_one_pairs.groupByKey() return grouped_words.flatMap(_sum_group)Trace Part 1 on Example 1
Let's watch
["red blue red", "blue green", ""]flow through all three stages:Input lines: ["red blue red", "blue green", ""] Stage 1 — rdd.flatMap(_words_to_pairs): [("red", 1), ("blue", 1), ("red", 1), ("blue", 1), ("green", 1)] Stage 2 — .groupByKey(): [("red", [1, 1]), ("blue", [1, 1]), ("green", [1])] Stage 3 — .flatMap(_sum_group): [("red", 2), ("blue", 2), ("green", 1)]Notice what happens on tricky whitespace:
"".split()and" \t\n".split()both return[], so blank lines contribute zero pairs, and"blue green".split()returns["blue", "green"]without empty-string tokens.Settle the duplicate rule for Part 2
In Part 2,
rdd1 = [8, 2, 8, 8, 5]andrdd2 = [2, 8, 9, 8]must produce[8, 8, 2]. That immediately rules out two common interpretations: - Plain set intersection (deduplicating) would return[8, 2](only one copy of8). - Inner-join pairing (matching every left8with every right8) would return 3 × 2 = 6 copies of8plus2.Because
8appears 3 times inrdd1and 2 times inrdd2, you can pair off at most 2 copies of8, leaving one unmatched8inrdd1. Keepingmin(a, b)copies is called multiset intersection (a multiset, or bag, is a set that tracks how many copies of each element exist). It matches Python'sCounter(a) & Counter(b)and SQL'sINTERSECT ALL, and it is symmetric:intersect(rdd1, rdd2)has the exact same elements asintersect(rdd2, rdd1).Build Part 2: tag each side before grouping
To compare counts between
rdd1andrdd2, we need equal items from both RDDs to land in the samegroupByKey()bucket. We haveunionto combine two RDDs—but if we calledrdd1.union(rdd2)directly on raw items,[8, 8, 8, 8, 8]fromrdd1and[]fromrdd2would look identical to[8, 8, 8]fromrdd1and[8, 8]fromrdd2!The fix is to tag each item with which side it came from before calling
union: 1.flatMaprdd1so everyitembecomes(item, "L"). 2.flatMaprdd2so everyitembecomes(item, "R"). 3.unionthe two tagged RDDs and callgroupByKey(). Now each distinctitemhas a list like["L", "L", "R"]recording every copy from both sides. 4.flatMapeach group to count"L"s and"R"s and return[item] * min(left_count, right_count). When an item appears on only one side,minis0, so[item] * 0returns[]and drops it automatically!LEFT_SIDE = "L" RIGHT_SIDE = "R" def _tag_left(item): """Wrap one item from rdd1 as a (key=item, value='L') pair.""" return [(item, LEFT_SIDE)] def _tag_right(item): """Wrap one item from rdd2 as a (key=item, value='R') pair.""" return [(item, RIGHT_SIDE)] def _emit_common_copies(group): """Emit min(left_count, right_count) copies of item from (item, ['L', 'R', ...]).""" item, side_tags = group left_count = 0 right_count = 0 for tag in side_tags: if tag == LEFT_SIDE: left_count += 1 else: right_count += 1 common_count = min(left_count, right_count) return [item] * common_count def intersect(rdd1, rdd2): """Return a SimpleRDD of shared items, keeping min(count in rdd1, count in rdd2) copies.""" tagged_left = rdd1.flatMap(_tag_left) tagged_right = rdd2.flatMap(_tag_right) grouped_by_item = tagged_left.union(tagged_right).groupByKey() return grouped_by_item.flatMap(_emit_common_copies)Trace Part 2 and analyze skew
Let's trace Example 2 with
rdd1 = [8, 2, 8, 8, 5]andrdd2 = [2, 8, 9, 8]:tagged_left : [(8, "L"), (2, "L"), (8, "L"), (8, "L"), (5, "L")] tagged_right : [(2, "R"), (8, "R"), (9, "R"), (8, "R")] union : [(8, "L"), (2, "L"), (8, "L"), (8, "L"), (5, "L"), (2, "R"), (8, "R"), (9, "R"), (8, "R")] groupByKey : [(8, ["L", "L", "L", "R", "R"]), (2, ["L", "R"]), (5, ["L"]), (9, ["R"])] _emit_common_copies per group: item 8 -> left=3, right=2 -> min(3, 2) = 2 -> [8, 8] item 2 -> left=1, right=1 -> min(1, 1) = 1 -> [2] item 5 -> left=1, right=0 -> min(1, 0) = 0 -> [] item 9 -> left=0, right=1 -> min(0, 1) = 0 -> [] Final SimpleRDD : [8, 8, 2]What if a single hot value like
7appears 100,000,000 times? Withn1andn2input items andkoutput items, time is linear—O(n1 + n2 + k)—because each item is tagged, grouped in a hash table, and counted once. However,groupByKey()builds one in-memory list of 100,000,000"L"/"R"tags for key7. On a real cluster, all values for a single key go to a single worker machine—a bottleneck called data skew that can exhaust one worker's memory while other workers sit idle. Pre-aggregating counts per partition before shuffling (discussed in the follow-ups) shrinks that list to one integer count per partition.Complete solution
from typing import Any, List, Tuple from collections import defaultdict class SimpleRDD: def __init__(self, items: List[Any]) -> None: self.items = items def flatMap(self, func): """Run func on every element and concatenate the resulting sequences.""" new_items = [] for item in self.items: new_items.extend(func(item)) return SimpleRDD(new_items) def groupByKey(self): """Aggregate (key, value) tuples into (key, [values]) tuples.""" grouped = defaultdict(list) for key, value in self.items: grouped[key].append(value) return SimpleRDD(list(grouped.items())) def union(self, other_rdd): """Concatenate self and other_rdd into a fresh SimpleRDD.""" return SimpleRDD(self.items + other_rdd.items) def collect(self): """Materialize a shallow Python list of all elements.""" return list(self.items) # ---------- Part 1: word count ---------- def _words_to_pairs(sentence: str) -> List[Tuple[str, int]]: """Split one sentence on whitespace into (word, 1) pairs.""" # str.split() with no argument splits on any run of whitespace and drops empty strings. pairs: List[Tuple[str, int]] = [] for word in sentence.split(): pairs.append((word, 1)) return pairs def _sum_group(group: Tuple[str, List[int]]) -> List[Tuple[str, int]]: """Convert one grouped item (word, [1, 1, ...]) into [(word, total_count)].""" # Returning a 1-element list lets flatMap act like a missing .map() method. word, ones = group return [(word, sum(ones))] def word_count(rdd: SimpleRDD) -> SimpleRDD: """Return a SimpleRDD of (word, count) pairs for the sentences in rdd.""" # Stage 1: sentences -> SimpleRDD of (word, 1) pairs. word_one_pairs = rdd.flatMap(_words_to_pairs) # Stage 2: group equal words -> SimpleRDD of (word, [1, 1, ...]). grouped_words = word_one_pairs.groupByKey() # Stage 3: sum each word's list -> SimpleRDD of (word, total_count). return grouped_words.flatMap(_sum_group) # ---------- Part 2: multiset intersect ---------- LEFT_SIDE = "L" RIGHT_SIDE = "R" def _tag_left(item: Any) -> List[Tuple[Any, str]]: """Wrap one item from rdd1 as a (key=item, value='L') pair.""" return [(item, LEFT_SIDE)] def _tag_right(item: Any) -> List[Tuple[Any, str]]: """Wrap one item from rdd2 as a (key=item, value='R') pair.""" return [(item, RIGHT_SIDE)] def _emit_common_copies(group: Tuple[Any, List[str]]) -> List[Any]: """Emit min(left_count, right_count) copies of item from (item, ['L', 'R', ...]).""" item, side_tags = group left_count = 0 right_count = 0 for tag in side_tags: if tag == LEFT_SIDE: left_count += 1 else: right_count += 1 # Multiset intersection keeps min(copies in rdd1, copies in rdd2). # When an item appears on only one side, common_count is 0 and [] drops it (like filter). common_count = min(left_count, right_count) return [item] * common_count def intersect(rdd1: SimpleRDD, rdd2: SimpleRDD) -> SimpleRDD: """Return a SimpleRDD of shared items, keeping min(count in rdd1, count in rdd2) copies.""" # Tag items BEFORE union so we still know how many copies came from each input RDD. tagged_left = rdd1.flatMap(_tag_left) tagged_right = rdd2.flatMap(_tag_right) # Merge both tagged streams and group equal items -> SimpleRDD of (item, ['L', 'R', ...]). grouped_by_item = tagged_left.union(tagged_right).groupByKey() # Emit min(left_count, right_count) copies of each item. return grouped_by_item.flatMap(_emit_common_copies)✅ Submit now — all tests should pass.
Intuition & how it works
Imagine working in a mailroom that has only three conveyor-belt machines: a repackager (flatMap) that opens each envelope and drops zero, one, or several new envelopes onto the belt; a merger (union) that pours two belts onto one; and a pigeonhole sorter (groupByKey) that stacks (label, slip) envelopes with the same label into one bin. Even though there is no dedicated map or filter button, flatMap can imitate both—returning a 1-item list [y] transforms 1 item into 1 item (map), and returning [] throws an item away (filter). And when we need to compare two separate collections in intersect, sticking an "L" or "R" note onto each item before pouring the belts together lets the pigeonhole sorter count how many copies came from each side.
The obvious shortcut—calling collect() and counting in a plain Python Counter—fails the design goal because in a real distributed RDD (Resilient Distributed Dataset, a collection split across many machines), collect() drags the entire dataset onto one machine's memory and crashes it. Meanwhile, calling rdd1.union(rdd2) without "L"/"R" tags loses track of where items came from (five 8s from [8, 8, 8, 8, 8] and [] look identical to three 8s on the left and two 8s on the right), and matching items by scanning a list takes slow O(n1 × n2) time when a value repeats thousands of times.
Walk through both pipelines on the statement's examples:
- Word count on ["red blue red", "blue green", ""]: flatMap splits lines into [("red", 1), ("blue", 1), ("red", 1), ("blue", 1), ("green", 1)] → groupByKey stacks matching keys into [("red", [1, 1]), ("blue", [1, 1]), ("green", [1])] → a second flatMap sums each list into [("red", 2), ("blue", 2), ("green", 1)].
- Multiset intersect (keeping duplicate counts with min) on [8, 2, 8, 8, 5] and [2, 8, 9, 8]: tag left as [(8, "L"), (2, "L"), (8, "L"), (8, "L"), (5, "L")] and right as [(2, "R"), (8, "R"), (9, "R"), (8, "R")] → union and groupByKey produce [(8, ["L", "L", "L", "R", "R"]), (2, ["L", "R"]), (5, ["L"]), (9, ["R"])] → flatMap emits min(left, right) copies per key, dropping 5 (min(1, 0) = 0) and 9 (min(0, 1) = 0) and outputting [8, 8, 2].
Complexity
word_counttime: O(C + W), whereCis total characters andWis total words. Splitting every sentence scansCcharacters once, and each of theWwords creates one(word, 1)pair, performs one average O(1) dictionary append insidegroupByKey, and gets added once insum(ones).word_countspace: O(C + W). The intermediate RDDs holdW(word, 1)pairs andWintegers across all[1, 1, ...]group lists before collapsing to one(word, count)tuple per distinct word.intersecttime: O(n1 + n2 + k), wheren1andn2are the input sizes andkis the output size. We tagn1 + n2items once, insert each intogroupByKey's hash table in average O(1) time, scan then1 + n2side tags once, and materializekoutput references (k <= min(n1, n2)).intersectspace: O(n1 + n2). Both tagged RDDs, their union, and thegroupByKeytag lists holdn1 + n2pairs in memory; if a single hot item appearsmtimes, allmof its tags sit in a single list.
Edge cases
- Empty RDDs (
SimpleRDD([])): Bothword_countandintersectcleanly return an emptySimpleRDD([]when collected), neverNoneor a raw Pythonlist. - Blank sentences and irregular whitespace (
""," a\t\nb "): Callingsentence.split()with no separator argument treats any run of spaces, tabs, or newlines as a single delimiter and produces[]on blank strings, preventing""phantom words. - Case and punctuation (
"Log","log","log:"): Treated as distinct words under whitespace splitting; lowercasing or punctuation stripping should only be added if confirmed with the interviewer. - Unequal duplicate counts (
[5, 5, 5, 5]vs[5, 6]):min(4, 1)emits[5], never 4 copies and never 4 × 1 pairs. - Items that are themselves tuples or
None: Becauseitemsits in thekeyslot of(item, "L"), an item like(1, "L")orNonenever collides with the"L"/"R"tag stored in thevalueslot. - Python hash equivalences (
1,1.0,True): Because Python defines1 == 1.0 == Truewith identical hashes, dictionary-backedgroupByKeymerges them under whichever key appeared first.
Common mistakes
- Calling
collect()insideword_countorintersect: Computes the answer locally on one machine instead of composing RDD transformations, which fails the core interview constraint. - Returning a plain Python
listinstead of aSimpleRDD: Callers chaining.flatMap(...)or.collect()on the return value will crash withAttributeError. - Using
sentence.split(" ")instead ofsentence.split(): Consecutive spaces or empty strings""generate spurious("", count)entries. - Calling
unionbefore tagging sides inintersect: Once untagged items are merged, there is no way to distinguish 2 copies on each side from 4 copies on one side and 0 on the other. - Emitting
left_count * right_countcopies or deduplicating to 1 copy:left * rightcomputes an inner join (6copies of8in Example 2), while deduplicating computes a set intersection (1copy of8), both failing[8, 8, 2].
Alternative approaches
- Pre-count each RDD before intersecting: Apply a
word_count-like step tordd1andrdd2separately to get(item, left_count)and(item, right_count), tag them"L"and"R",union,groupByKey, and emitmin(left_count, right_count)copies. With only the fourSimpleRDDmethods, the per-sidegroupByKeystill materializes every copy first, so total local work is similar—but once map-side combining exists (see follow-up 2), pre-counting dramatically cuts network traffic. - Return
(item, count)pairs instead of expanded copies: When a single item can repeat 10^9 times in both inputs, returning compressed(item, min(a, b))pairs avoids allocating a 10^9-element output RDD.
Follow-up questions
- Using solely
flatMap,groupByKey, andunion, how can you builddistinct(rdd), and how does its output compare tointersectwhen duplicates exist? Map each itemxviaflatMapto[(x, None)], callgroupByKey()so duplicates collapse into(x, [None, ...]), andflatMapeach group back to[x]. On Example 2's inputs[8, 2, 8, 8, 5]and[2, 8, 9, 8],distinct(left)returns[8, 2, 5]anddistinct(left.union(right))returns[8, 2, 5, 9], whereasintersect(left, right)returns[8, 8, 2]; composingdistinct(intersect(left, right))yields[8, 2], which is standard duplicate-free set intersection.
```python def _pair_with_dummy(item): return [(item, None)]
def _keep_key(group): key, _ = group return [key]
def distinct(rdd): return rdd.flatMap(_pair_with_dummy).groupByKey().flatMap(_keep_key) ```
- Because
groupByKeytransfers every raw pair over the network in a distributed setting, which single primitive would you add toSimpleRDDto cut shuffle traffic during word counting? AddreduceByKey(func), which runs a combiner—a local pre-aggregation inside each partition—before performing the shuffle (the network step that sends equal keys to the same worker). For example, if 1,000 partitions each hold 1,000,000 words drawn from a 50,000-word vocabulary,groupByKeyships all 1,000 × 1,000,000 = 10^9(word, 1)pairs across the network, whereasreduceByKeysends at most one partial count per distinct word per partition: at most 1,000 × 50,000 = 5 × 10^7 pairs (at least 20× less network traffic and no giant[1, 1, ...]lists in memory).
python
def reduceByKey(self, func):
totals = {}
for key, value in self.items:
if key in totals:
totals[key] = func(totals[key], value)
else:
totals[key] = value
return SimpleRDD(list(totals.items()))
- How can you express an inner join between two
(key, value)RDDs using only the existingSimpleRDDoperations? Use the exact same side-tagging pattern, keeping the joinkeyas the outer key:flatMapleft(k, v)pairs to[(k, ("L", v))]and right(k, w)pairs to[(k, ("R", w))],unionthem, callgroupByKey(), and inside a finalflatMapsplit each key's list intoleft_valsandright_valsand emit(k, (v, w))for every(v, w)pair. If a single hot key has 10,000 left rows and 10,000 right rows, that Cartesian product emits 10^8 pairs on one worker (data skew, where one machine gets an oversized share of the work); production engines mitigate this with a broadcast join—copying the smaller dataset to every worker so the larger dataset never shuffles—or by salting hot keys across multiple sub-keys.
Follow-up questions
- Using solely `flatMap`, `groupByKey`, and `union`, how can you build `distinct(rdd)`, and how does its output compare to `intersect` when duplicates exist?
- Because `groupByKey` transfers every raw pair over the network in a distributed setting, which single primitive would you add to `SimpleRDD` to cut shuffle traffic during word counting?
- How can you express an inner join between two `(key, value)` RDDs using only the existing `SimpleRDD` operations?
Similar questions
- Multi-Line Buffer Editor with Four-Directional Cursor Navigation
- Stateful Document Cursor with Typing, Deletion, and 2D Movement
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging