Micheal  Block

Micheal Block

1598709600

Count of Rectangles with area K made up of only 1s from given Binary Arrays

Given two binary arrays A[] and B[], of length N and M respectively, the task is to find the number of rectangles of area K consisting of 1‘s in the matrix C[][] generated by multiplying the two arrays such that, **C[i][j] = A[i] * B[j] **( 1 < i < n, 1 < j < m).

Examples:

Input:_ N= 3, M = 3, A[] = {1, 1, 0}, B[] = {0, 1, 1}, K = 2_

Output:_ 4_

Explanation:_ C[][] = {{0, 1, 1}, {0, 1, 1}, {0, 0, 0}}_

0 1 1        0 1 1      0 1 1       0 1 1
0 1 1        0 1 1      0 1 1       0 1 1
0 0 0        0 0 0      0 0 0       0 0 0

Therefore, there are 4 possible rectangles of area 2 from the matrix.

Input:_ N = 4, M = 2, A[] = {0, 0, 1, 1}, B[] = {1, 0, 1}, K = 2_

Output:_ 2_

Explanation:_ C[][] = {{0, 0, 0}, {0, 0, 0}, {1, 0, 1}, {1, 0, 1}}_

0 0 0        0 0 0
0 0 0        0 0 0
1 0 1        1 0 1
1 0 1        1 0 1

Therefore, there are 2 possible rectangles of area 2 in the matrix.

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

**Naive Approach: **The simplest approach to solve the problem is to generate the required matrix by multiplying the two arrays and for every possible rectangle of area **K, **check if it consists of only 1’s or not…

Time Complexity:_ O(N * M * K)_

Auxiliary Space:_ O(N * M)_

**Efficient Approach: **To optimize the above approach, the following observations need to be made instead of generating the matrix:

  • _The __area of a rectangle is equal to the product of its __length __and _breadth.
  • _Using this property, visualize the rectangle as a submatrix which contains only _1s. Therefore, this submatrix is the result of the product of two subarrays of length a, b where a * b = K.
  • Since the submatrix contains only 1‘s, it is obvious that these two subarrays also contain only 1‘s in them.

Therefore, the problem reduces to finding the subarrays consisting of only 1‘s of all possible lengths which are proper divisors of K, from the arrays A[] and B[]. Follow the steps below to solve the problem:

  • Precalculate the count of possible subarrays.
  • Iterate through all the divisors of K and for each possible pair (p, q) where p * q = K, check if there exist subarrays of length p, q in A[] and B[].
  • Increase the count of possible such subarrays accordingly and finally, print the obtained count.

Below is the implementation of the above approach:

  • C++

// C++ Program to implement

// the above approach

#include <bits/stdc++.h>

**using** **namespace** std;

// Function to find the subarrays of

// all possible lengths made up of only 1s

vector<``**int**``> findSubarrays(vector<``**int**``>& a)

{

**int** n = a.size();

// Stores the frequency

// of the subarrays

vector<``**int**``> freq(n + 1);

**int** count = 0;

**for** (``**int** i = 0; i < n; i++) {

**if** (a[i] == 0) {

// Check if the previous

// value was also 0

**if** (count == 0)

**continue**``;

// If the previous value was 1

**else** {

**int** value = count;

**for** (``**int** j = 1; j <= count; j++) {

// Find the subarrays of

// each size from 1 to count

freq[j] += value;

value--;

}

count = 0;

}

}

**else**

count++;

}

// If A[] is of the form ....111

**if** (count > 0) {

**int** value = count;

**for** (``**int** j = 1; j <= count; j++) {

freq[j] += value;

value--;

}

}

**return** freq;

}

// Function to find the count

// of all possible rectangles

**void** countRectangles(vector<``**int**``>& a,

vector<``**int**``>& b, **int** K)

