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?
- A. Sort the string once for each character and compare neighbours, O(n^2 log n)
- B. Build a list of all substrings of s and count each with list.count, O(n^3)
- C. One pass with collections.Counter(s) or a dict update, O(n) total
- 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
- What is printed? python from itertools import accumulate print(list(accumulate([1, 2, 3], initial=0)), next(iter(sorted({3, 1, 2}))))
- What is printed? python st = [] for t in '2 1 + 3 '.split(): if t.isdigit(): st.append(int(t)) else: b = st.pop() a = st.pop() st.append(a…
- What is printed? python a = [-2, 1, -3, 4, -1, 2, 1, -5, 4] best = cur = a[0] for x in a[1:]: cur = max(x, cur + x) best = max(best, cur)…
- What is printed? python print(sum(bin(i).count('1') for i in range(8)))
- What is printed? python seen = {} for i, x in enumerate([2, 7, 11, 15]): if 9 - x in seen: print((seen[9 - x], i)) break seen[x] = i
- What is printed? python print(len(bin(10 6)) - 2, len(bin(2 20)) - 2)