Find any one of the multiple repeating elements in read only array
Last Updated :
24 Mar, 2023
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
arr[] = {10, 1, 2, 3, 5, 4, 9, 8, 5, 6, 4}
Output : One of the numbers repeated in the array is: 4 OR 5
Method 1: Since the size of the array is n+1 and elements range from 1 to n then it is confirmed that there will be at least one repeating element. A simple solution is to create a count array and store counts of all elements. As soon as we encounter an element with a count of more than 1, we return it.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findRepeatingNumber( const int arr[], int n)
{
for ( int i = 0; i < n; i++) {
int count = 0;
for ( int j = 0; j < n; j++) {
if (arr[i] == arr[j])
count++;
}
if (count > 1)
return arr[i];
}
return -1;
}
int main()
{
const int arr[] = { 1, 1, 2, 3, 5, 4 };
int n = 5;
cout << "One of the numbers repeated in"
" the array is: "
<< findRepeatingNumber(arr, n) << endl;
}
|
Java
public class GFG {
public static int findRepeatingNumber( int [] arr, int n)
{
for ( int i = 0 ; i < n; i++) {
int count = 0 ;
for ( int j = 0 ; j < n; j++) {
if (arr[i] == arr[j]) {
count++;
}
}
if (count > 1 ) {
return arr[i];
}
}
return - 1 ;
}
public static void main(String[] args)
{
final int [] arr = { 1 , 1 , 2 , 3 , 5 , 4 };
int n = 5 ;
System.out.print( "One of the numbers repeated in"
+ " the array is: " );
System.out.print(findRepeatingNumber(arr, n));
System.out.print( "\n" );
}
}
|
Python3
from math import sqrt
def findRepeatingNumber(arr, n):
for i in arr:
count = 0 ;
for j in arr:
if i = = j:
count = count + 1
if (count> 1 ):
return i
return - 1
if __name__ = = '__main__' :
arr = [ 1 , 1 , 2 , 3 , 5 , 4 ]
n = 5
print ( "One of the numbers repeated in the array is:" ,
findRepeatingNumber(arr, n))
|
C#
using System;
public class GFG {
public static int findRepeatingNumber( int [] arr, int n)
{
for ( int i = 0; i < n; i++) {
int count = 0;
for ( int j = 0; j < n; j++) {
if (arr[i] == arr[j]) {
count++;
}
}
if (count > 1) {
return arr[i];
}
}
return -1;
}
public static void Main(String[] args)
{
int [] arr = { 1, 1, 2, 3, 5, 4 };
int n = 5;
Console.Write( "One of the numbers repeated in"
+ " the array is: " );
Console.Write(findRepeatingNumber(arr, n));
Console.Write( "\n" );
}
}
|
Javascript
<script>
function findRepeatingNumber(arr, n){
for (let i = 0; i < n; i++) {
let count = 0;
for (let j = 0; j < n; j++) {
if (arr[i] == arr[j]) {
count++;
}
}
if (count > 1) {
return arr[i];
}
}
return -1;
}
const arr = [ 1, 1, 2, 3, 5, 4 ];
let n = 5;
document.write( "One of the numbers repeated in the array is: " + findRepeatingNumber(arr, n));
</script>
|
Output
One of the numbers repeated in the array is: 1
Time Complexity: O(n2)
Auxiliary Space: O(1)
A space-optimized solution is to break the given range (from 1 to n) into blocks of size equal to sqrt(n). We maintain the count of elements belonging to each block for every block. Now as the size of an array is (n+1) and blocks are of size sqrt(n), then there will be one such block whose size will be more than sqrt(n). For the block whose count is greater than sqrt(n), we can use hashing for the elements of this block to find which element appears more than once.
Explanation:
The method described above works because of the following two reasons:
- There would always be a block that has a count greater than sqrt(n) because of one extra element. Even when one extra element has been added it will occupy a position in one of the blocks only, making that block to be selected.
- The selected block definitely has a repeating element. Consider that ith block is selected. The size of the block is greater than sqrt(n) (Hence, it is selected) Maximum distinct elements in this block = sqrt(n). Thus, size can be greater than sqrt(n) only if there is a repeating element in range ( i*sqrt(n), (i+1)*sqrt(n) ].
Note: The last block formed may or may not have a range equal to sqrt(n). Thus, checking if this block has a repeating element will be different than other blocks. However, this difficulty can be overcome from the implementation point of view by initializing the selected block with the last block. This is safe because at least one block has to get selected.
Below is the step-by-step algorithm to solve this problem:
- Divide the array into blocks of size sqrt(n).
- Make a count array that stores the count of elements for each block.
- Pick up the block which has a count of more than sqrt(n), setting the last block
as default.
- For the elements belonging to the selected block, use the method of hashing(explained in the next step) to find the repeating element in that block.
- We can create a hash array of key-value pairs, where the key is the element in the block and the value is the count of a number of times the given key is appearing. This can be easily implemented using unordered_map in C++ STL.
Below is the implementation of the above idea:
C++
#include <bits/stdc++.h>
using namespace std;
int findRepeatingNumber( const int arr[], int n)
{
int sq = sqrt (n);
int range = (n / sq) + 1;
int count[range] = {0};
for ( int i = 0; i <= n; i++)
{
count[(arr[i] - 1) / sq]++;
}
int selected_block = range - 1;
for ( int i = 0; i < range - 1; i++)
{
if (count[i] > sq)
{
selected_block = i;
break ;
}
}
unordered_map< int , int > m;
for ( int i = 0; i <= n; i++)
{
if ( ((selected_block * sq) < arr[i]) &&
(arr[i] <= ((selected_block + 1) * sq)))
{
m[arr[i]]++;
if (m[arr[i]] > 1)
return arr[i];
}
}
return -1;
}
int main()
{
const int arr[] = { 1, 1, 2, 3, 5, 4 };
int n = 5;
cout << "One of the numbers repeated in"
" the array is: "
<< findRepeatingNumber(arr, n) << endl;
}
|
Java
import java.io.*;
import java.util.*;
class GFG
{
static int findRepeatingNumber( int [] arr, int n)
{
int sq = ( int ) Math.sqrt(n);
int range = (n / sq) + 1 ;
int [] count = new int [range];
for ( int i = 0 ; i <= n; i++)
{
count[(arr[i] - 1 ) / sq]++;
}
int selected_block = range - 1 ;
for ( int i = 0 ; i < range - 1 ; i++)
{
if (count[i] > sq)
{
selected_block = i;
break ;
}
}
HashMap<Integer, Integer> m = new HashMap<>();
for ( int i = 0 ; i <= n; i++)
{
if ( ((selected_block * sq) < arr[i]) &&
(arr[i] <= ((selected_block + 1 ) * sq)))
{
m.put(arr[i], 1 );
if (m.get(arr[i]) == 1 )
return arr[i];
}
}
return - 1 ;
}
public static void main(String args[])
{
int [] arr = { 1 , 1 , 2 , 3 , 5 , 4 };
int n = 5 ;
System.out.println( "One of the numbers repeated in the array is: " +
findRepeatingNumber(arr, n));
}
}
|
Python3
from math import sqrt
def findRepeatingNumber(arr, n):
sq = sqrt(n)
range__ = int ((n / sq) + 1 )
count = [ 0 for i in range (range__)]
for i in range ( 0 , n + 1 , 1 ):
count[ int ((arr[i] - 1 ) / sq)] + = 1
selected_block = range__ - 1
for i in range ( 0 , range__ - 1 , 1 ):
if (count[i] > sq):
selected_block = i
break
m = {i: 0 for i in range (n)}
for i in range ( 0 , n + 1 , 1 ):
if (((selected_block * sq) < arr[i]) and
(arr[i] < = ((selected_block + 1 ) * sq))):
m[arr[i]] + = 1
if (m[arr[i]] > 1 ):
return arr[i]
return - 1
if __name__ = = '__main__' :
arr = [ 1 , 1 , 2 , 3 , 5 , 4 ]
n = 5
print ( "One of the numbers repeated in the array is:" ,
findRepeatingNumber(arr, n))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int findRepeatingNumber( int [] arr, int n)
{
int sq = ( int ) Math.Sqrt(n);
int range = (n / sq) + 1;
int [] count = new int [range];
for ( int i = 0; i <= n; i++)
{
count[(arr[i] - 1) / sq]++;
}
int selected_block = range - 1;
for ( int i = 0; i < range - 1; i++)
{
if (count[i] > sq)
{
selected_block = i;
break ;
}
}
Dictionary< int , int > m = new Dictionary< int , int >();
for ( int i = 0; i <= n; i++)
{
if ( ((selected_block * sq) < arr[i]) &&
(arr[i] <= ((selected_block + 1) * sq)))
{
m.Add(arr[i], 1);
if (m[arr[i]] == 1)
return arr[i];
}
}
return -1;
}
public static void Main(String []args)
{
int [] arr = { 1, 1, 2, 3, 5, 4 };
int n = 5;
Console.WriteLine( "One of the numbers repeated in the array is: " +
findRepeatingNumber(arr, n));
}
}
|
Javascript
<script>
function findRepeatingNumber(arr, n) {
let sq = Math.sqrt(n);
let range = Math.floor(n / sq) + 1;
let count = new Array(range).fill(0);
for (let i = 0; i <= n; i++) {
count[(Math.floor((arr[i] - 1) / sq))]++;
}
let selected_block = range - 1;
for (let i = 0; i < range - 1; i++) {
if (count[i] > sq) {
selected_block = i;
break ;
}
}
let m = new Map();
for (let i = 0; i <= n; i++) {
if (((selected_block * sq) < arr[i]) &&
(arr[i] <= ((selected_block + 1) * sq))) {
m[arr[i]]++;
if (m.has(arr[i])) {
m.set(arr[i], m.get(arr[i]) + 1)
} else {
m.set(arr[i], 1)
}
if (m.get(arr[i]) > 1)
return arr[i];
}
}
return -1;
}
const arr = [1, 1, 2, 3, 5, 4];
let n = 5;
document.write( "One of the numbers repeated in"
+ " the array is: "
+ findRepeatingNumber(arr, n) + "<br>" );
</script>
|
Output
One of the numbers repeated in the array is: 1
Time Complexity: O(N)
Auxiliary Space: sqrt(N)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
13 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. How do
14 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high. We sort the array using multiple passes. After the fi
8 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Conditions to apply Binary Search Algorithm in a Data S
15+ min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted. First we find the smallest element a
8 min read
Sorting Algorithms
A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read