{

// Size of each of the arrays

**int** n = a.size();

**int** m = b.size();

// Stores the count of subarrays

// of each size consisting of

// only 1s from array A[]

vector<``**int**``> subA

= findSubarrays(a);

// Stores the count of subarrays

// of each size consisting of

// only 1s from array B[]

vector<``**int**``> subB

= findSubarrays(b);

**int** total = 0;

// Iterating over all subarrays

// consisting of only 1s in A[]

**for** (``**int** i = 1; i < subA.size(); i++) {

// If i is a factor of K, then

// there is a subarray of size K/i in B[]

**if** (K % i == 0 and (K / i) <= m) {

total = total + subA[i] * subB[K / i];

}

}

cout << total;

}

// Driver Code

**int** main()

{

vector<``**int**``> a = { 0, 0, 1, 1 };

vector<``**int**``> b = { 1, 0, 1 };

**int** K = 2;

countRectangles(a, b, K);

**return** 0;

}

Output:

2

Time Complexity:_ O(D) * O(N + M), where D is the number of divisors of K._

Auxiliary Space:_ O(N + M)_

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#arrays #geometric #mathematical #matrix #searching #area-volume-programs #binary-representation #square-rectangle #subarray #submatrix

What is GEEK

Buddha Community

Count of Rectangles with area K made up of only 1s from given Binary Arrays
Micheal  Block

Micheal Block

1598709600

Count of Rectangles with area K made up of only 1s from given Binary Arrays

Given two binary arrays A[] and B[], of length N and M respectively, the task is to find the number of rectangles of area K consisting of 1‘s in the matrix C[][] generated by multiplying the two arrays such that, **C[i][j] = A[i] * B[j] **( 1 < i < n, 1 < j < m).

Examples:

Input:_ N= 3, M = 3, A[] = {1, 1, 0}, B[] = {0, 1, 1}, K = 2_

Output:_ 4_

Explanation:_ C[][] = {{0, 1, 1}, {0, 1, 1}, {0, 0, 0}}_

0 1 1        0 1 1      0 1 1       0 1 1
0 1 1        0 1 1      0 1 1       0 1 1
0 0 0        0 0 0      0 0 0       0 0 0

Therefore, there are 4 possible rectangles of area 2 from the matrix.

Input:_ N = 4, M = 2, A[] = {0, 0, 1, 1}, B[] = {1, 0, 1}, K = 2_

Output:_ 2_

Explanation:_ C[][] = {{0, 0, 0}, {0, 0, 0}, {1, 0, 1}, {1, 0, 1}}_

0 0 0        0 0 0
0 0 0        0 0 0
1 0 1        1 0 1
1 0 1        1 0 1

Therefore, there are 2 possible rectangles of area 2 in the matrix.

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

**Naive Approach: **The simplest approach to solve the problem is to generate the required matrix by multiplying the two arrays and for every possible rectangle of area **K, **check if it consists of only 1’s or not…

Time Complexity:_ O(N * M * K)_

Auxiliary Space:_ O(N * M)_

**Efficient Approach: **To optimize the above approach, the following observations need to be made instead of generating the matrix:

  • _The __area of a rectangle is equal to the product of its __length __and _breadth.
  • _Using this property, visualize the rectangle as a submatrix which contains only _1s. Therefore, this submatrix is the result of the product of two subarrays of length a, b where a * b = K.
  • Since the submatrix contains only 1‘s, it is obvious that these two subarrays also contain only 1‘s in them.

Therefore, the problem reduces to finding the subarrays consisting of only 1‘s of all possible lengths which are proper divisors of K, from the arrays A[] and B[]. Follow the steps below to solve the problem:

  • Precalculate the count of possible subarrays.
  • Iterate through all the divisors of K and for each possible pair (p, q) where p * q = K, check if there exist subarrays of length p, q in A[] and B[].
  • Increase the count of possible such subarrays accordingly and finally, print the obtained count.

Below is the implementation of the above approach:

  • C++

// C++ Program to implement

// the above approach

#include <bits/stdc++.h>

**using** **namespace** std;

// Function to find the subarrays of

// all possible lengths made up of only 1s

vector<``**int**``> findSubarrays(vector<``**int**``>& a)

