সমস্যা বিবরণ
একটি সংখ্যার লিস্ট এবং একটি মান k দেওয়া আছে। লিস্ট থেকে পার্থক্য ঠিক k হয় এমন ভিন্ন জোড়ার সংখ্যা বের করতে হবে।
পদ্ধতি ১: ডাবল for লুপ (O(n²))
listA = [5, 3, 7, 2, 9]
k = 2
count = 0
for i in range(len(listA)):
for j in range(i + 1, len(listA)):
if listA[i] - listA[j] == k or listA[j] - listA[i] == k:
count += 1
print("Required Pairs:", count) # 3
পদ্ধতি ২: সর্ট করে while লুপ (O(n log n))
লিস্ট সর্ট করুন, دوটি পয়েন্টার current_index এবং next_index দিয়ে লিনিয়ার স্ক্যান করুন।
listA = [5, 3, 7, 2, 9]
k = 2
count = 0
listA.sort()
next_index = 0
current_index = 0
while current_index < len(listA):
if listA[current_index] - listA[next_index] == k:
count += 1
next_index += 1
current_index += 1
elif listA[current_index] - listA[next_index] > k:
next_index += 1
else:
current_index += 1
print("Required Pairs:", count) # 3