Two-Part Challenge: Token Frequencies and Multiset Overlap with a Barebones RDD
Data Structure DesignModel answerLast updated
Using only flatMap, groupByKey, union, and collect on a minimal RDD class, implement word counting and a duplicate-preserving intersection of two datasets.
You have access to a stripped-down RDD-like class that deliberately omits most of the usual operations. The only methods available are flatMap, groupByKey, union, and collect.
from collections import defaultdict
class RDDLite:
def __init__(self, data):
self.data = data
def flatMap(self, fn):
"""Apply fn to every element, concatenate all returned iterables, return new RDDLite."""
out = []
for x in self.data:
out.extend(fn(x))
return RDDLite(out)
def groupByKey(self):
"""Assume elements are (key, value) pairs. Return RDDLite of (key, [values])."""
buckets = defaultdict(list)
for k, v in self.data:
buckets[k].append(v)
return RDDLite(list(buckets.items()))
def union(self, other):
"""Return a new RDDLite containing all elements from both RDDs."""
return RDDLite(self.data + other.data)
def collect(self):
"""Return a plain Python list of all elements."""
return list(self.data)
There is no map, filter, reduceByKey, or distinct. Your solutions should work by composing the four available operations rather than by calling collect() up front and processing the raw list in Python.
Part 1 — Token frequency table
Write word_count(rdd) that accepts an RDD of text strings and returns an RDD of (word, count) pairs. Tokenize on whitespace only; treat case as-is.
lines = RDDLite(["the cat sat", "the dog ran", "the cat ran"])
word_count(lines).collect()
# [('the', 3), ('cat', 2), ('sat', 1), ('dog', 1), ('ran', 2)]
Points to address:
- How you emulate
mapwithflatMap - How you turn a grouped value list into a numeric count
- The time and memory cost of the approach, especially compared to
reduceByKey
Part 2 — Multiset intersection
Write intersect(rdd_a, rdd_b) that returns an RDD of every element shared by both inputs. If a value appears c_a times in the first RDD and c_b times in the second, it should appear min(c_a, c_b) times in the output.
a = RDDLite([2, 2, 2, 5])
b = RDDLite([2, 2, 7])
intersect(a, b).collect()
# [2, 2]
Points to address:
- Stating the multiplicity rule before writing any code
- How to track which source each element came from using the available operations
- What happens to elements that exist on only one side
- Memory cost when a single value is extremely frequent
Hints
Hint 1
flatMap can stand in for map by always returning a one-element list, and for filter by returning an empty list — you don't need any missing method.
Hint 2
After groupByKey gives you (word, [1, 1, 1, ...]), the count is just len() of the values list, and another flatMap can replace that list with a single (word, count) pair.
Hint 3
Before calling union, tag every element in rdd_a as (element, 'a') and every element in rdd_b as (element, 'b') — then groupByKey separates the two sides naturally and you can compute min(count_a, count_b) per element.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Part 1 — Token frequency table
The core substitution. flatMap expects a function that returns a list. Returning [y] is identical to map(x -> y). Returning [] is identical to filtering the element out. That means flatMap covers all three missing operations.
The pipeline has three steps:
- Split each string on whitespace and emit a
(word, 1)pair for every token. - Call
groupByKeyto collect all the 1s for each word. - Replace each value list with its length using another
flatMap.
def word_count(rdd):
# Step 1: tokenize and create (word, sentinel) pairs
pairs = rdd.flatMap(lambda line: [(w, 1) for w in line.split()])
# Step 2: gather all sentinels under the same word
grouped = pairs.groupByKey()
# Step 3: swap the sentinel list for its length
return grouped.flatMap(lambda kv: [(kv[0], len(kv[1]))])
Checking against the example: "the cat sat", "the dog ran", "the cat ran" → after step 1 you have nine (word, 1) pairs. After step 2, the maps to [1,1,1], cat to [1,1], and so on. After step 3 the lengths replace the lists.
Complexity. Let n be the total token count. Steps 1 and 3 are each O(n). Step 2 is O(n) for the pass but materializes every sentinel in memory — peak memory is O(n) because groupByKey stores all n values before you can compute a single count. A real Spark job would use reduceByKey to fold counts locally before the shuffle, reducing memory to O(unique words). That option isn't available here.
Order. Python 3.7+ preserves insertion order in dicts, so groupByKey returns words in first-appearance order, which matches the expected output.
Part 2 — Multiset intersection
Multiplicity rule, stated first. If a value appears c_a times in rdd_a and c_b times in rdd_b, include min(c_a, c_b) copies in the result. Elements on only one side contribute 0 copies and are absent from the output.
Strategy. groupByKey groups elements by a key. The challenge is distinguishing which side each occurrence came from after combining both RDDs. The solution is to tag every element before the union so the tags land in the same group.
- Tag each element in
rdd_aas(element, 'a')and each inrdd_bas(element, 'b'). - Union the two tagged RDDs.
groupByKeyproduces(element, ['a', 'a', ..., 'b', 'b', ...]).- Count the
'a'and'b'tags, take the minimum, and emit that many copies.
def intersect(rdd_a, rdd_b):
# Step 1: tag by source
tagged_a = rdd_a.flatMap(lambda x: [(x, 'a')])
tagged_b = rdd_b.flatMap(lambda x: [(x, 'b')])
# Step 2: combine into one RDD
combined = tagged_a.union(tagged_b)
# Step 3: group tags by element value
grouped = combined.groupByKey()
# Step 4: emit min(count_a, count_b) copies of each element
def emit(kv):
element, tags = kv
count_a = tags.count('a')
count_b = tags.count('b')
return [element] * min(count_a, count_b)
return grouped.flatMap(emit)
Walking through the example: rdd_a = [2, 2, 2, 5], rdd_b = [2, 2, 7]. After tagging and unioning, groupByKey produces three groups: 2 → ['a','a','a','b','b'], 5 → ['a'], 7 → ['b']. For 2: min(3, 2) = 2, emit two copies. For 5 and 7: one side has count 0, so nothing is emitted. Result: [2, 2].
Complexity. Tagging and unioning is O(n + m). groupByKey materializes every tag string, so memory is O(n + m). The final flatMap does a linear scan of each group's tag list to count occurrences — list.count() is O(len(tags)), and summed across all groups this is another O(n + m). If one value appears millions of times, its group holds millions of single-character strings, which is expensive. A better approach (if you could use reduceByKey) would be to aggregate counts per side before grouping, capping memory at O(unique values).
Common mistakes to avoid
- Calling
collect()at the start and processing a plain list in Python — this technically works but bypasses the abstraction and won't scale in a real distributed setting. - Returning a bare value from the
flatMapcallback instead of a list, which causesextendto iterate over characters in a string or digits in a number. - Applying set semantics and deduplicating before counting, which breaks the
minrule. - Forgetting to handle elements that exist on only one side — the
min(count_a, count_b)naturally evaluates to 0 when one count is 0, but only if both counts are actually computed rather than skipped.