Find duplicates under given constraints
Last Updated :
11 Feb, 2023
A sorted array contains 6 different numbers, only 1 number is repeated five times. So there are total 10 numbers in array. Find the duplicate numbers using two comparisons only.
Examples :
Input: arr[] = {1, 1, 1, 1, 1, 5, 7, 10, 20, 30}
Output: 1
Input: arr[] = {1, 2, 3, 3, 3, 3, 3, 5, 9, 10}
Output: 3
Asked in Yahoo
An important observation is, arr[4] or arr[5] is an occurrence of repeated element for sure. Below is the implementation based on this observation.
Implementation:
CPP
#include<bits/stdc++.h>
using namespace std;
int findDuplicate( int a[])
{
if (a[3] == a[4])
return a[3];
else if (a[4] == a[5])
return a[4];
else
return a[5];
}
int main()
{
int a[] = {1, 1, 1, 1, 1, 5, 7, 10, 20, 30};
cout << findDuplicate(a);
return 0;
}
|
Java
class Num{
static int findDuplicate( int a[])
{
if (a[ 3 ] == a[ 4 ])
return a[ 3 ];
else if (a[ 4 ] == a[ 5 ])
return a[ 4 ];
else
return a[ 5 ];
}
public static void main(String[] args)
{
int a[] = { 1 , 1 , 1 , 1 , 1 , 5 , 7 , 10 , 20 , 30 };
System.out.println(findDuplicate(a));
}
}
|
Python3
def findDuplicate(a):
if (a[ 3 ] = = a[ 4 ]):
return a[ 3 ]
elif (a[ 4 ] = = a[ 5 ]):
return a[ 4 ]
else :
return a[ 5 ]
a = [ 1 , 1 , 1 , 1 , 1 , 5 , 7 , 10 , 20 , 30 ]
print (findDuplicate(a))
|
C#
using System;
class GFG {
static int findDuplicate( int []a)
{
if (a[3] == a[4])
return a[3];
else if (a[4] == a[5])
return a[4];
else
return a[5];
}
public static void Main()
{
int []a = {1, 1, 1, 1, 1, 5,
7, 10, 20, 30};
Console.Write(findDuplicate(a));
}
}
|
PHP
<?php
function findDuplicate( $a )
{
if ( $a [3] == $a [4])
return $a [3];
else if ( $a [4] == $a [5])
return $a [4];
else
return $a [5];
}
$a = array (1, 1, 1, 1, 1,
5, 7, 10, 20, 30);
echo findDuplicate( $a );
?>
|
Javascript
<script>
function findDuplicate(a)
{
if (a[3] == a[4])
return a[3];
else if (a[4] == a[5])
return a[4];
else
return a[5];
}
let a = [1, 1, 1, 1, 1, 5, 7, 10, 20, 30];
document.write(findDuplicate(a));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Exercise: Extend the above problem for an array with n different elements, size of array is 2*(n-1) and one element repeats (n-1) times.
Share your thoughts in the comments
Please Login to comment...