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
Smallest subarray with positive sum for all indices
Given an array arr[] of size N. The task is to determine the minimum length of a subarray starting from index i, such that the sum of the subarray is strictly greater than 0. Calculate the length for all i's in the range 1 to N. If no such subarray exists, then return 0. Examples: Input: N = 3, arr[
8 min read
Smallest Subarray with Sum K from an Array
Given an array arr[] consisting of N integers, the task is to find the length of the Smallest subarray with a sum equal to K. Examples: Input: arr[] = {2, 4, 6, 10, 2, 1}, K = 12 Output: 2 Explanation: All possible subarrays with sum 12 are {2, 4, 6} and {10, 2}. Input: arr[] = {-8, -8, -3, 8}, K =
10 min read
Smallest Subarray to be Sorted to make the whole array sorted
Given an unsorted array arr[]. Find the subarray arr[s...e] such that sorting this subarray makes the whole array sorted.Note: If the given array is already sorted then return [0, 0].Examples:Input: arr[] = [10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60]Output: [3, 8]Explanation: Sorting subarray start
15+ min read
Count subarrays for every array element in which they are the minimum | Set 2
Given an array arr[] consisting of N integers, the task is to create an array brr[] of size N where brr[i] represents the count of subarrays in which arr[i] is the smallest element. Examples: Input: arr[] = {3, 2, 4}Output: {1, 3, 1}Explanation: For arr[0], there is only one subarray in which 3 is t
12 min read
Length of smallest subarray to be removed such that the remaining array is sorted
Given an array arr[] consisting of N integers, the task is to print the length of the smallest subarray to be removed from arr[] such that the remaining array is sorted. Examples: Input: arr[] = {1, 2, 3, 10, 4, 2, 3, 5}Output: 3Explanation:The smallest subarray to be remove is {10, 4, 2} of length
8 min read
Longest increasing subsequence which forms a subarray in the sorted representation of the array
Given an array arr[] of N integers, the task is to find the length of the longest increasing subsequence such that it forms a subarray when the original array is sorted. Examples: Input: arr[] = { 2, 6, 4, 8, 2, 9 }Output: 3Explanation: Sorted array: {2, 2, 4, 6, 8, 9}All possible non-decreasing seq
11 min read
Length of smallest Subarray with at least one element repeated K times
Given an array arr[] of length N and an integer K. The task is to find the minimum length of subarray such that at least one element of the subarray is repeated exactly K times in that subarray. If no such subarray exists, print -1. Examples: Input: arr[] = {1, 2, 1, 2, 1}, K = 2Output: 3Explanation
9 min read
Find the smallest subarray having atleast one duplicate
Given an array arr of N elements, the task is to find the length of the smallest subarray of the given array that contains at least one duplicate element. A subarray is formed from consecutive elements of an array. If no such array exists, print "-1".Examples: Input: arr = {1, 2, 3, 1, 5, 4, 5} Outp
8 min read
Print n smallest elements from given array in their original order
We are given an array of m-elements, we need to find n smallest elements from the array but they must be in the same order as they are in given array. Examples: Input : arr[] = {4, 2, 6, 1, 5}, n = 3 Output : 4 2 1 Explanation : 1, 2 and 4 are 3 smallest numbers and 4 2 1 is their order in given arr
5 min read
Count subarrays for every array element in which they are the minimum
Given an array arr[] consisting of N integers, the task is to create an array brr[] of size N where brr[i] represents the count of subarrays in which arr[i] is the smallest element. Examples: Input: arr[] = {3, 2, 4} Output: {1, 3, 1} Explanation: For arr[0], there is only one subarray in which 3 is
15+ min read