Data Structures & AlgorithmsModerateTCS NQT · number theory
Problem: How many pairs (i < j) of a = [1, 2, 4, 5, 7, 8] have a[i] - a[j] divisible by 3? Run the code.
Problem: How many pairs (i < j) of a = [1, 2, 4, 5, 7, 8] have a[i] - a[j] divisible by 3? Run the code.
a = [1, 2, 4, 5, 7, 8] print(sum(1 for i in range(len(a)) for j in range(i + 1, len(a)) if (a[i] - a[j]) % 3 == 0))What is printed?
- A. 5
- B. 12
- C. 6
- D. 9
Correct answer: C. 6
Equal residues mod 3 form the groups {1, 4, 7} and {2, 5, 8}, each giving C(3,2) = 3 pairs, for 6. Starting j at i also counts the 6 self-pairs (12), counting the non-divisible pairs gives 9, and assuming one third of the 15 pairs gives 5.
More Coding Interview Problems questions
- Problem: What is the minimum number of meeting rooms needed for intervals [0,30], [5,10], [15,20]? Run the sweep-line code. python iv =…
- Problem: How many inversions (pairs i < j with a[i] > a[j]) does a = [2, 0, 2, 1, 1, 0] have? Run the code. python a = [2, 0, 2, 1, 1, 0]…
- Problem: How many integers x in [1, 50] are perfect sixth powers (x = y^6 for an integer y)? Run the code. python print(sum(1 for x in…
- Problem: Merging ropes of lengths 2, 3, 4 costs the sum of the two lengths merged each time, always merging the two shortest. What is the…
- Problem: How many subsets (including the empty one) of {1, 2, 3, 4, 5} have a sum divisible by 4? Run the code. python print(sum(1 for m…
- Problem: What does the following print? It takes the maximum of every window of size 2 in [4, 2, 12, 11, -5]. python a = [4, 2, 12, 11…