Find Duplicate Element
Find duplicate element in array of size n+1 with elements 1 to n.
AdvancedPhase 4 - Level 5: Logical & AppliedExample 14 of 14
find-duplicate-element.py
1# Take array2n = int(input("Enter n: "))3arr = []4for i in range(n + 1):5 arr.append(int(input(f"Element {i+1}: ")))67# Find duplicate using sum8expected_sum = n * (n + 1) // 29actual_sum = sum(arr)10duplicate = actual_sum - expected_sum1112print(f"Duplicate: {duplicate}")
Output
Enter n: 4 Element 1: 1 Element 2: 2 Element 3: 3 Element 4: 4 Element 5: 3 Duplicate: 3
What's going on
Use sum difference to find duplicate.
Key Concepts:
Expected sum for 1 to n
Actual sum includes duplicate
Duplicate = actual - expected
🔗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