Data Structures & AlgorithmsModerateCodeforces Div2 B · bit operations
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: 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.
a = [1, 2, 3] print(sum(a[i] ^ a[j] for i in range(len(a)) for j in range(i + 1, len(a))))What is printed?
- A. 6
- B. 12
- C. 9
- D. 3
Correct answer: A. 6
The pairs give 1 XOR 2 = 3, 1 XOR 3 = 2 and 2 XOR 3 = 1, which sum to 6. Adding the pair sums instead gives 12, using OR (every pair gives 3) gives 9, and using AND gives 0 + 1 + 2 = 3.
More Coding Interview Problems questions
- 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?
- Problem: What is the maximum product of a non-empty contiguous subarray of [2, 3, -2, 4, -1]? Use the code below. python a = [2, 3, -2, 4…
- Problem: How many islands (4-connected groups of '1') are in the grid below? Run the DFS code. python g = ['11000', '11000', '00100'…
- Problem: How many subarrays of [1, -1, 2, -2, 3, -3] have sum zero? Run the prefix-count code. python from collections import Counter a =…
- Problem: A data stream needs the median of the last k elements. Which structure supports each slide in O(log k) time?