Smallest subarray which upon repetition gives the original array
Last Updated :
11 Jul, 2022
Given an array arr[] of N integers, the task is to find the smallest subarray brr[] of size at least 2 such that by performing repeating operation on the array brr[] gives the original array arr[]. Print "-1" if it is not possible to find such a subarray.
A repeating operation on an array is to append all the current element of the array to the same array again.
For Example, if an array arr[] = {1, 2} then on repeating operation array becomes {1, 2, 1, 2}.
Examples:
Input: arr[] = {1, 2, 3, 3, 1, 2, 3, 3}
Output: {1, 2, 3, 3}
Explanation:
{1, 2, 3, 3} is the smallest subarray which when repeated 2 times gives the original array {1, 2, 3, 3, 1, 2, 3, 3}
Input: arr[] = {1, 1, 6, 1, 1, 7}
Output: -1
Explanation:
There doesn't exist any subarray.
Naive Approach: The idea is to generate all possible subarrays of length at least 2 and check whether repeating those subarrays gives the original array or not.
Time Complexity: O(N3)
Auxiliary Space: O(N)
Efficient Approach: The above approach can be optimized by observing the fact that the resultant subarray brr[] must start from the 1st index of the original array to generate arr[] on repeat. Therefore, generate only those subarrays which start from the 1st index and have a length of at least 2 and check whether repeating those subarrays gives the original array or not. Below are the steps:
- Create an auxiliary array brr[] and insert the first two elements of the original array into it as the resulting array must be of at least two in size.
- Traverse over the possible length of subarray [2, N/2 + 1] and check if the array brr[] of length i on repeating gives the original array arr[] or not.
- If yes then print this subarray and break the loop.
- Otherwise, insert the current element into the subarray and check again.
- Repeat the above steps until all the subarrays are checked.
- Print "-1" if the array brr[] is not found.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <iostream>
#include <vector>
using namespace std;
// Function to print the array
void printArray(vector<int>& brr)
{
for (auto& it : brr) {
cout << it << ' ';
}
}
// Function to find the smallest subarray
void RepeatingSubarray(int arr[], int N)
{
// Corner Case
if (N < 2) {
cout << "-1";
}
// Initialize the auxiliary subarray
vector<int> brr;
// Push the first 2 elements into
// the subarray brr[]
brr.push_back(arr[0]);
brr.push_back(arr[1]);
// Iterate over the length of
// subarray
for (int i = 2; i < N / 2 + 1; i++) {
// If array can be divided into
// subarray of i equal length
if (N % i == 0) {
bool a = false;
int n = brr.size();
int j = i;
// Check if on repeating the
// current subarray gives the
// original array or not
while (j < N) {
int K = j % i;
if (arr[j] == brr[K]) {
j++;
}
else {
a = true;
break;
}
}
// Subarray found
if (!a && j == N) {
printArray(brr);
return;
}
}
// Add current element into
// subarray
brr.push_back(arr[i]);
}
// No subarray found
cout << "-1";
return;
}
// Driver Code
int main()
{
int arr[] = { 1, 2, 2, 1, 2,
2, 1, 2, 2 };
int N = sizeof(arr) / sizeof(arr[0]);
// Function call
RepeatingSubarray(arr, N);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to print the array
static void printArray(Vector<Integer> brr)
{
for(int it : brr)
{
System.out.print(it + " ");
}
}
// Function to find the smallest subarray
static void RepeatingSubarray(int arr[], int N)
{
// Corner Case
if (N < 2)
{
System.out.print("-1");
}
// Initialize the auxiliary subarray
Vector<Integer> brr = new Vector<Integer>();
// Push the first 2 elements into
// the subarray brr[]
brr.add(arr[0]);
brr.add(arr[1]);
// Iterate over the length of
// subarray
for(int i = 2; i < N / 2 + 1; i++)
{
// If array can be divided into
// subarray of i equal length
if (N % i == 0)
{
boolean a = false;
int n = brr.size();
int j = i;
// Check if on repeating the
// current subarray gives the
// original array or not
while (j < N)
{
int K = j % i;
if (arr[j] == brr.get(K))
{
j++;
}
else
{
a = true;
break;
}
}
// Subarray found
if (!a && j == N)
{
printArray(brr);
return;
}
}
// Add current element into
// subarray
brr.add(arr[i]);
}
// No subarray found
System.out.print("-1");
return;
}
// Driver Code
public static void main(String[] args)
{
int arr[] = { 1, 2, 2, 1, 2,
2, 1, 2, 2 };
int N = arr.length;
// Function call
RepeatingSubarray(arr, N);
}
}
// This code is contributed by Amit Katiyar
Python3
# Python3 program for the above approach
# Function to print the array
def printArray(brr):
for it in brr:
print(it, end = ' ')
# Function to find the smallest subarray
def RepeatingSubarray(arr, N):
# Corner Case
if (N < 2):
print("-1")
# Initialize the auxiliary subarray
brr = []
# Push the first 2 elements into
# the subarray brr[]
brr.append(arr[0])
brr.append(arr[1])
# Iterate over the length of
# subarray
for i in range(2, N // 2 + 1):
# If array can be divided into
# subarray of i equal length
if (N % i == 0):
a = False
n = len(brr)
j = i
# Check if on repeating the
# current subarray gives the
# original array or not
while (j < N):
K = j % i
if (arr[j] == brr[K]):
j += 1
else:
a = True
break
# Subarray found
if (not a and j == N):
printArray(brr)
return
# Add current element into
# subarray
brr.append(arr[i])
# No subarray found
print("-1")
return
# Driver Code
if __name__ =="__main__":
arr = [ 1, 2, 2, 1, 2,
2, 1, 2, 2 ]
N = len(arr)
# Function call
RepeatingSubarray(arr, N)
# This code is contributed by chitranayal
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to print the array
static void printArray(List<int> brr)
{
foreach(int it in brr)
{
Console.Write(it + " ");
}
}
// Function to find the smallest subarray
static void RepeatingSubarray(int []arr, int N)
{
// Corner Case
if (N < 2)
{
Console.Write("-1");
}
// Initialize the auxiliary subarray
List<int> brr = new List<int>();
// Push the first 2 elements into
// the subarray brr[]
brr.Add(arr[0]);
brr.Add(arr[1]);
// Iterate over the length of
// subarray
for(int i = 2; i < N / 2 + 1; i++)
{
// If array can be divided into
// subarray of i equal length
if (N % i == 0)
{
bool a = false;
int n = brr.Count;
int j = i;
// Check if on repeating the
// current subarray gives the
// original array or not
while (j < N)
{
int K = j % i;
if (arr[j] == brr[K])
{
j++;
}
else
{
a = true;
break;
}
}
// Subarray found
if (!a && j == N)
{
printArray(brr);
return;
}
}
// Add current element into
// subarray
brr.Add(arr[i]);
}
// No subarray found
Console.Write("-1");
return;
}
// Driver Code
public static void Main(String[] args)
{
int []arr = {1, 2, 2, 1,
2, 2, 1, 2, 2};
int N = arr.Length;
// Function call
RepeatingSubarray(arr, N);
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// JavaScript program for the above approach
// Function to print the array
function printArray(brr)
{
for (let it of brr) {
document.write(it + ' ');
}
}
// Function to find the smallest subarray
function RepeatingSubarray(arr, N)
{
// Corner Case
if (N < 2) {
document.write("-1");
}
// Initialize the auxiliary subarray
let brr = [];
// Push the first 2 elements into
// the subarray brr[]
brr.push(arr[0]);
brr.push(arr[1]);
// Iterate over the length of
// subarray
for (let i = 2; i < Math.floor(N / 2) + 1; i++) {
// If array can be divided into
// subarray of i equal length
if (N % i == 0) {
let a = false;
let n = brr.length;
let j = i;
// Check if on repeating the
// current subarray gives the
// original array or not
while (j < N) {
let K = j % i;
if (arr[j] == brr[K]) {
j++;
}
else {
a = true;
break;
}
}
// Subarray found
if (!a && j == N) {
printArray(brr);
return;
}
}
// Add current element into
// subarray
brr.push(arr[i]);
}
// No subarray found
document.write("-1");
return;
}
// Driver Code
let arr = [ 1, 2, 2, 1, 2,
2, 1, 2, 2 ];
let N = arr.length;
// Function call
RepeatingSubarray(arr, N);
// This code is contributed by Surbhi Tyagi.
</script>
Time Complexity: O(N2)
Auxiliary Space: O(N)
Related Topic: Subarrays, Subsequences, and Subsets in Array
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
12 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. Merge
14 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 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
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 fir
8 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
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). Binary Search AlgorithmConditions to apply Binary Searc
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
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read