Data Structures & AlgorithmsHardTCS NQT Digital · counting
Problem: How many pairs (i < j) of a = [1, 2, 3, 4, 5, 6, 7] have a[i] + a[j] divisible by 4?
Problem: How many pairs (i < j) of a = [1, 2, 3, 4, 5, 6, 7] have a[i] + a[j] divisible by 4?
a = [1, 2, 3, 4, 5, 6, 7] print(sum(1 for i in range(len(a)) for j in range(i + 1, len(a)) if (a[i] + a[j]) % 4 == 0))What is printed?
- A. 5
- B. 4
- C. 6
- D. 7
Correct answer: A. 5
The qualifying pairs are (1,3), (1,7), (2,6), (3,5) and (5,7), for a total of 5. Counting by residue classes mod 4 gives the same result in O(n).
More Coding Interview Problems questions
- Problem: Count the subarrays of a = [10, 5, 2, 6] whose product is strictly less than k = 100. python def cnt(a, k): if k <= 1: return 0 p…
- Problem: How many distinct subsequences (including the empty one) does 'aba' have? Run the DP below. python def dsub(s): dp = [1] last =…
- Problem: The minimum number of insertions to make 'abcab' a palindrome equals n minus the length of its longest palindromic subsequence…
- Problem: Count pairs (i < j) of a = [1, 2, 3] with a[i] XOR a[j] summed over all pairs. What is the total of the XOR values? Run the code…
- Problem: What is the maximum sum of a path from the top-left to the bottom-right of the grid [[1,3,1],[1,5,1],[4,2,1]] moving only right…
- Problem: How many binary strings of length 5 contain no two consecutive 1s?