Check if array contains duplicates
Last Updated :
29 Aug, 2024
Given an integer array arr[], check if the array contains any duplicate value.
Examples:
Input: arr[] = {4, 5, 6, 4}
Output: true
Explanation: 4 is the duplicate value.
Input: arr[] = {1, 2, 3, 4}
Output: false
Explanation: All values are distinct.
[Naive Approach] By using two nested loops – O(n ^ 2) Time and O(1) Space
The simple idea is to use a nested loop to compare each element in the array with every other element. If any two elements are found to be the same, return true
, indicating the array has a duplicate element. If no duplicates are found after all comparisons, return false
.
C++
// C++ Program check if there are any duplicates
// in the array using nested loops approach
#include <bits/stdc++.h>
using namespace std;
bool checkDuplicates(vector<int> &arr) {
int n = arr.size();
// Outer loop to pick each element one by one
for(int i = 0; i < n - 1; i++) {
// Inner loop to compare the current element with
// the rest of the elements
for(int j = i + 1; j < n; j++) {
// If a duplicate is found, return true
if(arr[i] == arr[j])
return true;
}
}
// If no duplicates are found, return false
return false;
}
int main () {
vector<int> arr = {4, 5, 6, 4};
cout << (checkDuplicates(arr) ? "true" : "false") << endl;
return 0;
}
C
// C Program check if there are any duplicates
// in the array using nested loops approach
#include <stdio.h>
#include <stdbool.h>
bool checkDuplicates(int *arr, int n) {
// Outer loop to pick each element one by one
for(int i = 0; i < n - 1; i++) {
// Inner loop to compare the current element
// with the rest of the elements
for(int j = i + 1; j < n; j++) {
// If a duplicate is found, return true
if(arr[i] == arr[j])
return true;
}
}
// If no duplicates are found, return false
return false;
}
int main () {
int arr[] = {4, 5, 6, 4};
int n = sizeof(arr) / sizeof(arr[0]);
printf(checkDuplicates(arr, n) ? "true" : "false");
return 0;
}
Java
// Java Program check if there are any duplicates
// in the array using nested loops approach
import java.util.*;
class GfG {
static boolean checkDuplicates(int[] arr) {
int n = arr.length;
// Outer loop to pick each element one by one
for (int i = 0; i < n - 1; i++) {
// Inner loop to compare the current element
// with the rest of the elements
for (int j = i + 1; j < n; j++) {
// If a duplicate is found Return true
if (arr[i] == arr[j])
return true;
}
}
// If no duplicates are found, return false
return false;
}
public static void main(String[] args) {
int[] arr = {4, 5, 6, 4};
System.out.println(checkDuplicates(arr));
}
}
Python
# Python Program check if there are any duplicates
# in the array using nested loops approach
def check_duplicates(arr):
n = len(arr)
# Outer loop to pick each element one by one
for i in range(n - 1):
# Inner loop to compare the current element with the
# rest of the elements
for j in range(i + 1, n):
# If a duplicate is found return True
if arr[i] == arr[j]:
return True
# If no duplicates are found, return False
return False
if __name__ == "__main__":
arr = [4, 5, 6, 4]
print(check_duplicates(arr))
C#
// C# Program check if there are any duplicates
// in the array using nested loops approach
using System;
using System.Collections.Generic;
class GfG {
static bool CheckDuplicates(int[] arr) {
int n = arr.Length;
// Outer loop to pick each element one by one
for (int i = 0; i < n - 1; i++) {
// Inner loop to compare the current element with
// the rest of the elements
for (int j = i + 1; j < n; j++) {
// If a duplicate is found return true
if (arr[i] == arr[j]) {
return true;
}
}
}
// If no duplicates are found, return false
return false;
}
static void Main() {
int[] arr = { 4, 5, 6, 4 };
Console.WriteLine(CheckDuplicates(arr));
}
}
JavaScript
// JavaScript Program check if there are any duplicates
// in the array using nested loops approach
function checkDuplicates(arr) {
let n = arr.length;
// Outer loop to pick each element one by one
for (let i = 0; i < n - 1; i++) {
// Inner loop to compare the current element with
// the rest of the elements
for (let j = i + 1; j < n; j++) {
// If a duplicate is found return true
if (arr[i] === arr[j]) {
return true;
}
}
}
// If no duplicates are found, return false
return false;
}
let arr = [4, 5, 6, 4];
console.log(checkDuplicates(arr));
Time Complexity: O(N2), As we are using nested loop over the given array, where N is the number of elements in the given array.
Auxiliary Space: O(1), As we are not using any extra space.
[Expected Approach] By using HashSet Data Structure – O(n) Time and O(n) Space
The main idea is to insert each value into a HashSet, which only stores unique elements. If any insertion fails or if any elements are already exits in HashSet, it means a duplicate exists, so return true
. If all insertions succeed, it indicates that all elements are unique, so return false
.
C++
// C++ Program check if there are any duplicates
// in the array using Hashing
#include <iostream>
#include <unordered_set>
#include <vector>
using namespace std;
bool checkDuplicates(vector<int>& arr) {
int n = arr.size();
// Create an unordered_set to store the unique elements
unordered_set<int> st;
// Iterate through each element
for (int i = 0; i < n; i++) {
// If the element is already present, return true
// Else insert the element into the set
if (st.find(arr[i]) != st.end())
return true;
else
st.insert(arr[i]);
}
// If no duplicates are found, return false
return false;
}
int main() {
vector<int> arr = { 4, 5, 6, 4 };
cout << (checkDuplicates(arr) ? "true" : "false") << endl;
return 0;
}
Java
// Java Program check if there are any duplicates
// in the array using Hashing
import java.util.HashSet;
import java.util.Set;
class GfG {
// Function to check if there are any duplicates
static boolean checkDuplicates(int[] arr) {
int n = arr.length;
// Create a HashSet to store the unique elements
Set<Integer> st = new HashSet<>();
// Iterate through each element
for (int i = 0; i < n; i++) {
// If the element is already present, return true
// Else insert the element into the set
if (st.contains(arr[i]))
return true;
else
st.add(arr[i]);
}
// If no duplicates are found, return false
return false;
}
public static void main(String[] args) {
int[] arr = { 4, 5, 6, 4 };
System.out.println(checkDuplicates(arr));
}
}
Python
# Python Program check if there are any duplicates
# in the array using Hashing
def checkDuplicates(arr):
n = len(arr)
# Create a set to store the unique elements
st = set()
# Iterate through each element
for i in range(n):
# If the element is already present, return true
# Else insert the element into the set
if arr[i] in st:
return True
else:
st.add(arr[i])
# If no duplicates are found, return false
return False
if __name__ == "__main__":
arr = [4, 5, 6, 4]
print(checkDuplicates(arr))
C#
// C# Program check if there are any duplicates
// in the array using Hashing
using System;
using System.Collections.Generic;
class GfG {
// Function to check if there are any duplicates
static bool CheckDuplicates(int[] arr) {
int n = arr.Length;
// Create a HashSet to store the unique elements
HashSet<int> st = new HashSet<int>();
// Iterate through each element
for (int i = 0; i < n; i++) {
// If the element is already present, return true
// Else insert the element into the set
if (st.Contains(arr[i]))
return true;
else
st.Add(arr[i]);
}
// If no duplicates are found, return false
return false;
}
public static void Main(string[] args) {
int[] arr = { 4, 5, 6, 4 };
Console.WriteLine(CheckDuplicates(arr));
}
}
JavaScript
// JavaScript Program check if there are any duplicates
// in the array using Hashing
function checkDuplicates(arr) {
const n = arr.length;
// Create a Set to store the unique elements
const st = new Set();
// Iterate through each element
for (let i = 0; i < n; i++) {
// If the element is already present, return true
// Else insert the element into the set
if (st.has(arr[i]))
return true;
else
st.add(arr[i]);
}
// If no duplicates are found, return false
return false;
}
const arr = [4, 5, 6, 4];
console.log(checkDuplicates(arr));
Time Complexity: O(n), As we are traversing over the array once.
Auxiliary space: O(n), As we are using unordered set which takes O(n) space in worst case, where n is the size of the array.
[Other Approach] By Sorting the array - O(n * log(n)) Time and O(1) Space
The main idea is to first sort the array arr[]
and then iterate through it to check if any adjacent elements are equal. If a pair of adjacent elements is equal, the function returns true
, indicating the presence of duplicates. If no duplicates are found after traversing the entire array, the function returns false
.
C++
// C++ Program check if there are any duplicates
// in the array using Sorting
#include <bits/stdc++.h>
using namespace std;
bool checkDuplicates(vector<int>& arr) {
int n = arr.size();
// Sort the input array
sort(arr.begin(), arr.end());
// Iterate through the sorted array
for (int i = 1; i < n; ++i) {
// Check if adjacent elements are equal
if (arr[i] == arr[i - 1])
return true;
}
// If no duplicates are found, return false
return false;
}
int main() {
vector<int> arr = { 4, 5, 6, 4 };
cout << (checkDuplicates(arr) ? "true" : "false") << endl;
return 0;
}
C
// C Program check if there are any duplicates
// in the array using Sorting
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
// Function to compare two integers for qsort
int compare(const void* a, const void* b) {
return (*(int*)a - *(int*)b);
}
bool checkDuplicates(int* arr, int n) {
// Sort the array
qsort(arr, n, sizeof(int), compare);
// Iterate through the sorted array
for (int i = 1; i < n; i++) {
// Check if adjacent elements are equal
if (arr[i] == arr[i - 1])
return true;
}
// If no duplicates are found, return false
return false;
}
int main() {
int arr[] = { 4, 5, 6, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
printf("%s\n", checkDuplicates(arr, n) ? "true" : "false");
return 0;
}
Java
// Java Program check if there are any duplicates
// in the array using Sorting
import java.util.Arrays;
class GFG {
static boolean checkDuplicates(int[] arr) {
int n = arr.length;
// Sort the array
Arrays.sort(arr);
// Iterate through the sorted array
for (int i = 1; i < n; i++) {
// Check if adjacent elements are equal
if (arr[i] == arr[i - 1])
return true;
}
// If no duplicates are found, return false
return false;
}
public static void main(String[] args) {
int[] arr = { 4, 5, 6, 4 };
System.out.println(checkDuplicates(arr));
}
}
Python
# Python Program check if there are any duplicates
# in the array using Sorting
def check_duplicates(arr):
n = len(arr)
# Sort the array
arr.sort()
# Iterate through the sorted array
for i in range(1, n):
# Check if adjacent elements are equal
if arr[i] == arr[i - 1]:
return True
# If no duplicates are found, return False
return False
if __name__ == "__main__":
arr = [4, 5, 6, 4]
print(check_duplicates(arr))
C#
// C# Program check if there are any duplicates
// in the array using Sorting
using System;
class GFG {
static bool CheckDuplicates(int[] arr) {
int n = arr.Length;
// Sort the array
Array.Sort(arr);
// Iterate through the sorted array
for (int i = 1; i < n; i++) {
// Check if adjacent elements are equal
if (arr[i] == arr[i - 1])
return true;
}
// If no duplicates are found, return false
return false;
}
static void Main() {
int[] arr = { 4, 5, 6, 4 };
Console.WriteLine(CheckDuplicates(arr));
}
}
JavaScript
// JavaScript Program check if there are any duplicates
// in the array using Sorting
function checkDuplicates(arr) {
let n = arr.length;
// Sort the array
arr.sort((a, b) => a - b);
// Iterate through the sorted array
for (let i = 1; i < n; i++) {
// Check if adjacent elements are equal
if (arr[i] === arr[i - 1])
return true;
}
// If no duplicates are found, return false
return false;
}
const arr = [4, 5, 6, 4];
console.log(checkDuplicates(arr));
Time Complexity: O(n * logn), As we are using sorting function which takes nlogn time.
Auxiliary space: O(1), As we are not using extra space.
Similar Reads
Check for Array Contains Duplicate III Given an integer array arr[] and two integers indexDifference and valueDifference, find a pair of indices (i, j) such that: i != jabs(i - j) <= indexDifferenceabs(arr[i] - arr[j]) <= valueDifferenceReturn true if such a pair exists, false otherwise. Example: Input: arr = [1,2,3,1], indexDiffer
6 min read
Check if an array contains only one distinct element Given an array arr[] of size N, the task is to check if the array contains only one distinct element or not. If it contains only one distinct element then print âYesâ, otherwise print âNoâ. Examples: Input: arr[] = {3, 3, 4, 3, 3} Output: No Explanation: There are 2 distinct elements present in the
8 min read
Check if array contains contiguous integers with duplicates allowed Given an array of n integers(duplicates allowed). Print "Yes" if it is a set of contiguous integers else print "No". Examples: Input : arr[] = {5, 2, 3, 6, 4, 4, 6, 6}Output : YesThe elements form a contiguous set of integerswhich is {2, 3, 4, 5, 6}.Input : arr[] = {10, 14, 10, 12, 12, 13, 15}Output
15+ min read
Find duplicates under given constraints 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} Outpu
4 min read
Check if all subarrays contains at least one unique element Given an array arr[] consisting of N integers, the task is to check if all subarrays of the array have at least one unique element in it or not. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: arr[] = {1, 2, 1}Output: YesExplanation:For Subarrays of size 1: {1}, {2}, {
11 min read
Find if an array contains a string with one mismatch Given a string and array of strings, find whether the array contains a string with one character difference from the given string. Array may contain strings of different lengths. Examples: Input : str = "banana" arr[] = {"bana", "apple", "banaba", bonanzo", "banamf"} Output :True Explanation:-There
9 min read
Check if given two Arrays are equal (using Map) Given two arrays, A[] and B[], the task is to check if they are equal or not. Arrays are considered equal if any permutation of array B equates to array A. Examples: Input: A[] = [2, 4, 5, 7, 5, 6] and B[] = [4, 2, 5, 5, 6, 7]Output: YesExplanation: All the elements in array A are present in array B
6 min read
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
Check if the array is beautiful Given an integer n and an array of size n check if it satisfies following conditions:- All elements of array must lie between 1 to n.Array must NOT be sorted in ascending order.The array consists of unique elements.If all conditions satisfied print Yes else No. Examples: Input: 4 1 2 3 4Output: NoAr
9 min read
Check whether K times of a element is present in array Given an array arr[] and an integer K, the task is to check whether K times of any element are also present in the array. Examples : Input: arr[] = {10, 14, 8, 13, 5}, K = 2 Output: Yes Explanation: K times of 5 is also present in an array, i.e. 10. Input: arr[] = {7, 8, 5, 9, 11}, K = 3 Output: No
8 min read