- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find duplicates under given constraints in C++
Suppose we have a list with 6 different numbers. Only one number is repeated five times. So there are total 10 elements in the array. Find duplicate numbers using only two comparisons. If the list is like [1, 2, 3, 4, 4, 4, 4, 4, 5, 6], so output is 4.
As there are only 10 numbers, then for any type of duplicate numbers, the range of numbers will be placed from index 3 to 5. By checking these indices, we can find the result.
Example
#include<iostream> using namespace std; int getDuplicate(int array[]) { if (array[3] == array[4]) return array[3]; else if (array[4] == array[5]) return array[4]; else return array[5]; } int main() { int a[] = {1, 2, 3, 4, 4, 4, 4, 4, 5, 6}; cout << "Duplicate element: " << getDuplicate(a); }
Output
Duplicate element: 4
Advertisements