Find the only different element in an array
Last Updated :
26 Apr, 2023
Given an array of integers where all elements are same except one element, find the only different element in the array. It may be assumed that the size of the array is at least two.
Examples:
Input : arr[] = {10, 10, 10, 20, 10, 10}
Output : 3
arr[3] is the only different element.
Input : arr[] = {30, 10, 30, 30, 30}
Output : 1
arr[1] is the only different element.
A simple solution is to traverse the array. For every element, check if it is different from others or not. The time complexity of this solution would be O(n*n)
A better solution is to use hashing. We count frequencies of all elements. The hash table will have two elements. We print the element with value (or frequency) equal to 1. This solution works in O(n) time but requires O(n) extra space.
An efficient solution is to first check the first three elements. There can be two cases,
- Two elements are same, i.e., one is different according to given conditions in the question. In this case, the different element is among the first three, so we return the different element.
- All three elements are same. In this case, the different element lies in the remaining array. So we traverse the array from the fourth element and simply check if the value of the current element is different from previous or not.
Below is the implementation of the above idea.
C++
// C++ program to find the only different
// element in an array.
#include <bits/stdc++.h>
using namespace std;
// Function to find minimum range
// increments to sort an array
int findTheOnlyDifferent(int arr[], int n)
{
// Array size must be at least two.
if (n == 1)
return -1;
// If there are two elements, then we
// can return any one element as different
if (n == 2)
return 0;
// Check if the different element is among
// first three
if (arr[0] == arr[1] && arr[0] != arr[2])
return 2;
if (arr[0] == arr[2] && arr[0] != arr[1])
return 1;
if (arr[1] == arr[2] && arr[0] != arr[1])
return 0;
// If we reach here, then first three elements
// must be same (assuming that only one element
// is different.
for (int i = 3; i < n; i++)
if (arr[i] != arr[i - 1])
return i;
return -1;
}
// Driver Code
int main()
{
int arr[] = { 10, 20, 20, 20, 20 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << findTheOnlyDifferent(arr, n);
return 0;
}
Java
// Java program to find the only different
// element in an array.
public class GFG
{
// Function to find minimum range
// increments to sort an array
static int findTheOnlyDifferent(int[] arr, int n)
{
// Array size must be at least two.
if (n == 1)
return -1;
// If there are two elements, then we
// can return any one element as different
if (n == 2)
return 0;
// Check if the different element is among
// first three
if (arr[0] == arr[1] && arr[0] != arr[2])
return 2;
if (arr[0] == arr[2] && arr[0] != arr[1])
return 1;
if (arr[1] == arr[2] && arr[0] != arr[1])
return 0;
// If we reach here, then first three elements
// must be same (assuming that only one element
// is different.
for (int i = 3; i < n; i++)
if (arr[i] != arr[i - 1])
return i;
return -1;
}
// Driver Code
public static void main(String args[])
{
int[] arr = { 10, 20, 20, 20, 20 };
int n = arr.length;
System.out.println(findTheOnlyDifferent(arr, n));
}
// This code is contributed
// by Ryuga
}
Python3
# Python3 program to find the only
# different element in an array.
# Function to find minimum range
# increments to sort an array
def findTheOnlyDifferent(arr, n):
# Array size must be at least two.
if n == 1:
return -1
# If there are two elements,
# then we can return any one
# element as different
if n == 2:
return 0
# Check if the different element
# is among first three
if arr[0] == arr[1] and arr[0] != arr[2]:
return 2
if arr[0] == arr[2] and arr[0] != arr[1]:
return 1
if arr[1] == arr[2] and arr[0] != arr[1]:
return 0
# If we reach here, then first
# three elements must be same
# (assuming that only one element
# is different.
for i in range(3, n):
if arr[i] != arr[i - 1]:
return i
return -1
# Driver Code
if __name__ == "__main__":
arr = [10, 20, 20, 20, 20]
n = len(arr)
print(findTheOnlyDifferent(arr, n))
# This code is contributed
# by Rituraj Jain
JavaScript
// JavaScript program to find the only different
// element in an array.
// Function to find minimum range
// increments to sort an array
function findTheOnlyDifferent(arr, n) {
// Array size must be at least two.
if (n === 1)
return -1;
// If there are two elements, then we
// can return any one element as different
if (n === 2)
return 0;
// Check if the different element is among
// first three
if (arr[0] === arr[1] && arr[0] !== arr[2])
return 2;
if (arr[0] === arr[2] && arr[0] !== arr[1])
return 1;
if (arr[1] === arr[2] && arr[0] !== arr[1])
return 0;
// If we reach here, then first three elements
// must be same (assuming that only one element
// is different.
for (let i = 3; i < n; i++)
if (arr[i] !== arr[i - 1])
return i;
return -1;
}
// Driver Code
const arr = [10, 20, 20, 20, 20];
const n = arr.length;
console.log(findTheOnlyDifferent(arr, n));
C#
// C# program to find the only different
// element in an array.
using System;
class GFG
{
// Function to find minimum range
// increments to sort an array
static int findTheOnlyDifferent(int[] arr, int n)
{
// Array size must be at least two.
if (n == 1)
return -1;
// If there are two elements, then we
// can return any one element as different
if (n == 2)
return 0;
// Check if the different element is among
// first three
if (arr[0] == arr[1] && arr[0] != arr[2])
return 2;
if (arr[0] == arr[2] && arr[0] != arr[1])
return 1;
if (arr[1] == arr[2] && arr[0] != arr[1])
return 0;
// If we reach here, then first three elements
// must be same (assuming that only one element
// is different.
for (int i = 3; i < n; i++)
if (arr[i] != arr[i - 1])
return i;
return -1;
}
// Driver Code
public static void Main()
{
int[] arr = { 10, 20, 20, 20, 20 };
int n = arr.Length;
Console.Write(findTheOnlyDifferent(arr, n));
}
}
// This code is contributed
// by Akanksha Rai
PHP
<?php
// PHP program to find the only different
// element in an array.
// Function to find minimum range
// increments to sort an array
function findTheOnlyDifferent($arr, $n)
{
// Array size must be at least two.
if ($n == 1)
return -1;
// If there are two elements, then we
// can return any one element as different
if ($n == 2)
return 0;
// Check if the different element is among
// first three
if ($arr[0] == $arr[1] && $arr[0] != $arr[2])
return 2;
if ($arr[0] == $arr[2] && $arr[0] != $arr[1])
return 1;
if ($arr[1] == $arr[2] && $arr[0] != $arr[1])
return 0;
// If we reach here, then first three
// elements must be same (assuming that
// only one element is different.
for ($i = 3; $i < $n; $i++)
if ($arr[$i] != $arr[$i - 1])
return $i;
return -1;
}
// Driver Code
$arr = array(10, 20, 20, 20, 20);
$n = sizeof($arr);
echo findTheOnlyDifferent($arr, $n);
// This code is contributed by ajit
?>
Time Complexity: O(n)
Auxiliary Space: O(1)
SECOND APPROACH : Using STL
Another approach to this problem is by using vector method . Like we will simply copy all the element in another array and then we will simply compare the first element of new sorted array with previous one and the index which is not same will be our answer .
Below is the implementation of the above approach :
C++
#include <bits/stdc++.h>
using namespace std;
void solve()
{
int arr[] = { 10, 20, 20, 20, 20 };
int n = sizeof(arr) / sizeof(arr[0]);
int arr2[n];
for(int i=0;i<n;i++)
{
arr2[i]=arr[i];
}
sort(arr2,arr2+n);
for (int i = 0; i < n; i++) {
if (arr[i] != arr2[1]) {
cout << i << "\n";
}
}
}
int main() {
solve();
return 0;
}
Java
// Java program to find the only different
// element in an array.
import java.util.Arrays;
// Function to find minimum range
// increments to sort an array
public class Main {
public static void main(String[] args) {
solve();
}
static void solve() {
int[] arr = {10, 20, 20, 20, 20};
int n = arr.length;
int[] arr2 = Arrays.copyOf(arr, n);
Arrays.sort(arr2);
for (int i = 0; i < n; i++) {
if (arr[i] != arr2[1]) {
System.out.println(i);
}
}
}
}
Python3
# Python3 program to find the only different
# Function to solve the problem
def solve():
# Initialize an array
arr = [10, 20, 20, 20, 20]
n = len(arr)
# Create a copy of the array and sort it
arr2 = arr.copy()
arr2.sort()
# Loop through the original array and print the indices
# of elements that are not equal to the second smallest element
for i in range(n):
if arr[i] != arr2[1]:
print(i)
# Call the solve function
solve()
JavaScript
// Function to find the second smallest element index in an array
function findSecondSmallestIndex(arr) {
let n = arr.length;
// Create a copy of the original array
let arr2 = [...arr];
// Sort the copied array
arr2.sort((a, b) => a - b);
// Loop through the original array
for (let i = 0; i < n; i++) {
// If the current element is not equal to the second smallest element
if (arr[i] !== arr2[1]) {
// Return the index of the current element
return i;
}
}
}
// Test the function
let arr = [10, 20, 20, 20, 20];
let index = findSecondSmallestIndex(arr);
console.log(` ${index}`);
C#
using System;
class MainClass {
public static void Main(string[] args)
{
// Initialize an array
int[] arr = { 10, 20, 20, 20, 20 };
int n = arr.Length;
// Create a copy of the array and sort it
int[] arr2 = new int[n];
Array.Copy(arr, arr2, n);
Array.Sort(arr2);
// Loop through the original array and print the
// indices of elements that are not equal to the
// second smallest element
for (int i = 0; i < n; i++) {
if (arr[i] != arr2[1]) {
Console.WriteLine(i);
}
}
}
}
Time Complexity: O(n)
Auxiliary Space: O(1)
Similar Reads
Find duplicate elements in an array Given an array of n integers. The task is to find all elements that have more than one occurrences. The output should only be one occurrence of a number irrespective of the number of occurrences in the input array.Examples: Input: {2, 10, 10, 100, 2, 10, 11, 2, 11, 2}Output: {2, 10, 11}Input: {5, 40
11 min read
Count distinct elements in an array in Python Given an unsorted array, count all distinct elements in it. Examples: Input : arr[] = {10, 20, 20, 10, 30, 10} Output : 3 Input : arr[] = {10, 20, 20, 10, 20} Output : 2 We have existing solution for this article. We can solve this problem in Python3 using Counter method. Approach#1: Using Set() Thi
2 min read
Find sum of non-repeating (distinct) elements in an array Given an integer array with repeated elements, the task is to find the sum of all distinct elements in the array.Examples: Input : arr[] = {12, 10, 9, 45, 2, 10, 10, 45,10};Output : 78Here we take 12, 10, 9, 45, 2 for sumbecause it's distinct elements Input : arr[] = {1, 10, 9, 4, 2, 10, 10, 45 , 4}
14 min read
Find extra element in the second array Given two arrays A[] and B[]. The second array B[] contains all the elements of A[] except for 1 extra element. The task is to find that extra element.Examples: Input: A[] = { 1, 2, 3 }, B[] = {1, 2, 3, 4} Output: 4 Element 4 is not present in arrayInput: A[] = {10, 15, 5}, B[] = {10, 100, 15, 5} Ou
10 min read
Find index of the element differing in parity with all other array elements Given an array arr[] of size N (N > 3), the task is to find the position of the element that differs in parity (odd/even) with respect to all other array elements. Note: It is guaranteed that there will always be a number that differs in parity from all other elements. Examples: Input: arr[] = {2
11 min read
Find the only non-repeating element in a given array Given an array A[] consisting of N (1 ? N ? 105) positive integers, the task is to find the only array element with a single occurrence. Note: It is guaranteed that only one such element exists in the array. Examples: Input: A[] = {1, 1, 2, 3, 3}Output: 2Explanation: Distinct array elements are {1,
10 min read
Single Element in a Sorted Array Given a sorted array in which all elements appear twice and one element appears only once, the task is to find the element that appears once.Examples: Input: arr[] = {1, 1, 3, 3, 4, 5, 5, 7, 7, 8, 8}Output: 4Explanation: All numbers except 4 occur twice in the array.Input: arr[] = {1, 1, 3, 3, 4, 4,
10 min read
Find lost element from a duplicated array Given two arrays that are duplicates of each other except one element, that is one element from one of the array is missing, we need to find that missing element. Examples: Input: arr1[] = {1, 4, 5, 7, 9} arr2[] = {4, 5, 7, 9}Output: 11 is missing from second array.Input: arr1[] = {2, 3, 4, 5} arr2[
15+ min read
Print sorted distinct elements of array Given an array that might contain duplicates, print all distinct elements in sorted order. Examples: Input : 1, 3, 2, 2, 1Output : 1 2 3Input : 1, 1, 1, 2, 2, 3Output : 1 2 3The simple Solution is to sort the array first, then traverse the array and print only first occurrences of elements. Algorith
6 min read
Find missing elements from an Array with duplicates Given an array arr[] of size N having integers in the range [1, N] with some of the elements missing. The task is to find the missing elements. Note: There can be duplicates in the array. Examples: Input: arr[] = {1, 3, 3, 3, 5}, N = 5Output: 2 4Explanation: The numbers missing from the list are 2 a
12 min read