Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Count Pairs with Sum K

Count unordered index pairs whose values add to a target. Students trace nested bounds and avoid counting a pair twice or pairing an element with itself.

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

In this one

  • Enumerate unordered index pairs
  • Avoid self-pairing
  • Count duplicate positions separately

How it works

  1. 1

    Choose i for every list position.

  2. 2

    Choose j only from positions after i.

  3. 3

    Increment count when the indexed values sum to k.

Edge cases

Can one entry pair with itself?

Can one entry pair with itself?

No. j is always greater than i.

What about [2, 2, 2] with target four?

What about [2, 2, 2] with target four?

There are three index pairs.

What's going on

For each i, j starts at i + 1. That visits every pair of different positions exactly once.

If the two values sum to k, count increases by one. Duplicate values at different indexes create separate valid pairs; this is not a count of distinct value combinations. An empty or one-element list has no pairs to test.

Can one entry pair with itself? No. j is always greater than i.

What about [2, 2, 2] with target four? There are three index pairs.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why start j at i + 1?

Pick an answer to check it.

Question 2

Can one entry pair with itself?

Pick an answer to check it.

Questions people ask

Can one entry pair with itself?

No. j is always greater than i.

What about [2, 2, 2] with target four?

There are three index pairs.

Why start j at i + 1?

To skip self-pairs and reversed duplicates.