{

**int** n = a.size();

// Stores the frequency

// of the subarrays

vector<``**int**``> freq(n + 1);

**int** count = 0;

**for** (``**int** i = 0; i < n; i++) {

**if** (a[i] == 0) {

// Check if the previous

// value was also 0

**if** (count == 0)

**continue**``;

// If the previous value was 1

**else** {

**int** value = count;

**for** (``**int** j = 1; j <= count; j++) {

// Find the subarrays of

// each size from 1 to count

freq[j] += value;

value--;

}

count = 0;

}

}

**else**

count++;

}

// If A[] is of the form ....111

**if** (count > 0) {

**int** value = count;

**for** (``**int** j = 1; j <= count; j++) {

freq[j] += value;

value--;

}

}

**return** freq;

}

// Function to find the count

// of all possible rectangles

**void** countRectangles(vector<``**int**``>& a,

vector<``**int**``>& b, **int** K)

{

// Size of each of the arrays

**int** n = a.size();

**int** m = b.size();

// Stores the count of subarrays

// of each size consisting of

// only 1s from array A[]

vector<``**int**``> subA

= findSubarrays(a);

// Stores the count of subarrays

// of each size consisting of

// only 1s from array B[]

vector<``**int**``> subB

= findSubarrays(b);

**int** total = 0;

// Iterating over all subarrays

// consisting of only 1s in A[]

**for** (``**int** i = 1; i < subA.size(); i++) {

// If i is a factor of K, then

// there is a subarray of size K/i in B[]

**if** (K % i == 0 and (K / i) <= m) {

total = total + subA[i] * subB[K / i];

}

}

cout << total;

}

// Driver Code

**int** main()

{

vector<``**int**``> a = { 0, 0, 1, 1 };

vector<``**int**``> b = { 1, 0, 1 };

**int** K = 2;

countRectangles(a, b, K);

**return** 0;

}

Output:

2

Time Complexity:_ O(D) * O(N + M), where D is the number of divisors of K._

Auxiliary Space:_ O(N + M)_

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#arrays #geometric #mathematical #matrix #searching #area-volume-programs #binary-representation #square-rectangle #subarray #submatrix

Joseph  Murray

Joseph Murray

1623911281

How to Print an Array in Java

Introduction

Printing an array is a quick way to give us visibility on the values of the contents inside. Sometimes the array values are the desired output of the program.

In this article, we’ll take a look at how to print an array in Java using four different ways.

While the “best way” depends on what your program needs to do, we begin with the simplest method for printing and then show more verbose ways to do it.

#java #array #how to print an array in java #array in java #print an array in java #print

Abdullah  Kozey

Abdullah Kozey

1617742620

C Program to Count Frequency Of Each Element in an Array

Given an array arr[] of size N, the task is to find the frequency of each distinct element present in the given array.

Examples:

Input: arr[] = { 1, 100000000, 3, 100000000, 3 }

Output: { 1 : 1, 3 : 2, 100000000 : 2 }

Explanation:

Distinct elements of the given array are { 1, 100000000, 3 }

Frequency of 1 in the given array is 1.

Frequency of 100000000 in the given array is 2.

Frequency of 3 in the given array is 2.

Therefore, the required output is { 1 : 1, 100000000 : 2, 3 : 2 }

Input: arr[] = { 100000000, 100000000, 800000000, 100000000 }

Output: { 100000000 : 3, 800000000 : 1}

#arrays #c #c programs #mathematical #searching #sorting #binary search #frequency-counting #quick sort

Mikel  Okuneva

Mikel Okuneva

1597921200

Count of replacements required to make the sum of all Pairs of given type

