Count Pairs with Sum K

Count pairs of elements whose sum equals k.

AdvancedPhase 4 - Level 5: Logical & AppliedExample 7 of 14
count-pairs-with-sum-k.py
1# Take array
2n = int(input("Enter array size: "))
3arr = []
4for i in range(n):
5 arr.append(int(input(f"Element {i+1}: ")))
6
7k = int(input("Enter target sum: "))
8
9# Count pairs
10count = 0
11for i in range(len(arr)):
12 for j in range(i + 1, len(arr)):
13 if arr[i] + arr[j] == k:
14 count += 1
15
16print(f"Number of pairs with sum {k}: {count}")

Output

Enter array size: 5
Element 1: 2
Element 2: 4
Element 3: 3
Element 4: 5
Element 5: 1
Enter target sum: 6
Number of pairs with sum 6: 2

What's going on

Check all pairs using nested loops.

Key Concepts:

Outer loop: first element
Inner loop: second element (i+1 to avoid duplicates)
Count if sum equals k