Find out the duplicate element in O(logN) time

By | September 26, 2023

Given an array consisting of integers in range 1 to n consisting of only one duplicate element. Find out the duplicate element in O(logN) time.

Examples:

Input : 
6
1 1 2 3 4 5
Output : 
1

Input : 
5
1 2 3 4 4
Output : 
4

Using Binary Search:

#include <bits/stdc++.h>
using namespace std;

int find_only_repeating_element(int arr[], int n) {
    int low = 0;
    int high = n - 1;
    while (low <= high) {
        int mid = low + (high - low) / 2;
        if (arr[mid] == arr[mid + 1] || arr[mid] == arr[mid - 1]) {
            return arr[mid];
        }
        if (arr[mid] < mid + 1) {
            high = mid - 1;
        } else {
            low = mid + 1;
        }
    }
    return -1;
}

int main() {
    int n;
    cin >> n;
    int *arr = new int[n];
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }
    cout << find_only_repeating_element(arr, n) << endl;
    delete[] arr; // Deallocate memory
    return 0;
}

Time Complexity: O(logN)

Author: Mithlesh Upadhyay

I hold an M.Tech degree in Artificial Intelligence (2023) from Delhi Technological University (DTU) and possess over 4 years of experience. I worked at GeeksforGeeks, leading teams and managing content, including GATE CS, Test Series, Placements, C, and C++. I've also contributed technical content to companies like MarsDev, Tutorialspoint, StudyTonight, TutorialCup, and Guru99. My skill set includes coding, Data Structures and Algorithms (DSA), and Object-Oriented Programming (OOPs). I'm proficient in C++, Python, JavaScript, HTML, CSS, Bootstrap, React.js, Node.js, MongoDB, Django, and Data Science.