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:

  1. word_count(rdd: SimpleRDD) -> SimpleRDD

    • Given a SimpleRDD of text lines, return a SimpleRDD of (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.
  2. intersect(rdd1: SimpleRDD, rdd2: SimpleRDD) -> SimpleRDD

    • Given two SimpleRDD instances holding hashable elements, return a SimpleRDD containing their multiset (bag) intersection.
    • Whenever an element occurs a times in rdd1 and b times in rdd2, include min(a, b) copies of that element in the output SimpleRDD.
    • Returned elements may appear in any order.

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 SimpleRDD constructed solely via flatMap, groupByKey, and union (never call collect() inside word_count or intersect).
  • Input SimpleRDD objects must remain unmodified.
  • All elements in rdd1 and rdd2 for intersect are hashable Python values (such as integers, strings, tuples, or None).
  • Output element ordering is unconstrained.
  • Inputs can contain up to 10^5 repeated copies of a single element, so per-element linear list scans (O(n * m)) will time out.

Step-by-step walkthrough

  1. 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, and collect—and asked to build word_count(rdd) and intersect(rdd1, rdd2).

    Before writing any code in an interview, state your answers to the open clarifying questions out loud: - Never call collect() inside transformations. Calling collect() pulls an entire distributed dataset onto one machine's memory, which defeats the whole point of an RDD API. Both functions must chain flatMap, groupByKey, and union and return a new SimpleRDD. - Output order does not matter. On a real cluster, groupByKey shuffles 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 in groupByKey is hashable (strings, numbers, tuples, None). - Duplicate rule for intersect: If an item appears a times in rdd1 and b times in rdd2, emit it min(a, b) times.

  2. Express map and filter using flatMap

    Notice that SimpleRDD has no .map() and no .filter(). That is fine because flatMap(func) calls func(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 many
    
    def 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: use flatMap to create (key, value) pairs, call groupByKey(), then use flatMap to turn each (key, [values]) group into the final output.

  3. Build Part 1: word count

    To count words across sentences, we chain three transformations: 1. Tokenize and pair (flatMap): Split each sentence with sentence.split() and emit (word, 1) for every word. 2. Group by word (groupByKey): Collect all 1s for the same word into (word, [1, 1, ...]). 3. Sum each group (flatMap): Turn (word, ones) into a one-element list [(word, sum(ones))]. Using sum(ones) instead of len(ones) also works cleanly if values ever represent partial counts rather than 1s.

    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)
    
  4. 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.

  5. Settle the duplicate rule for Part 2

    In Part 2, rdd1 = [8, 2, 8, 8, 5] and rdd2 = [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 of 8). - Inner-join pairing (matching every left 8 with every right 8) would return 3 × 2 = 6 copies of 8 plus 2.

    Because 8 appears 3 times in rdd1 and 2 times in rdd2, you can pair off at most 2 copies of 8, leaving one unmatched 8 in rdd1. Keeping min(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's Counter(a) & Counter(b) and SQL's INTERSECT ALL, and it is symmetric: intersect(rdd1, rdd2) has the exact same elements as intersect(rdd2, rdd1).

  6. Build Part 2: tag each side before grouping

    To compare counts between rdd1 and rdd2, we need equal items from both RDDs to land in the same groupByKey() bucket. We have union to combine two RDDs—but if we called rdd1.union(rdd2) directly on raw items, [8, 8, 8, 8, 8] from rdd1 and [] from rdd2 would look identical to [8, 8, 8] from rdd1 and [8, 8] from rdd2!

    The fix is to tag each item with which side it came from before calling union: 1. flatMap rdd1 so every item becomes (item, "L"). 2. flatMap rdd2 so every item becomes (item, "R"). 3. union the two tagged RDDs and call groupByKey(). Now each distinct item has a list like ["L", "L", "R"] recording every copy from both sides. 4. flatMap each group to count "L"s and "R"s and return [item] * min(left_count, right_count). When an item appears on only one side, min is 0, so [item] * 0 returns [] 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)
    
  7. Trace Part 2 and analyze skew

    Let's trace Example 2 with rdd1 = [8, 2, 8, 8, 5] and rdd2 = [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 7 appears 100,000,000 times? With n1 and n2 input items and k output 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 key 7. 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.

  8. 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_count time: O(C + W), where C is total characters and W is total words. Splitting every sentence scans C characters once, and each of the W words creates one (word, 1) pair, performs one average O(1) dictionary append inside groupByKey, and gets added once in sum(ones).
  • word_count space: O(C + W). The intermediate RDDs hold W (word, 1) pairs and W integers across all [1, 1, ...] group lists before collapsing to one (word, count) tuple per distinct word.
  • intersect time: O(n1 + n2 + k), where n1 and n2 are the input sizes and k is the output size. We tag n1 + n2 items once, insert each into groupByKey's hash table in average O(1) time, scan the n1 + n2 side tags once, and materialize k output references (k <= min(n1, n2)).
  • intersect space: O(n1 + n2). Both tagged RDDs, their union, and the groupByKey tag lists hold n1 + n2 pairs in memory; if a single hot item appears m times, all m of its tags sit in a single list.

Edge cases

  • Empty RDDs (SimpleRDD([])): Both word_count and intersect cleanly return an empty SimpleRDD ([] when collected), never None or a raw Python list.
  • Blank sentences and irregular whitespace ("", " a\t\nb "): Calling sentence.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: Because item sits in the key slot of (item, "L"), an item like (1, "L") or None never collides with the "L"/"R" tag stored in the value slot.
  • Python hash equivalences (1, 1.0, True): Because Python defines 1 == 1.0 == True with identical hashes, dictionary-backed groupByKey merges them under whichever key appeared first.

Common mistakes

  • Calling collect() inside word_count or intersect: Computes the answer locally on one machine instead of composing RDD transformations, which fails the core interview constraint.
  • Returning a plain Python list instead of a SimpleRDD: Callers chaining .flatMap(...) or .collect() on the return value will crash with AttributeError.
  • Using sentence.split(" ") instead of sentence.split(): Consecutive spaces or empty strings "" generate spurious ("", count) entries.
  • Calling union before tagging sides in intersect: 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_count copies or deduplicating to 1 copy: left * right computes an inner join (6 copies of 8 in Example 2), while deduplicating computes a set intersection (1 copy of 8), both failing [8, 8, 2].

Alternative approaches

  • Pre-count each RDD before intersecting: Apply a word_count-like step to rdd1 and rdd2 separately to get (item, left_count) and (item, right_count), tag them "L" and "R", union, groupByKey, and emit min(left_count, right_count) copies. With only the four SimpleRDD methods, the per-side groupByKey still 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, and union, how can you build distinct(rdd), and how does its output compare to intersect when duplicates exist? Map each item x via flatMap to [(x, None)], call groupByKey() so duplicates collapse into (x, [None, ...]), and flatMap each 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] and distinct(left.union(right)) returns [8, 2, 5, 9], whereas intersect(left, right) returns [8, 8, 2]; composing distinct(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 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? Add reduceByKey(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, groupByKey ships all 1,000 × 1,000,000 = 10^9 (word, 1) pairs across the network, whereas reduceByKey sends 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 existing SimpleRDD operations? Use the exact same side-tagging pattern, keeping the join key as the outer key: flatMap left (k, v) pairs to [(k, ("L", v))] and right (k, w) pairs to [(k, ("R", w))], union them, call groupByKey(), and inside a final flatMap split each key's list into left_vals and right_vals and 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

Similar questions

More Datologyai interview questions

All 3 Datologyai questions →