Open In App

Find the only repeating element in a sorted array of size n

Last Updated : 19 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a sorted array of n elements containing elements in range from 1 to n-1 i.e. one element occurs twice, the task is to find the repeating element in an array.

Examples : 

Input :  arr[] = { 1, 2 , 3 , 4 , 4}
Output : 4

Input : arr[] = { 1 , 1 , 2 , 3 , 4}
Output : 1

Brute Force:

  1. Traverse the input array using a for a loop.
  2. For each element in the array, traverse the remaining part of the array using another for loop.
  3. For each subsequent element, check if it is equal to the current element.
  4. If a match is found, return the current element.
  5. If no match is found, continue with the next element in the outer loop.
  6. If the outer loop completes without finding a match, return -1 to indicate that there is no repeating element in the array.

Below is the implementation of the above approach:

C++
// C++ program to find the only repeating element in an
// array of size n and elements from range 1 to n-1.
#include <bits/stdc++.h>
using namespace std;


// Returns index of second appearance of a repeating element
// The function assumes that array elements are in range from
// 1 to n-1.
int FindRepeatingElement(int arr[], int size){
    for(int i=0; i<size; i++){
        for(int j=i+1; j<size; j++){
            if(arr[i] == arr[j])
                return i;
        }
    }
    return -1;
}


// Driver code
int main()
{
    int arr[] = {1, 2 , 3 , 4 , 4};
    int n = sizeof(arr) / sizeof(arr[0]);
    int index = FindRepeatingElement(arr, n);
    if (index != -1)
        cout << arr[index];
    return 0;
}
Java
import java.util.*;

public class Main {

    // Returns index of second appearance of a repeating element
    // The function assumes that array elements are in range from
    // 1 to n-1.
    public static int findRepeatingElement(int arr[], int size){
        for(int i=0; i<size; i++){
            for(int j=i+1; j<size; j++){
                if(arr[i] == arr[j])
                    return i;
            }
        }
        return -1;
    }

    // Driver code
    public static void main(String[] args) {
        int arr[] = {1, 2 , 3 , 4 , 4};
        int n = arr.length;
        int index = findRepeatingElement(arr, n);
        if (index != -1)
            System.out.println(arr[index]);
    }
}
Python3
# Python3 program to find the only repeating element in an
# array of size n and elements from range 1 to n-1.

# Returns second appearance of a repeating element
# The function assumes that array elements are in range from
# 1 to n-1.
def FindRepeatingElement(arr, size):
    for i in range(size):
        for j in range(i+1, size):
            if arr[i] == arr[j]:
                return arr[i]
    return -1

# Driver code
if __name__ == '__main__':
    arr = [1, 2, 3, 4, 4]
    n = len(arr)
    element = FindRepeatingElement(arr, n)
    if element != -1:
        print(element)
C#
using System;

public class Program
{

  // Returns index of second appearance of a repeating element
  // The function assumes that array elements are in range from
  // 1 to n-1.
  public static int FindRepeatingElement(int[] arr, int size)
  {
    for (int i = 0; i < size; i++)
    {
      for (int j = i + 1; j < size; j++)
      {
        if (arr[i] == arr[j])
        {
          return i;
        }
      }
    }
    return -1;
  }

  // Driver code
  public static void Main()
  {
    int[] arr = { 1, 2, 3, 4, 4 };
    int n = arr.Length;
    int index = FindRepeatingElement(arr, n);
    if (index != -1)
    {
      Console.WriteLine(arr[index]);
    }
  }
}
Javascript
// JavaScript program to find the only repeating element in an
// array of size n and elements from range 1 to n-1.

// Returns index of second appearance of a repeating element
// The function assumes that array elements are in range from
// 1 to n-1.
function FindRepeatingElement(arr, size)
{
    for(let i=0; i<size; i++)
    {
        for(let j=i+1; j<size; j++)
        {
            if(arr[i] == arr[j])
                return i;
        }
    }
    return -1;
}

// Driver code
let arr = [1, 2 , 3 , 4 , 4];
let n = arr.length;
let index = FindRepeatingElement(arr, n);
if (index != -1)
console.log(arr[index]);

// This code is contributed by akashish__

Output
4

Time Complexity: O(N^2)
Auxiliary Space: O(1)

An efficient method is to use Floyd’s Tortoise and Hare algorithm.

C++
// C++ program to find the only repeating element in an 
// array of size n and elements from range 1 to n-1. 
#include <bits/stdc++.h> 
using namespace std; 

// Returns the repeating element in the array
// The function assumes that array elements are in range from 
// 1 to n-1. 
int FindRepeatingElement(int arr[], int size){
    for(int i = 0; i < size; i++){
        if(arr[abs(arr[i])] >= 0)
            arr[abs(arr[i])] = -arr[abs(arr[i])];
        else
            return abs(arr[i]);
    }
    return -1;
}

