Skip to content

Commit 3b55cda

Browse files
committed
Add Python solution for Codeforces 1538C (Number of Pairs)
- Implemented binary search approach for pair counting - Time complexity: O(n log n) - Space complexity: O(n) - Handles constraints up to n=2×10^5
1 parent b12b606 commit 3b55cda

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

  • Problems/Binary-Search/Day-07/sol/Ishan_Raj_Singh
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
"""
2+
Approach: Two Pointers approach
3+
Submission Link: https://codeforces.com/problemset/submission/1538/356144559
4+
"""
5+
6+
def solve_two_pointers():
7+
n, l, r = map(int, input().split())
8+
a = list(map(int, input().split()))
9+
10+
a.sort()
11+
count = 0
12+
13+
for i in range(n):
14+
min_sum = l - a[i]
15+
max_sum = r - a[i]
16+
17+
left = i + 1
18+
right = n - 1
19+
20+
lo, hi = i + 1, n
21+
while lo < hi:
22+
mid = (lo + hi) // 2
23+
if a[mid] < min_sum:
24+
lo = mid + 1
25+
else:
26+
hi = mid
27+
left_bound = lo
28+
29+
lo, hi = i + 1, n
30+
while lo < hi:
31+
mid = (lo + hi) // 2
32+
if a[mid] <= max_sum:
33+
lo = mid + 1
34+
else:
35+
hi = mid
36+
right_bound = lo - 1
37+
38+
if left_bound < n and right_bound >= i + 1 and left_bound <= right_bound:
39+
count += (right_bound - left_bound + 1)
40+
41+
print(count)
42+
43+
t = int(input())
44+
for _ in range(t):
45+
solve_two_pointers()

0 commit comments

Comments
 (0)