Find Duplicate in an Array in C++

ijsathi

Israt Zahan Sathi

Posted on January 15, 2024

Find Duplicate in an Array in C++

Problem 1
You will be given an array arr of size n. Print "YES" if there is any duplicate value in the array, "NO" otherwise.

Sample Input 1
5
2 8 5 7 3
Sample Output 1
NO

Sample Input 2
7
2 1 3 5 2 1 9
Sample Output 2
YES

Input Format

  • First line will contain n.
  • Second line will contain the array arr. Image description

Follow the steps to resolve the problem:

  • Assuming we get an input.
  • Now declare n and input its value.
  • Declare an array name is arr, and take that as input.
  • Take a tmp _to check if there are duplicate values in the array.[_tmp _is a variable used as a flag to indicate whether there are duplicate elements in the array. The name "_tmp" is often used as a shorthand for "temporary" or "temporary variable." Its purpose is to store a temporary state or result during the execution of the program.]
  • Then loop through and look for duplicates. If duplicate value is found then I will set "tmp = 1" and also break the loop.
  • After that I will check, if duplicate value is found I will print "YES", if not found I will print "NO".

Below is the implementation of the above method:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    cin >> n;
    int arr[n];
    for (int i = 0; i < n; i++)
        cin >> arr[i];
    int tmp = 0;
    for (int i = 0; i < n; i++)
    {
        for (int j = i + 1; j < n; j++)
        {
            if (arr[i] == arr[j])
            {
                tmp = 1;
                break;
            }
        }
    }
    if (tmp)
        cout << "YES" << endl;
    else
        cout << "NO" << endl;
    return 0;
}
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
ijsathi
Israt Zahan Sathi

Posted on January 15, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related