Data Structures & AlgorithmsHardAmazon · Microsoft OA

Edge case: itertools.groupby on unsorted data.

Edge case: itertools.groupby on unsorted data.
from itertools import groupby
data = "aabbbaacc"
print([(k, len(list(g))) for k, g in groupby(data)], len(list(groupby(sorted(data)))))
What is printed?
  1. A. [('a', 2), ('b', 3), ('a', 2), ('c', 2)] 3
  2. B. [('a', 4), ('b', 3), ('c', 2)] 3
  3. C. [('a', 2), ('b', 3), ('a', 2), ('c', 2)] 4
  4. D. [('a', 4), ('b', 3), ('c', 2)] 4

Correct answer: A. [('a', 2), ('b', 3), ('a', 2), ('c', 2)] 3

groupby groups only CONSECUTIVE equal items, so 'a' appears as two separate groups. Sorting first (or using Counter) gives one group per distinct value: 3.

More Coding Interview Problems questions

Exams that ask this topic