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 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
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
🔗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