Data Structures & AlgorithmsHardCodeforces Div2 C · two pointers
Problem: Count the pairs (i < j) with a[i] + a[j] < 6 for the array [5, 1, 4, 2, 3].
Problem: Count the pairs (i < j) with a[i] + a[j] < 6 for the array [5, 1, 4, 2, 3].
def count(a, T):
a = sorted(a)
i, j = 0, len(a) - 1
ans = 0
while i < j:
if a[i] + a[j] < T:
ans += j - i
i += 1
else:
j -= 1
return ans
print(count([5, 1, 4, 2, 3], 6))What is printed?- A. 3
- B. 5
- C. 6
- D. 4
Correct answer: D. 4
After sorting, the two-pointer scan counts (1,2), (1,3), (1,4) and (2,3), giving 4. The pair (2,4) sums to exactly 6 and must not be counted.
More Coding Interview Problems questions
- Problem: Mo's algorithm answers q range queries on an array of length n by sorting queries into blocks of size about sqrt(n) and moving…
- Problem: In a segment tree with lazy propagation, what is the cost of one range-add update on an array of length n?
- Problem: What does the following print? python print(-7 // 2, -7 % 2, 7 // -2, int(-7 / 2))
- Problem: What does the following print? python print(bin(12 & -12), 12 & -12)
- Problem: Coins of values {1, 3, 4} are available, unlimited copies each. To make amount 6, the greedy algorithm always takes the largest…
- Problem: What does the following print? python def ed(a, b): m, n = len(a), len(b) dp = [[0] (n + 1) for in range(m + 1)] for i in range(m…