Majority element in a circular array of 0's and 1's
Last Updated :
31 Aug, 2022
Given a circular array containing only 0’s and 1’s, of size n where n = p*q (p and q are both odd integers). The task is to check if there is a way such that 1 will be in majority after applying the following operations:
- Divide circular array into p subarrays each of size q.
- In each subarray, the number which is in majority will get stored into array B.
- Now, 1 will said to be in majority if it is in majority into array B.
Note: A number is in majority in an array if it occurs more than half times of the size of an array.
Examples:
Input: p = 3, q = 3, array[] = {0, 0, 1, 1, 0, 1, 1, 0, 0}
Output: Yes
Assume index of the array from 1 to N, Since the array is circular so index N and 1 will be adjacent.
Divide this circular array into subarray in this way :-
{2, 3, 4}, {5, 6, 7} and {8, 9, 1}. [These are the index of elements]
In {2, 3, 4}, 1 is in majority,
in {5, 6, 7}, again 1 is in majority and
In {8, 9, 1}, 0 is in majority.
Now insert 1, 1, 0 into array B so array B = {1, 1, 0}
In array B, 1 is the majority element so print Yes.
Input: p = 3, q = 3, array[] = {1, 0, 0, 1, 1, 0, 1, 0, 0}
Output: No
No matter how you divide this circular subarray,
1 will not be in majority. Hence, the answer is No.
Approach:
- First of all, iterate over the circular array and count the total number of 1’s in each of p subarray(of size q).
- Store this number into another array (of size p).
- If in this case, 1 is in majority then, print yes.
- Else take another set by moving the previous set’s index 1 unit either increasing or decreasing it, and keep track of only those indices which are new in given set and update number of 1’s in the array.
- Repeat the 2nd and 3rd step.
We will repeat q times if there is no majority of 1 found until that, the answer would be NO, else ( like in the previous example case ) the answer would be 1.
Since at the maximum, we can repeat this process q times and each time we are tracking only two elements in each of p subarray.
Explanation:
In given example-1, we will divide circular subarray as [indices] => {1, 2, 3}, {4, 5, 6}, {7, 8, 9} and store number of 1’s in another array which are [1, 2, 1] in subarrays respectively.
Taking another set in example 1 by increasing 1 unit so set will be {2, 3, 4}, {5, 6, 7}, {8, 9, 1} now in set 1 only change is inclusion of element 4 and removal of element 1, we will only track these so updated number of 1’s will be 2, 2, 0.
Below is the implementation of above approach:
C++
// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
// Function to check if 1 is the majority
// element or not
void majority(bool a[], int p, int q, int size)
{
// assuming starting and ending index of 1st subarray
int start = 0, ends = q;
// to store majority of p
int arr[p];
// subarrays each of size q ;
int k = 0;
// Loop to calculate total number
// of 1's in subarray which will get
// stored in array arr[]
while (k < p) {
int one = 0;
for (int j = start; j < ends; j++) {
if (a[j] == 1) {
one++;
}
}
// starting index of next subarray
start = ends;
// ending index of next subarray
ends = ends + q;
// storing 1's
arr[k] = one;
k++;
}
start = 0;
ends = q;
// variable to keep a check
// if 1 is in majority or not
bool found = 0;
// In this case, we are repeating
// the task of calculating
// total number of 1's backward
while (ends > 0) {
// to store the total number of 1's
int dist_one = 0;
// Check if 1 is in majority in
// this subarray
for (int i = 0; i < p; i++)
if (arr[i] > q / 2)
dist_one++;
// If 1 is in majority return
if (dist_one > p / 2) {
found = 1;
cout << "Yes" << endl;
return;
}
// shifting starting index of
// subarray by 1 unit leftwards
start--;
// shifting ending index of
// subarray by 1 unit leftwards
ends--;
// to ensure it is a valid index
// ( array is circular) -1 index means
// last index of a circular array
if (start < 0)
start = size + start;
int st = start, en = ends, l = 0;
// now to track changes occur
// due to shifting of the subarray
while (en < size) {
if (a[st % size] != a[en % size]) {
// st refers to starting index of
// new subarray and en refers to
// last element of same subarray
// but in previous iteration
if (a[st % size] == 1)
arr[l]++;
else
arr[l]--;
}
l++;
// now repeating the same
// for other subarrays too
st = (st + q);
en = en + q;
}
}
if (found == 0) {
cout << "No" << endl;
}
}
// Driver code
int main()
{
int p = 3, q = 3;
int n = p * q;
bool a[] = { 0, 0, 1, 1, 0, 1, 1, 0, 0 };
// circular array of given size
majority(a, p, q, n);
return 0;
}
Java
// Java implementation of above approach
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
// Function to check if 1 is the majority
// element or not
static void majority(int a[], int p, int q, int size)
{
// assuming starting and ending index of 1st subarray
int start = 0, ends = q;
// to store majority of p
int []arr = new int[p];
// subarrays each of size q ;
int k = 0;
// Loop to calculate total number
// of 1's in subarray which will get
// stored in array arr[]
while (k < p) {
int one = 0;
for (int j = start; j < ends; j++) {
if (a[j] == 1) {
one++;
}
}
// starting index of next subarray
start = ends;
// ending index of next subarray
ends = ends + q;
// storing 1's
arr[k] = one;
k++;
}
start = 0;
ends = q;
// variable to keep a check
// if 1 is in majority or not
boolean found = false;
// In this case, we are repeating
// the task of calculating
// total number of 1's backward
while (ends > 0) {
// to store the total number of 1's
int dist_one = 0;
// Check if 1 is in majority in
// this subarray
for (int i = 0; i < p; i++)
if (arr[i] > q / 2)
dist_one++;
// If 1 is in majority return
if (dist_one > p / 2) {
found = true;
System.out.println( "Yes" );
return;
}
// shifting starting index of
// subarray by 1 unit leftwards
start--;
// shifting ending index of
// subarray by 1 unit leftwards
ends--;
// to ensure it is a valid index
// ( array is circular) -1 index means
// last index of a circular array
if (start < 0)
start = size + start;
int st = start, en = ends,l = 0;
// now to track changes occur
// due to shifting of the subarray
while (en < size) {
if (a[st % size] != a[en % size]) {
// st refers to starting index of
// new subarray and en refers to
// last element of same subarray
// but in previous iteration
if (a[st % size] == 1)
arr[l]++;
else
arr[l]--;
}
l++;
// now repeating the same
// for other subarrays too
st = (st + q);
en = en + q;
}
}
if (found == false ) {
System.out.println( "No" );
}
}
// Driver code
public static void main(String args[])
{
int p = 3, q = 3;
int n = p * q;
int a[] = { 0, 0, 1, 1, 0, 1, 1, 0, 0 };
// circular array of given size
majority(a, p, q, n);
}
}
Python3
# Python3 implementation of
# above approach
# Function to check if 1 is
# the majority element or not
def majority(a, p, q, size) :
# assuming starting and
# ending index of 1st subarray
start = 0
ends = q
# to store arr = []
arr = [None] * p
# subarrays each of size q
k = 0
# Loop to calculate total number
# of 1's in subarray which
# will get stored in array arr
while (k < p):
one = 0
for j in range(start, ends):
if (a[j] == 1):
one = one + 1
# starting index of
# next subarray
start = ends
# ending index of next
# subarray
ends = ends + q
# storing 1's
arr[k] = one
k = k + 1
start = 0
ends = q
# variable to keep a check
# if 1 is in majority or not
found = 0
# In this case, we are
# repeating the task of
# calculating total number
# of 1's backward
while (ends > 0) :
# to store the total
# number of 1's
dist_one = 0
# Check if 1 is in majority
# in this subarray
for i in range(0, p):
if (arr[i] > q / 2):
dist_one = dist_one + 1
# If 1 is in majority return
if (dist_one > p / 2) :
found = 1
print("Yes")
return
# shifting starting index of
# subarray by 1 unit leftwards
start = start - 1
# shifting ending index
# of subarray by 1 unit
# leftwards
ends = ends - 1
# to ensure it is a valid
# index( array is circular) -1
# index means last index of
# a circular array
if (start < 0):
start = size + start
st = start
en = ends
l = 0
# now to track changes occur
# due to shifting of the
# subarray
while (en < size) :
if (a[st % size] != a[en % size]) :
# st refers to starting index of
# new subarray and en refers to
# last element of same subarray
# but in previous iteration
if (a[st % size] == 1):
arr[l] = arr[l] + 1
else:
arr[l] = arr[l] - 1
l = l + 1
# now repeating the same
# for other subarrays too
st = (st + q)
en = en + q
if (found == 0) :
print("No")
# Driver code
p = 3
q = 3
n = p * q
a = [ 0, 0, 1, 1, 0, 1, 1, 0, 0 ]
# circular array of given size
majority(a, p, q, n)
# This code is contributed
# by Yatin Gupta
C#
// C# implementation of above approach
using System;
class GFG
{
// Function to check if 1 is the
// majority element or not
public static void majority(int[] a, int p,
int q, int size)
{
// assuming starting and ending
// index of 1st subarray
int start = 0, ends = q;
// to store majority of p
int[] arr = new int[p];
// subarrays each of size q ;
int k = 0;
// Loop to calculate total number
// of 1's in subarray which will
// get stored in array arr[]
while (k < p)
{
int one = 0;
for (int j = start; j < ends; j++)
{
if (a[j] == 1)
{
one++;
}
}
// starting index of next subarray
start = ends;
// ending index of next subarray
ends = ends + q;
// storing 1's
arr[k] = one;
k++;
}
start = 0;
ends = q;
// variable to keep a check
// if 1 is in majority or not
bool found = false;
// In this case, we are repeating
// the task of calculating
// total number of 1's backward
while (ends > 0)
{
// to store the total number of 1's
int dist_one = 0;
// Check if 1 is in majority in
// this subarray
for (int i = 0; i < p; i++)
{
if (arr[i] > q / 2)
{
dist_one++;
}
}
// If 1 is in majority return
if (dist_one > p / 2)
{
found = true;
Console.WriteLine("Yes");
return;
}
// shifting starting index of
// subarray by 1 unit leftwards
start--;
// shifting ending index of
// subarray by 1 unit leftwards
ends--;
// to ensure it is a valid index
// ( array is circular) -1 index means
// last index of a circular array
if (start < 0)
{
start = size + start;
}
int st = start, en = ends, l = 0;
// now to track changes occur
// due to shifting of the subarray
while (en < size)
{
if (a[st % size] != a[en % size])
{
// st refers to starting index of
// new subarray and en refers to
// last element of same subarray
// but in previous iteration
if (a[st % size] == 1)
{
arr[l]++;
}
else
{
arr[l]--;
}
}
l++;
// now repeating the same
// for other subarrays too
st = (st + q);
en = en + q;
}
}
if (found == false)
{
Console.WriteLine("No");
}
}
// Driver code
public static void Main(string[] args)
{
int p = 3, q = 3;
int n = p * q;
int[] a = new int[] {0, 0, 1, 1,
0, 1, 1, 0, 0};
// circular array of given size
majority(a, p, q, n);
}
}
// This code is contributed by Shrikant13
PHP
<?php
//PHP implementation of above approach
// Function to check if 1 is the majority
// element or not
function majority($a, $p, $q, $size)
{
// assuming starting and ending index of 1st subarray
$start = 0; $ends = $q;
// to store majority of p
$arr=array(0);
// subarrays each of size q ;
$k = 0;
// Loop to calculate total number
// of 1's in subarray which will get
// stored in array arr[]
while ($k < $p) {
$one = 0;
for ($j = $start; $j < $ends; $j++) {
if ($a[$j] == 1) {
$one++;
}
}
// starting index of next subarray
$start = $ends;
// ending index of next subarray
$ends = $ends + $q;
// storing 1's
$arr[$k] = $one;
$k++;
}
$start = 0;
$ends = $q;
// variable to keep a check
// if 1 is in majority or not
$found = 0;
// In this case, we are repeating
// the task of calculating
// total number of 1's backward
while ($ends > 0) {
// to store the total number of 1's
$dist_one = 0;
// Check if 1 is in majority in
// this subarray
for ($i = 0; $i < $p; $i++)
if ($arr[$i] > $q / 2)
$dist_one++;
// If 1 is in majority return
if ($dist_one > $p / 2) {
$found = 1;
echo "Yes" ,"\n";
return;
}
// shifting starting index of
// subarray by 1 unit leftwards
$start--;
// shifting ending index of
// subarray by 1 unit leftwards
$ends--;
// to ensure it is a valid index
// ( array is circular) -1 index means
// last index of a circular array
if ($start < 0)
$start = $size + $start;
$st = $start; $en = $ends; $l = 0;
// now to track changes occur
// due to shifting of the subarray
while ($en < $size) {
if ($a[$st % $size] != $a[$en % $size]) {
// st refers to starting index of
// new subarray and en refers to
// last element of same subarray
// but in previous iteration
if ($a[$st % $size] == 1)
$arr[$l]++;
else
$arr[$l]--;
}
$l++;
// now repeating the same
// for other subarrays too
$st = ($st + $q);
$en = $en + $q;
}
}
if ($found == 0) {
echo "No" ,"\n";
}
}
// Driver code
$p = 3; $q = 3;
$n = $p * $q;
$a = array( 0, 0, 1, 1, 0, 1, 1, 0, 0 );
// circular array of given size
majority($a, $p, $q, $n);
#This Code is Contributed by ajit
?>
JavaScript
<script>
// Javascript implementation
// of above approach
// Function to check if 1 is the
// majority element or not
function majority(a, p, q, size)
{
// assuming starting and ending
// index of 1st subarray
let start = 0, ends = q;
// to store majority of p
let arr = new Array(p);
arr.fill(0);
// subarrays each of size q ;
let k = 0;
// Loop to calculate total number
// of 1's in subarray which will
// get stored in array arr[]
while (k < p)
{
let one = 0;
for (let j = start; j < ends; j++)
{
if (a[j] == 1)
{
one++;
}
}
// starting index of next subarray
start = ends;
// ending index of next subarray
ends = ends + q;
// storing 1's
arr[k] = one;
k++;
}
start = 0;
ends = q;
// variable to keep a check
// if 1 is in majority or not
let found = false;
// In this case, we are repeating
// the task of calculating
// total number of 1's backward
while (ends > 0)
{
// to store the total number of 1's
let dist_one = 0;
// Check if 1 is in majority in
// this subarray
for (let i = 0; i < p; i++)
{
if (arr[i] > parseInt(q / 2, 10))
{
dist_one++;
}
}
// If 1 is in majority return
if (dist_one > parseInt(p / 2, 10))
{
found = true;
document.write("Yes");
return;
}
// shifting starting index of
// subarray by 1 unit leftwards
start--;
// shifting ending index of
// subarray by 1 unit leftwards
ends--;
// to ensure it is a valid index
// ( array is circular) -1 index means
// last index of a circular array
if (start < 0)
{
start = size + start;
}
let st = start, en = ends, l = 0;
// now to track changes occur
// due to shifting of the subarray
while (en < size)
{
if (a[st % size] != a[en % size])
{
// st refers to starting index of
// new subarray and en refers to
// last element of same subarray
// but in previous iteration
if (a[st % size] == 1)
{
arr[l]++;
}
else
{
arr[l]--;
}
}
l++;
// now repeating the same
// for other subarrays too
st = (st + q);
en = en + q;
}
}
if (found == false)
{
document.write("No");
}
}
let p = 3, q = 3;
let n = p * q;
let a = [0, 0, 1, 1, 0, 1, 1, 0, 0];
// circular array of given size
majority(a, p, q, n);
</script>
Complexity Analysis:
- Time Complexity: O(p*q)
- Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn 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
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA 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
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem