ProgrammingModerateAmazon OA · Flipkart coding round

Which implementation of "count how many times each character appears in s" is the best choice in Python when len(s) = 2 * 10^5?

  1. A. Sort the string once for each character and compare neighbours, O(n^2 log n)
  2. B. Build a list of all substrings of s and count each with list.count, O(n^3)
  3. C. One pass with collections.Counter(s) or a dict update, O(n) total
  4. D. For every character c in s call s.count(c), O(n^2) total

Correct answer: C. One pass with collections.Counter(s) or a dict update, O(n) total

A single pass with a dict or Counter touches each character once. Calling s.count inside a loop rescans the string for every character, which is quadratic.

More Python Programming questions

Exams that ask this topic