// Driver code 
int main() 
{ 
    int arr[] = {1,3,3,4,5,6,7,8}; 
    int n = sizeof(arr) / sizeof(arr[0]); 
    int repeatingElement = FindRepeatingElement(arr, n); 
    cout << repeatingElement; 
    return 0; 
}
Java
class Test
{
    // Returns the repeating element in the array
    // The function assumes that array elements are in range from 
    // 1 to n-1. 
    static int findRepeatingElement(int arr[]){
        int tortoise = arr[0];
        int hare = arr[0];
        
        // Phase 1: Finding intersection point of Tortoise and Hare
        do {
            tortoise = arr[tortoise];
            hare = arr[arr[hare]];
        } while(tortoise != hare);
        
        // Phase 2: Finding the entrance to the cycle
        tortoise = arr[0];
        while(tortoise != hare){
            tortoise = arr[tortoise];
            hare = arr[hare];
        }
        
        return hare;
    }
    
    // Driver method
    public static void main(String[] args) 
    { 
        int  arr[] = {1, 2, 3, 3, 4, 5};
        int repeatingElement = findRepeatingElement(arr); 
        System.out.println(repeatingElement); 
    }
}
Python3
# Python program to find the only repeating element in an
# array of size n and elements from range 1 to n-1

def findRepeatingElement(arr):
    tortoise = arr[0]
    hare = arr[0]
    
    # Phase 1: Finding intersection point of Tortoise and Hare
    while True:
        tortoise = arr[tortoise]
        hare = arr[arr[hare]]
        if tortoise == hare:
            break
    
    # Phase 2: Finding the entrance to the cycle
    tortoise = arr[0]
    while tortoise != hare:
        tortoise = arr[tortoise]
        hare = arr[hare]
    
    return hare

# Driver code
arr = [1, 2, 3, 3, 4, 5]
repeatingElement = findRepeatingElement(arr)
print(repeatingElement)
C#
// C# program to find the only repeating
// element in an array of size n and 
// elements from range 1 to n-1.
using System;

class Test
{
    // Returns index of second appearance of a
    // repeating element. The function assumes that
    // array elements are in range from 1 to n-1.
    static int findRepeatingElement(int []arr, int low,
                                              int high)
    {
        // low = 0 , high = n-1;
        if (low > high)
            return -1;
    
        int mid = (low + high) / 2;
    
        // Check if the mid element 
        // is the repeating one
        if (arr[mid] != mid + 1)
        {
            if (mid > 0 && arr[mid]==arr[mid-1])
                return mid;
    
            // If mid element is not at its position
            // that means the repeated element is in left
            return findRepeatingElement(arr, low, mid-1);
        }
    
        // If mid is at proper position 
        // then repeated one is in right.
        return findRepeatingElement(arr, mid+1, high);
    }
    
    // Driver method
    public static void Main() 
    {
        int []arr = {1, 2, 3, 3, 4, 5};
        int index = findRepeatingElement(arr, 0, arr.Length-1);
        if (index != -1)
        Console.Write(arr[index]);
    }
}

// This code is contributed by Nitin Mittal.
Javascript
<script>
      // JavaScript program to find the only repeating element in an
      // array of size n and elements from range 1 to n-1.

      // Returns index of second appearance of a repeating element
      // The function assumes that array elements are in range from
      // 1 to n-1.
      function findRepeatingElement(arr, low, high) 
      {
      
        // low = 0 , high = n-1;
        if (low > high) return -1;

        var mid = parseInt((low + high) / 2);

        // Check if the mid element is the repeating one
        if (arr[mid] != mid + 1)
        {
          if (mid > 0 && arr[mid] == arr[mid - 1]) return mid;

          // If mid element is not at its position that means
          // the repeated element is in left
          return findRepeatingElement(arr, low, mid - 1);
        }

        // If mid is at proper position then repeated one is in
        // right.
        return findRepeatingElement(arr, mid + 1, high);
      }

      // Driver code
      var arr = [1, 2, 3, 3, 4, 5];
      var n = arr.length;
      var index = findRepeatingElement(arr, 0, n - 1);
      if (index != -1) document.write(arr[index]);
      
      // This code is contributed by rdtank.
    </script>
PHP
<?php
// PHP program to find the only 
// repeating element in an array 
// of size n and elements from
// range 1 to n-1.

