Data Structures & AlgorithmsHardCodeforces Div2 C/D · Amazon SDE OA
Count the unordered pairs (i < j) of the array a = [1, 2, ..., 14] whose sum is divisible by 3. Run the code.
Count the unordered pairs (i < j) of the array a = [1, 2, ..., 14] whose sum is divisible by 3. Run the code.
a=list(range(1,15)) c=[0,0,0] for x in a: c[x%3]+=1 print(c[0]*(c[0]-1)//2+c[1]*c[2])What is printed?
- A. 66
- B. 35
- C. 31
- D. 26
Correct answer: C. 31
Pairs sum to a multiple of 3 when residues are (0,0) or (1,2), so the count is C(c0,2)+c1·c2 = 6+25. Including i = j counts a pair that is not allowed, squaring instead of choosing pairs counts ordered pairs, and pairing within each residue class ignores the cross pairs.
More Coding Interview Problems questions
- Consider the permutation p = [4, 1, 7, 3, 8, 2, 6, 5]. Count its inversions, i.e. pairs of positions i < j with p[i] > p[j]. Run the code…
- Problem: A connected undirected graph has 7 vertices. Its BFS tree from vertex 0 has depths: vertex 0 at depth 0, vertices 1 and 2 at…
- Problem: A graph's vertices 0–4 are connected by edges 0-1 (1), 1-2 (1), 2-3 (1), 3-4 (1), 0-4 (5), 1-3 (3). What is the largest…
- Problem: In a directed graph on vertices 0–3, the arcs are 0→1, 1→2, 2→0, 2→3. The vertex 3 has no outgoing arcs. How many vertices can…
- Problem: A rooted tree has root 1 and children 1: [2, 3, 4], 3: [5], 4: [6, 7]. The number of nodes on the longest root-to-leaf path…
- Problem: The string "abcdcba" is checked for palindromic substrings with an odd length of at least 5. How many such substrings are there?