Check if an Array is made up of Subarrays of continuous repetitions of every distinct element
Last Updated :
03 Apr, 2023
Given an array arr[], consisting of N integers, the task is to check whether the entire array is only made up of subarrays such that each subarray consists of consecutive repetitions of a single element and every distinct element in the array is part of such subarray.
Examples:
Input: N = 10, arr[] = {1, 1, 1, 1, 2, 2, 3, 3, 3, 3}
Output: Yes
Explanation:
The given array consists of 3 distinct elements {1, 2, 3} and subarrays {1, 1, 1, 1}, {2, 2}, {3, 3, 3, 3}.
Therefore, the given array satisfies the conditions.
Input: N = 10, arr[] = {1, 1, 1, 2, 2, 2, 2, 1, 3, 3}
Output: No
Explanation:
The given array consists of 3 distinct elements {1, 2, 3} and subarrays {1, 1, 1}, {2, 2, 2, 2}, {1}, {3, 3}.
Since the subarray {1} does not contain any repetition, the given array does not satisfy the conditions.
Approach:
Follow the steps below to solve the problem:
- Initialize a variable curr = 0 to store the size of every subarray of a single repeating element is encountered.
- If any such index is found where arr[i] ? arr[i - 1], check if curr is greater than 1 or not. If so, reset curr to 0 and continue. Otherwise, print “No” as a subarray exists of a single element without repetition.
- Otherwise, increase curr.
- After traversing the array, check if curr is greater than 1 or not. If curr is equal to 1, this ensures that the last element is different from the second last element. Therefore, print “No”.
- Otherwise, print “Yes”.
Below is the implementation of the above approach:
C++
// C++ Program to implement
// the above problem
#include <bits/stdc++.h>
using namespace std;
// Function to check if the
// array is made up of
// subarrays of repetitions
bool ContinuousElements(int a[],
int n)
{
// Base Case
if (n == 1)
return false;
// Stores the size of
// current subarray
int curr = 1;
for (int i = 1; i < n; i++) {
// If a different element
// is encountered
if (a[i] != a[i - 1]) {
// If the previous subarray
// was a single element
if (curr == 1)
return false;
// Reset to new subarray
else
curr = 0;
}
// Increase size of subarray
curr++;
}
// If last element differed from
// the second last element
if (curr == 1)
return false;
return true;
}
// Driver code
int main()
{
int a[] = { 1, 1, 2, 2, 1, 3, 3 };
int n = sizeof(a)
/ sizeof(a[0]);
if (ContinuousElements(a, n))
cout << "Yes" << endl;
else
cout << "No" << endl;
return 0;
}
Java
// Java Program to implement
// the above approach
class GFG{
// Function to check if the
// array is made up of
// subarrays of repetitions
static boolean ContinuousElements(int a[],
int n)
{
// Base Case
if (n == 1)
return false;
// Stores the size of
// current subarray
int curr = 1;
for (int i = 1; i < n; i++)
{
// If a different element
// is encountered
if (a[i] != a[i - 1])
{
// If the previous subarray
// was a single element
if (curr == 1)
return false;
// Reset to new subarray
else
curr = 0;
}
// Increase size of subarray
curr++;
}
// If last element differed from
// the second last element
if (curr == 1)
return false;
return true;
}
// Driver code
public static void main(String[] args)
{
int a[] = { 1, 1, 2, 2, 1, 3, 3 };
int n = a.length;
if (ContinuousElements(a, n))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by rock_cool
Python3
# Python3 program to implement
# the above problem
# Function to check if the
# array is made up of
# subarrays of repetitions
def ContinuousElements(a, n):
# Base Case
if (n == 1):
return False
# Stores the size of
# current subarray
curr = 1
for i in range (1, n):
# If a different element
# is encountered
if (a[i] != a[i - 1]):
# If the previous subarray
# was a single element
if (curr == 1):
return False
# Reset to new subarray
else:
curr = 0
# Increase size of subarray
curr += 1
# If last element differed from
# the second last element
if (curr == 1):
return False
return True
# Driver code
if __name__ == "__main__":
a = [1, 1, 2, 2, 1, 3, 3]
n = len(a)
if (ContinuousElements(a, n)):
print ("Yes")
else:
print ("No")
# This code is contributed by Chitranayal
C#
// C# program to implement
// the above approach
using System;
class GFG{
// Function to check if the
// array is made up of
// subarrays of repetitions
static Boolean ContinuousElements(int []a,
int n)
{
// Base Case
if (n == 1)
return false;
// Stores the size of
// current subarray
int curr = 1;
for(int i = 1; i < n; i++)
{
// If a different element
// is encountered
if (a[i] != a[i - 1])
{
// If the previous subarray
// was a single element
if (curr == 1)
return false;
// Reset to new subarray
else
curr = 0;
}
// Increase size of subarray
curr++;
}
// If last element differed from
// the second last element
if (curr == 1)
return false;
return true;
}
// Driver code
public static void Main(String[] args)
{
int []a = { 1, 1, 2, 2, 1, 3, 3 };
int n = a.Length;
if (ContinuousElements(a, n))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by shivanisinghss2110
JavaScript
<script>
// Javascript program to implement
// the above problem
// Function to check if the
// array is made up of
// subarrays of repetitions
function ContinuousElements(a, n)
{
// Base Case
if (n == 1)
return false;
// Stores the size of
// current subarray
let curr = 1;
for(let i = 1; i < n; i++)
{
// If a different element
// is encountered
if (a[i] != a[i - 1])
{
// If the previous subarray
// was a single element
if (curr == 1)
return false;
// Reset to new subarray
else
curr = 0;
}
// Increase size of subarray
curr++;
}
// If last element differed from
// the second last element
if (curr == 1)
return false;
return true;
}
// Driver code
let a = [ 1, 1, 2, 2, 1, 3, 3 ];
let n = a.length;
if (ContinuousElements(a, n))
document.write("Yes");
else
document.write("No");
// This code is contributed by divyesh072019
</script>
Time Complexity: O(N)
Auxiliary Space: O(1)
New Approach:- Another approach to solving this problem is to use a hash table to keep track of the frequency of each distinct element in the array. Then, we can iterate through the hash table and check if the frequency of any element is not equal to the length of any subarray made up of that element. If such an element exists, then the array is not made up of subarrays of continuous repetitions of every distinct element.
Here's the implementation of this approach:-
C++
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
bool checkSubarrays(int arr[], int n) {
unordered_map<int, int> freq;
// Count frequency of each distinct element
for (int i = 0; i < n; i++) {
freq[arr[i]]++;
}
// Check if frequency of each distinct element
// is equal to the length of any subarray made up
// of that element
for (auto it = freq.begin(); it != freq.end(); it++) {
int elem = it->first;
int count = it->second;
int len = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == elem) {
len++;
} else {
if (len != count) {
return false;
}
len = 0;
}
}
if (len != count) {
return false;
}
}
return true;
}
int main() {
int arr[] = {1, 1, 2, 2, 1, 3, 3};
int n = sizeof(arr) / sizeof(arr[0]);
if (checkSubarrays(arr, n)) {
cout << "Yes\n";
} else {
cout << "No\n";
}
return 0;
}
Java
import java.util.*;
public class Main {
static boolean checkSubarrays(int[] arr, int n)
{
Map<Integer, Integer> freq = new HashMap<>();
// Count frequency of each distinct element
for (int i = 0; i < n; i++) {
freq.put(arr[i],
freq.getOrDefault(arr[i], 0) + 1);
}
// Check if frequency of each distinct element
// is equal to the length of any subarray made up
// of that element
for (Map.Entry<Integer, Integer> entry :
freq.entrySet()) {
int elem = entry.getKey();
int count = entry.getValue();
int len = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == elem) {
len++;
}
else {
if (len != count) {
return false;
}
len = 0;
}
}
if (len != count) {
return false;
}
}
return true;
}
public static void main(String[] args)
{
int[] arr = { 1, 1, 2, 2, 1, 3, 3 };
int n = arr.length;
if (checkSubarrays(arr, n)) {
System.out.println("Yes");
}
else {
System.out.println("No");
}
}
}
JavaScript
function checkSubarrays(arr, n) {
const freq = new Map();
// Count frequency of each distinct element
for (let i = 0; i < n; i++) {
freq.set(arr[i], (freq.get(arr[i]) || 0) + 1);
}
// Check if frequency of each distinct element
// is equal to the length of any subarray made up
// of that element
for (const [elem, count] of freq.entries()) {
let len = 0;
for (let i = 0; i < n; i++) {
if (arr[i] === elem) {
len++;
} else {
if (len !== count) {
return false;
}
len = 0;
}
}
if (len !== count) {
return false;
}
}
return true;
}
const arr = [1, 1, 2, 2, 1, 3, 3];
const n = arr.length;
if (checkSubarrays(arr, n)) {
console.log("Yes");
} else {
console.log("No");
}
C#
using System;
using System.Collections.Generic;
public class Program {
public static bool CheckSubarrays(int[] arr, int n)
{
Dictionary<int, int> freq
= new Dictionary<int, int>();
// Count frequency of each distinct element
for (int i = 0; i < n; i++) {
if (!freq.ContainsKey(arr[i])) {
freq[arr[i]] = 1;
}
else {
freq[arr[i]]++;
}
}
// Check if frequency of each distinct element
// is equal to the length of any subarray made up
// of that element
foreach(var item in freq)
{
int elem = item.Key;
int count = item.Value;
int len = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == elem) {
len++;
}
else {
if (len != count) {
return false;
}
len = 0;
}
}
if (len != count) {
return false;
}
}
return true;
}
public static void Main()
{
int[] arr = { 1, 1, 2, 2, 1, 3, 3 };
int n = arr.Length;
if (CheckSubarrays(arr, n)) {
Console.WriteLine("Yes");
}
else {
Console.WriteLine("No");
}
}
}
Python3
def checkSubarrays(arr, n):
freq = {}
# Count frequency of each distinct element
for i in range(n):
if arr[i] in freq:
freq[arr[i]] += 1
else:
freq[arr[i]] = 1
# Check if frequency of each distinct element
# is equal to the length of any subarray made up
# of that element
for elem, count in freq.items():
length = 0
for i in range(n):
if arr[i] == elem:
length += 1
else:
if length != count:
return False
length = 0
if length != count:
return False
return True
arr = [1, 1, 2, 2, 1, 3, 3]
n = len(arr)
if checkSubarrays(arr, n):
print("Yes")
else:
print("No")
Output:-
No
Time Complexity: O(n^2), where n is the length of the input array. This is because we are iterating over each distinct element in the array and then checking the length of all subarrays made up of that element. In the worst case, each element could be distinct, and there could be n such elements, leading to a time complexity of O(n^2).
Auxiliary Space: O(n), where n is the length of the input array. This is because we are using an unordered map to store the frequency of each distinct element, which can have at most n entries. Additionally, we are using a variable len to keep track of the length of the current subarray, which could be at most n. Therefore, the total space complexity is O(n + n) = O(n).
Similar Reads
Check if an array contains only one distinct element
Given an array arr[] of size N, the task is to check if the array contains only one distinct element or not. If it contains only one distinct element then print âYesâ, otherwise print âNoâ. Examples: Input: arr[] = {3, 3, 4, 3, 3} Output: No Explanation: There are 2 distinct elements present in the
8 min read
Check if an array can be split into K consecutive non-overlapping subarrays of length M consisting of single distinct element
Given two integers M and K and an array arr[] consisting of N positive integers, the task is to check if the array can be split into K consecutive non-overlapping subarrays of length M such that each subarray consists of a single distinct element. If found to be true, then print "Yes". Otherwise, pr
8 min read
Maximum sum of K-length subarray consisting of same number of distinct elements as the given array
Given an array arr[] consisting of N integers and an integer K, the task is to find a subarray of size K with maximum sum and count of distinct elements same as that of the original array. Examples: Input: arr[] = {7, 7, 2, 4, 2, 7, 4, 6, 6, 6}, K = 6Output: 31Explanation: The given array consists o
15+ min read
Maximum length of subarray consisting of same type of element on both halves of sub-array
Given an array arr[] of N integers, the task is to find the maximum length of sub-array consisting of the same type of element on both halves of the sub-array. Also, the elements on both halves differ from each other. Examples: Input: arr[] = {2, 3, 4, 4, 5, 5, 6, 7, 8, 10}Output: 4Explanation:{2, 3
8 min read
Find sum of non-repeating (distinct) elements in an array
Given an integer array with repeated elements, the task is to find the sum of all distinct elements in the array.Examples: Input : arr[] = {12, 10, 9, 45, 2, 10, 10, 45,10};Output : 78Here we take 12, 10, 9, 45, 2 for sumbecause it's distinct elements Input : arr[] = {1, 10, 9, 4, 2, 10, 10, 45 , 4}
14 min read
Count subarrays having a single distinct element that can be obtained from a given array
Given an array arr[] of size N, the task is to count the number of subarrays consisting of a single distinct element that can be obtained from a given array. Examples: Input: N = 4, arr[] = { 2, 2, 2, 2 }Output: 7Explanation: All such subarrays {{2}, {2}, {2}, {2}, {2, 2}, {2, 2, 2}, {2, 2, 2, 2}}.
5 min read
Count of subarrays which forms a permutation from given Array elements
Given an array A[] consisting of integers [1, N], the task is to count the total number of subarrays of all possible lengths x (1 ? x ? N), consisting of a permutation of integers [1, x] from the given array. Examples: Input: A[] = {3, 1, 2, 5, 4} Output: 4 Explanation: Subarrays forming a permutati
6 min read
Count subarrays having total distinct elements same as original array
Given an array of n integers. Count the total number of sub-arrays having total distinct elements, the same as that of the total distinct elements of the original array. Examples: Input : arr[] = {2, 1, 3, 2, 3} Output : 5 Total distinct elements in array is 3 Total sub-arrays that satisfy the condi
11 min read
Construct an Array having K Subarrays with all distinct elements
Given integers N and K, the task is to construct an array arr[] of size N using numbers in the range [1, N] such that it has K sub-arrays whose all the elements are distinct. Note: If there are multiple possible answers return any of them. Examples: Input: N = 5, K = 8Output: {1, 2, 3, 3, 3}Explanat
7 min read
Check if concatenation of any permutation of given list of arrays generates the given array
Given an array arr[] of N distinct integers and a list of arrays pieces[] of distinct integers, the task is to check if the given list of arrays can be concatenated in any order to obtain the given array. If it is possible, then print "Yes". Otherwise, print "No". Examples: Input: arr[] = {1, 2, 4,
9 min read