// Returns index of second 
// appearance of a repeating 
// element. The function assumes
// that array elements are in 
// range from 1 to n-1.
function findRepeatingElement($arr, 
                              $low, 
                              $high)
{
    // low = 0 , high = n-1;
    if ($low > $high)
        return -1;

    $mid = floor(($low + $high) / 2);

    // Check if the mid element
    // is the repeating one
    if ($arr[$mid] != $mid + 1)
    {
        if ($mid > 0 && $arr[$mid] == 
                        $arr[$mid - 1])
            return $mid;

        // If mid element is not at 
        // its position that means
        // the repeated element is in left
        return findRepeatingElement($arr, $low, 
                                    $mid - 1);
    }

    // If mid is at proper position
    // then repeated one is in right.
    return findRepeatingElement($arr, $mid + 1, 
                                        $high);
}

// Driver code
$arr = array(1, 2, 3, 3, 4, 5);
$n = sizeof($arr);
$index = findRepeatingElement($arr, 0, 
                              $n - 1);
if ($index != -1)
echo $arr[$index];

// This code is contributed
// by nitin mittal. 
?>

Output
3

Time Complexity : O(log n)

Space Complexity: O(1)

 



Similar Reads

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, 2, 3}. Frequency of these elements are {2, 1, 2} r
11 min read
Find the two non-repeating elements in an array of repeating elements/ Unique Numbers 2
Given an array arr[] containing 2*N+2 positive numbers, out of which 2*N numbers exist in pairs whereas the other two number occur exactly once and are distinct. Find the other two numbers. Return in increasing order. Example: Input: N = 2, arr[] = {1, 2, 3, 2, 1, 4}Output:3 4 Explanation: 3 and 4 occur exactly once. Input: N = 1, arr[] = {2, 1, 3,
9 min read
Find the repeating element in an Array of size N consisting of first M natural numbers
Given an array arr[] of size N, which contains a permutation of numbers from 1 to M, as well as an element that is repeated(one or more times), the task is to find the repeating element. Examples: Input: arr[]={2, 6, 4, 3, 1, 5, 2}, N=7Output:2Explanation: In arr[], all elements from 0 to 6 occurs once, except 2 which is repeated once. Input: arr[]
8 min read
Find any one of the multiple repeating elements in read only array | Set 2
Given a read-only array arr[] of size N + 1, find one of the multiple repeating elements in the array where the array contains integers only between 1 and N. Note: Read-only array means that the contents of the array can't be modified. Examples: Input: N = 5, arr[] = {1, 1, 2, 3, 5, 4} Output: 1 Explanation: 1 is the only number repeated in the arr
6 min read
Find any one of the multiple repeating elements in read only array
Given a read-only array of size ( n+1 ), find one of the multiple repeating elements in the array where the array contains integers only between 1 and n. A read-only array means that the contents of the array can’t be modified.Examples: Input : n = 5 arr[] = {1, 1, 2, 3, 5, 4} Output : One of the numbers repeated in the array is: 1 Input : n = 10 a
15 min read
Count of only repeated element in a sorted array of consecutive elements
Given a sorted array of consecutive elements. The array has only one element repeated many times. The task is to find the length of the sequence of the repeated elements Examples: Input: arr[] = {1, 2, 3, 4, 4, 4, 5, 6}Output: 4 3Repeated element is 4 and it appears 3 times Input: arr[] = {4, 4, 4, 4, 4}Output: 4 5 Input: arr[] = {6, 7, 8, 9, 10, 1
6 min read
Print all repeating adjacent pairs in sorted order from an array
Given an array arr[] consisting of N integers, the task is to print all adjacent integer pairs from the array which appears more than once in the given array. If the array contains more than one such pair, print all pairs in sorted order. Examples: Input: arr[] = {1, 2, 5, 1, 2}Output:1 2Explanation:1 2 is the only repeating integer pair in the arr
7 min read
Find the only positive or only negative number in the given Array
Given an array arr[] of either entirely positive integers or entirely negative integers except for one number. The task is to find that number. Examples: Input: arr[] = {3, 5, 2, 8, -7, 6, 9}Output: -7Explanation: Except -7 all the numbers in arr[] are positive integers. Input: arr[] = {-3, 5, -9}Output: 5 Brute Force Approach: A brute force approa
9 min read
Largest element in the longest Subarray consisting of only Even or only Odd numbers
Given an array arr[] of size N, the task is to find the largest element in the longest subarray consisting only of even numbers or odd numbers. Examples: Input: arr[] = { 2, 4, 6, 9, 10, 11 } Output: 6 Explanation: The longest subarray consisting of only even or odd numbers is { arr[0], arr[1], arr[2] }. Since the largest element of the subarray is
17 min read
Find the first repeating element in an array of integers
Given an array of integers arr[], The task is to find the index of first repeating element in it i.e. the element that occurs more than once and whose index of the first occurrence is the smallest. Examples: Input: arr[] = {10, 5, 3, 4, 3, 5, 6}Output: 5 Explanation: 5 is the first element that repeats Input: arr[] = {6, 10, 5, 4, 9, 120, 4, 6, 10}
22 min read