Fix the merge step in a parallel word count

Review the AI's codeEasy12 min

Your task

Your Go service counts words across many documents in parallel. The first version had every goroutine write to one shared map. Go maps are not safe for concurrent writes, so it lost counts and sometimes crashed with concurrent map writes. The new version gives each worker, or shard, its own map and merges the maps after all workers finish.

An assistant wrote merge_word_counts(docs, shard_count), which models that split and merge. It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • docs: the documents, as strings.
  • shard_count: how many workers share the documents.
  • Return one word=count string per distinct word, sorted by word.

Rules the tests check:

  • A word is a run of characters whose code points are above 32. Every character with code point 32 or below, such as a space, tab or newline, separates words.
  • Words are case sensitive: Go, go and GO are three words.
  • A word's count is how many times it appears across all documents.
  • The result never depends on shard_count. Any value, including 0 or below, gives the same counts as a single worker.
  • Sort by word as plain strings, by character code, so GO comes before Go and 10 before 2.

Examples

merge_word_counts(docs: list[str], shard_count: int) -> list[str]
Example 1
Inputmerge_word_counts(["go go gopher", "go home"], 2)
Output["go=3", "gopher=1", "home=1"]
Example 2
Inputmerge_word_counts(["go go gopher", "go home"], 1)
Output["go=3", "gopher=1", "home=1"]
Example 3
Inputmerge_word_counts([" a b ", "b\tc"], 4)
Output["a=1", "b=2", "c=1"]