Given an integer array arr of length N and an integer K, the task is to find the number of array elements to be replaced by a value from the range [1, K] such that each pair (arr[i], arr[N – 1 – i] have equal sum.

Examples :

Input:_ arr[] = {1, 2, 2, 1}, K = 3_

Output:_ 1_

Explanation:

Replace arr[0] with 3, so that the array becomes {3, 2, 2, 1}.

Now, it can be seen that arr[0] + arr[3] = arr[1] + arr[2] = 4.

_Input: _arr[] = {1, 2, 1, 2, 1, 2}

Output:_ 0_

Explanation:

No need to make any changes as arr[0] + arr[5] = arr[1] + arr[4] = arr[2] + arr[3] = 3

Naive Approach :

The simplest approach to this problem could be like iterate for all possible values of X, which can be any number in the range 1 to 2*K, and find the number of operation require to achieve pair sum equal to X. And finally return the minimum numbers of replacement from all operations.

Time Complexity :_ O (N * K)_

Auxiliary Space :_ O (1)_

Efficient Approach: The above approach can be optimized by the following observations:

  • X can clearly take values in the range [2, 2 * K].
  • Considering pairs arr[i] and arr[N – i – 1], it can be observed that the sum of any pair can be made equal to X in 0, 1 or 2 replacements.
  • Let the maximum of these two numbers be mx and minimum be mn. In one replacement, the sum of this pair will be in the range [mn + 1, mx + K].
  • The pair for which mx is less than **( X – K) **and mn is greater than or equal to X will need 2 replacements.
  • Simply insert mx and mn for all pairs in two different vectors, sort them and apply binary search to find the number of pairs for which 2 replacements are required.
  • Find the pairs which do not need any replacement by using Map by storing the frequencies of each sum.
  • Finally number of pairs which require one replacement can be calculated by the equation (N / 2 – (pairs which need 2 replacements + pairs which need no replacement) ).
  1. Follow these steps to find the solve the problem:
  2. Find maximum and minimum for all pairs arr [ i ]arr [ N – i – 1 ] and store them in max_values and min_values vectors respectively. Also store the frequencies of sum of all such pairs in a map.
  3. Sort the vectors max_values and min_values.
  4. Iterate from X = 2 to X = 2 * K, and for every value of X find the total number of replacements as described in the approach above. Update the answer as:

answer = min ( answer, 2 * (number of pairs for which we need to make 2 replacements) + (number of pairs for which we need to make one replacement) ).

Illustration :

arr[] = { 1, 2, 2, 1 }, K = 3

max_values = {1, 2}

min_values = {1, 2}

map = {{2, 1}, {4, 1}}

At X = 4, minimum replacement is required, that is, only 1 replacement, either conversion arr[0] to 3 or arr[3] to 3, is required to make the sum of all pairs equal to 4.

Below is the implementation of the above approach:

  • C++

// C++ Progrm to implement the

// above approach

#include <bits/stdc++.h>

#define int long long int

**using** **namespace** std;

**const** **int** inf = 1e18;

// Function to find the minimum

// replacements required

**int** minimumReplacement(``**int**``* arr, **int** N,

**int** K)

{

**int** ans = inf;

// Stores the maximum and minimum

// values for every pair of

// the form arr[i], arr[n-i-1]

vector<``**int**``> max_values;

vector<``**int**``> min_values;

// Map for storing frequencies

// of every sum formed by pairs

map<``**int**``, **int**``> sum_equal_to_x;

**for** (``**int** i = 0; i < N / 2; i++) {

// Minimum element in the pair

**int** mn = min(arr[i], arr[N - i - 1]);

// Maximum element in the pair

**int** mx = max(arr[i], arr[N - i - 1]);

// Incrementing the frequency of

// sum encountered

sum_equal_to_x[arr[i]

+ arr[N - i - 1]]++;

// Insert minimum and maximum values

min_values.push_back(mn);

max_values.push_back(mx);

}

// Sorting the vectors

sort(max_values.begin(),

max_values.end());

sort(min_values.begin(),

min_values.end());

// Iterate over all possible values of x

**for** (``**int** x = 2; x <= 2 * K; x++) {

// Count of pairs for which x > x + k

**int** mp1

= lower_bound(max_values.begin(),

max_values.end(), x - K)

- max_values.begin();

// Count of pairs for which x < mn + 1

**int** mp2

= lower_bound(min_values.begin(),

min_values.end(), x)

- min_values.begin();

// Count of pairs requiring 2 replacements

**int** rep2 = mp1 + (N / 2 - mp2);

// Count of pairs requiring no replacements

**int** rep0 = sum_equal_to_x[x];

// Count of pairs requiring 1 replacement

**int** rep1 = (N / 2 - rep2 - rep0);

// Update the answer

ans = min(ans, rep2 * 2 + rep1);

}

// Return the answer

**return** ans;

}

// Driver Code

int32_t main()

{

**int** N = 4;

**int** K = 3;

**int** arr[] = { 1, 2, 2, 1 };

cout << minimumReplacement(arr, N, K);

**return** 0;

}

Time Complexity:_ O(NlogN)_

Auxiliary Space:_ O(N)_

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#arrays #mathematical #searching #binary search #frequency-counting

Brain  Crist

Brain Crist

1596627360

Minimum count of elements required to obtain the given Array

Given an array arr[] consisting of N integers, the task is to find the array K[] of minimum possible length such that after performing multiple mirror operations on K[], the given array arr[] can be obtained.

Mirror Operation:_ Appending all the array elements to the original array in reverse order._

Illustration:

arr[] = {1, 2, 3}

After 1st mirror operation, arr[] modifies to {1, 2, 3, 3, 2, 1}

After 2nd mirror operation, arr[] modifies to {1, 2, 3, 3, 2, 1, 1, 2, 3, 3, 2, 1}

Examples:

Input:_ N = 6, arr[] = { 1, 2, 3, 3, 2, 1 }_

Output:_ 3_

Explanation:

Subarrays {1, 2, 3} and {3, 2, 1} are mirror images of each other.

Single mirror operation on {1, 2, 3} obtains the given array.

Therefore, the minimum number of elements required is 3.

Input:_ N = 8, arr[] = { 1, 2, 2, 1, 1, 2, 2, 1 }_

Output:_ 2_

Explanation:

Subarrays {1, 2, 2, 1} and {1, 2, 2, 1} are mirror images of each other.

Subarray {1, 2} and {2, 1} are mirror images of each other.

{1, 2} -> {1, 2, 2, 1} -> {1, 2, 2, 1, 1, 2, 2, 1}

Therefore, the minimum number of elements required is 2.

Naive Approach:

The simplest approach to solve the problem is to generate all the possible subarrays from the given array of size less than equal to N/2 and, for each subarray, check if performing mirror operation gives the array arr[] or not. Print the minimum length subarray satisfying the condition. If no subarray is found to be satisfying, print No.

Time Complexity:_ O(N3)_

Auxiliary Space:_ O(N)_

Efficient Approach:

The above approach can be further optimized using Divide and Conquer technique. Follow the steps below to solve the problem:

  • Initialize a variable K = N and then, check whether the prefix of A[] of length K is a palindrome or not.
  • If the prefix of length **K **is a palindrome then divide K by 2 and perform the above checking.
  • If the prefix is not a palindrome then the answer is the current value of K.
  • Keep checking while K > 0 until K is odd.
  • If K is odd, then print the current value of K.

Below is the implementation of the above approach:

  • C++

// C++ Program to implement

// the above approach

#include <bits/stdc++.h>

**using** **namespace** std;

// Function to find minimum number

// of elements required to form A[]

// by performing mirroring operation

**int** minimumrequired(``**int** A[], **int** N)

{

// Initialize K

**int** K = N;

**int** ans;

**while** (K > 0) {

// Odd length array

// cannot be formed by

// mirror operation

**if** (K % 2 == 1) {

ans = K;

**break**``;

}

**bool** ispalindrome = 1;

// Check if prefix of

// length K is palindrome

**for** (``**int** i = 0; i < K / 2; i++) {

// Check if not a palindrome

**if** (A[i] != A[K - 1 - i])

ispalindrome = 0;

}

// If found to be palindrome

**if** (ispalindrome) {

ans = K / 2;

K /= 2;

}

// Otherwise

**else** {

ans = K;

**break**``;

}

}

// Return the final answer

**return** ans;

}

// Driver Code

**int** main()

{

**int** a[] = { 1, 2, 2, 1, 1, 2, 2, 1 };

**int** N = **sizeof** a / **sizeof** a[0];

cout << minimumrequired(a, N);

**return** 0;

}

Output:

2

Time Complexity:_ O(N*log N)_

_Auxiliary Space: _O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#arrays #divide and conquer #greedy #array-rearrange #palindrome #prefix