Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern
Problem: Group words that are anagrams of each other and report how many groups there are.
Problem: Group words that are anagrams of each other and report how many groups there are.
from collections import defaultdict
def groups(words):
g = defaultdict(list)
for w in words:
g[''.join(sorted(w))].append(w)
return len(g), max(len(v) for v in g.values())
print(groups(["listen", "silent", "enlist", "google", "gogole", "cat", "act", "tac", "dog"]))What is printed?- A. (3, 3)
- B. (4, 2)
- C. (4, 3)
- D. (5, 3)
Correct answer: C. (4, 3)
Sorted letters form the key: 'eilnst' (3 words), 'eggloo' (2), 'act' (3), 'dgo' (1) – 4 groups, largest size 3. Cost O(N · L log L) for N words of length L; a 26-count tuple key gives O(N · L).
More Coding Interview Problems questions
- Problem: Count the number of contiguous subarrays whose sum equals k. Values can be negative. python def countk(a, k): seen = {0: 1} p =…
- Problem: Count subarrays whose sum is divisible by k (values may be negative). python def divk(a, k): cnt = [0] k cnt[0] = 1 p = ans = 0…
- Problem: For n ≤ 2 × 10⁵ integers in the range −10⁴..10⁴, count subarrays with sum exactly k. Why does a two-pointer sliding window NOT…
- Problem: A game keeps scores in a non-decreasing array. Remove duplicates in place and return the number of unique scores. python def…
- Problem: Allow each value at most twice in a sorted array (in place) and return the new length. python def keep2(a): w = 0 for x in a: if…
- Problem: Two sorted arrays must be merged into the first one, which has spare slots at the end (m real values, n values in the second)…