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.
1# Take array2n = int(input("Enter array size: "))3arr = []4for i in range(n):5 arr.append(int(input(f"Element {i+1}: ")))67k = int(input("Enter target sum: "))89# Count pairs10count = 011for i in range(len(arr)):12 for j in range(i + 1, len(arr)):13 if arr[i] + arr[j] == k:14 count += 11516print(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
Choose i for every list position.
- 2
Choose j only from positions after i.
- 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.
๐Related Content
- ๐
Phase 4 - Learn Concepts
Review Phase 4 concepts and explanations
- ๐
Phase 4 - Quiz
Test your Phase 4 understanding with quiz questions
- ๐ป
Phase 4 - All Practice Problems
Explore all practice problems for Phase 4
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum