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

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

1597748400

## Minimum increments by index value required to obtain at least two equal Array elements

Given a strictly decreasing array arr[] consisting of N integers, the task is to find the minimum number of operations required to make at least two array elements equal, where each operation involves increasing every array element by its index value.

Examples:

_Input: _arr[] = {6, 5, 1}

_Output: _1

Explanation:

{6 + 1, 5 + 2, 1 + 3} = {7, 7, 4}

_Input: _arr[] = {12, 8, 4}

_Output: _4

Explanation:

Step 1 : {12 + 1, 8 + 2, 4 + 3} = {13, 10, 7}

Step 2 : {13 + 1, 10 + 2, 7 + 3} = {14, 12, 10}

Step 3 : {15, 14, 13}

Step 4 : {16, 16, 16}

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

Naive approach: Follow the below steps to solve the problem:

• Check if the array already has at least two equal elements or not. If found to be true, print 0.
• Otherwise, keep updating the array by increasing each array element by its index value and increase count. Check if array has two equal elements or not.
• Print count once the array is found to be containing at least two equal elements.

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 update every element`

`// adding to it its index value`

`**void**` `update(``**int**` `arr[],` `**int**` `N)`

`{`

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

`arr[i] += (i + 1);`

`}`

`}`

`// Function to check if at least`

`// two elements are equal or not`

`**bool**` `check(``**int**` `arr[],` `**int**` `N)`

`{`

`**bool**` `f = 0;`

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

`// Count the frequency of arr[i]`

`**int**` `count = 0;`

`**for**` `(``**int**` `j = 0; j < N; j++) {`

`**if**` `(arr[i] == arr[j]) {`

`count++;`

`}`

`}`

`**if**` `(count >= 2) {`

`f = 1;`

`**break**``;`

`}`

`}`

`**if**` `(f == 1)`

`**return**` `**true**``;`

`**else**`

`**return**` `**false**``;`

`}`

`// Funtion to calculate the number`

`// of increment operations required`

`**void**` `incrementCount(``**int**` `arr[],` `**int**` `N)`

`{`

`// Stores the minimum number of steps`

`**int**` `min = 0;`

`**while**` `(check(arr, N) !=` `**true**``) {`

`update(arr, N);`

`min++;`

`}`

`cout << min;`

`}`

`// Driver Code`

`**int**` `main()`

`{`

`**int**` `N = 3;`

`**int**` `arr[N] = { 12, 8, 4 };`

`incrementCount(arr, N);`

`**return**` `0;`

`}`

Output:

``````4
``````

_Time Complexity: _O(N2)

Auxiliary Space:_ O(1)_

Efficient Approach: The above approach can be optimized by observing that by the given operation, the difference between any two adjacent elements reduces by 1 as the array is decreasing. Therefore, the minimum number of operations required is equal to the minimum difference between any two adjacent elements.

#arrays #greedy #mathematical #array-rearrange

1596958647

## Minimize swaps required to maximize the count of elements

Given an array A[], consisting of N elements, the task is to find the minimum number of swaps required such that array elements swapped to replace a higher element, in the original array, is maximized.

Examples:

Input:_ A[] = {4, 3, 3, 2, 5} _

Output:_ 3 _

Explanation:

Swap 1: {4, 3, 3, 2, 5} -> {5_, 3, 3, 2, 4} _

Swap 2: {5, 3, 3, 2, 4} -> {3_, 3, 5, 2, 4} _

_Swap 3: {3, 3, 52, 4} -> {3, 3, 25, 4} _

Therefore, elements {4, 3, 2} occupies original position of a higher element after swapping

Input:_. A[] = {6, 5, 4, 3, 2, 1} _

OutputL_ 5 _

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

**Naive Approach: **The simplest approach to solve the problem can be implemented as follows:

• **Sort **the array in ascending order.
• Initialize two variables, _result _and index, to store the count and the index up to which it has been considered in the original array, repectively.
• Iterate over the array elements. For any element A[i], go to a value in the array which is greater than ai and increment _index _variable accordingly.
• After finding an element greater than A[i], increment result and index.
• If _index _has reached the end of the array, no elements are left to be swapped with previously checked elements.
• Therefore, print count.

Below is the implementation of the above approach:

• C++
• Python3

`// C++ Program to implement`

`// the above approach`

`#include <bits/stdc++.h>`

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

`// Function to find the minimum`

`// number of swaps required`

`**int**` `countSwaps(``**int**` `A[],` `**int**` `n)`

`{`

`// Sort the array in ascending order`

`sort(A, A + n);`

`**int**` `ind = 1, res = 0;`

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

`// Iterate until a greater element`

`// is found`

`**while**` `(ind < n and A[ind] == A[i])`

`// Keep incrementing ind`

`ind++;`

`// If a greater element is found`

`**if**` `(ind < n and A[ind] > A[i]) {`

`// Increase count of swap`

`res++;`

`// Increment ind`

`ind++;`

`}`

`// If end of array is reached`

`**if**` `(ind >= n)`

`**break**``;`

`}`

`// Return the answer`

`**return**` `res;`

`}`

`// Driver Code`

`**int**` `main()`

`{`

`**int**` `A[] = { 4, 3, 3, 2, 5 };`

`cout << countSwaps(A, 5);`

`**return**` `0;`

`}`

Output:

``````3
``````

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

Auxiliary Space:_ O(1)_

Efficient Approach:

Since any swap between two unequal elements leads to an element replacing a higher element, it can be observed that the minimum number of swaps required is N – (the maximum frequency of an array element). Therefore, find the most frequent element in the array using HashMap, and print the result.

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 minimum`

`// number of swaps required`

`**int**` `countSwaps(``**int**` `A[],` `**int**` `n)`

`{`

`// Stores the frequency of the`

`// array elements`

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

`// Stores maximum frequency`

`**int**` `max_frequency = 0;`

`// Find the max frequency`

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

`// Update frequency`

`mp[A[i]]++;`

`// Update maximum frequency`

`max_frequency`

`= max(max_frequency, mp[A[i]]);`

`}`

`**return**` `n - max_frequency;`

`}`

`// Driver Code`

`**int**` `main()`

`{`

`**int**` `A[] = { 6, 5, 4, 3, 2, 1 };`

`// function call`

`cout << countSwaps(A, 6);`

`**return**` `0;`

`}`

Output:

``````5
``````

Time Complexity:_ O(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 #greedy #hash #mathematical #array-rearrange #cpp-map #frequency-counting

1597798800

## Count of Ways to obtain given Sum from the given Array elements

Given an array arr[], consisting of N non-negative integers and an integer S, the task is to find the number of ways to obtain the sum S by adding or subtracting array elements.

Note: All the array elements need to be involved in generating the sum.

Examples:

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

Output:_ 5_

Explanation:

Following are the possible ways to obtain the sum S:

• -1 + 1 + 1 + 1 + 1 = 3
• 1 -1 + 1 + 1 + 1 = 3
• 1 + 1 – 1 + 1 + 1 = 3
• 1 + 1 + 1 – 1 + 1 = 3
• 1 + 1 + 1 + 1 – 1 = 3

Input:_ arr[] = {1, 2, 3, 4, 5}, S = 3_

Output:_ 3_

Explanation:

Following are the possible ways to obtain the sum S:

• -1 -2 -3 + 4 + 5 = 3
• -1 + 2 + 3 + 4 – 5 = 3
• 1 – 2 + 3 – 4 + 5 = 3

Recursive** Approach:** It can be observed that each array element can either be added or subtracted to obtain sum. Therefore, for each array element, recursively check for both the possibilities and increase count when sum S is obtained after reaching the end of the array.

Below is the implementation of the above approach:

• Java

`// Java Program to implement`

`// the above approach`

`**import**` `java.io.*;`

`**class**` `GFG {`

`// Function to call dfs() to`

`// calculate the number of ways`

`**static**` `**int**` `findWays(``**int**``[] nums,` `**int**` `S)`

`{`

`**return**` `dfs(nums, S,` `0``,` `0``);`

`}`

`// Function to count the number of ways`

`**static**` `**int**` `dfs(``**int**``[] nums,` `**int**` `S,`

`**int**` `curr_sum,` `**int**` `index)`

`{`

`// Base Case: Reached the`

`// end of the array`

`**if**` `(index == nums.length) {`

`// Sum is equal to the`

`// required sum`

`**if**` `(S == curr_sum)`

`**return**` `1``;`

`**else**`

`**return**` `0``;`

`}`

`// Recursively check if required sum`

`// can be obtained by adding current`

`// element or by subtracting the`

`// current index element`

`**return**` `dfs(nums, S, curr_sum + nums[index],`

`index +` `1``)`

`+ dfs(nums, S, curr_sum - nums[index],`

`index +` `1``);`

`}`

`// Driver Code`

`**public**` `**static**` `**void**` `main(String[] args)`

`{`

`**int**` `S =` `3``;`

`**int**``[] arr =` `**new**` `**int**``[] {` `1``,` `2``,` `3``,` `4``,` `5` `};`

`**int**` `answer = findWays(arr, S);`

`System.out.println(answer);`

`}`

`}`

Output:

``````3
``````

Time Complexity:_ O(2N)_

Auxiliary Space:_ O(1)_

**Dynamic Programming ****Approach: **The above recursive approach can be optimized by using Memoization.

Below is the implementation of the above approach:

• Java

`// C++ Program to implement`

`// the above approach`

`**import**` `java.io.*;`

`**import**` `java.util.*;`

`**class**` `GFG {`

`// Function to call dfs`

`// to calculate the number of ways`

`**static**` `**int**` `findWays(``**int**``[] nums,` `**int**` `S)`

`{`

`**int**` `sum =` `0``;`

`// Iterate till the length of array`

`**for**` `(``**int**` `i =` `0``; i < nums.length; i++)`

`sum += nums[i];`

`// Initialize the memorization table`

`**int**``[][] memo`

`=` `**new**` `**int**``[nums.length +` `1``][``2` `* sum +` `1``];`

`**for**` `(``**int**``[] m : memo) {`

`Arrays.fill(m, Integer.MIN_VALUE);`

`}`

`**return**` `dfs(memo, nums, S,` `0``,` `0``, sum);`

`}`

`// Function to perform the DFS to calculate the`

`// number of ways`

`**static**` `**int**` `dfs(``**int**``[][] memo,` `**int**``[] nums,` `**int**` `S,`

`**int**` `curr_sum,` `**int**` `index,` `**int**` `sum)`

`{`

`// Base case: Reached the end of array`

`**if**` `(index == nums.length) {`

`// If current sum is obtained`

`**if**` `(S == curr_sum)`

`**return**` `1``;`

`// Otherwise`

`**else**`

`**return**` `0``;`

`}`

`// If previously calculated`

`// subproblem occurred`

`**if**` `(memo[index][curr_sum + sum]`

`!= Integer.MIN_VALUE) {`

`**return**` `memo[index][curr_sum + sum];`

`}`

`// Check if the required sum can`

`// be obtained by adding current`

`// element or by subtracting the`

`// current index element`

`**int**` `ans = dfs(memo, nums, index +` `1``,`

`curr_sum + nums[index], S, sum)`

`+ dfs(memo, nums, index +` `1``,`

`curr_sum - nums[index], S, sum);`

`// Store the count of ways`

`memo[index][curr_sum + sum] = ans;`

`**return**` `ans;`

`}`

`// Driver Code`

`**public**` `**static**` `**void**` `main(String[] args)`

`{`

`**int**` `S =` `3``;`

`**int**``[] arr =` `**new**` `**int**``[] {` `1``,` `2``,` `3``,` `4``,` `5` `};`

`**int**` `answer = findWays(arr, S);`

`System.out.println(answer);`

`}`

`}`

Output:

``````3
``````

Time Complexity:_ O(N * S)_

Auxiliary Space:_ O(N * S)_

Knapsack Approach: The idea is to implement the 0/1 Knapsack problem. Follow the steps below:

#arrays #dynamic programming #mathematical #recursion #searching #knapsack #memoization #subset

1598022000

## Minimum Subarray flips required to convert all elements of a Binary Array to K

Given an array of integers arr[] and a binary string str of length N, the task is to rearrange given array by swapping array elements from indices having the same character in the string, such that the number formed by the elements of the rearranged array as digits is the maximum possible.

Examples:

Input:_ arr[]={1, 3, 4, 2}, str=”0101”_

Output:_ 4 3 1 2_

Explanation:

Since arr[0] is less than arr[2], so swap them. Therefore the maximum possible number from the array is 4, 3, 1, 2.

Input:_ arr[] = { 1, 3, 456, 6, 7, 8 }, str = “101101”_

Output:_ 8 7 6 456 3 1_

Explanation:

Array elements present at 0-chractered indices: {3, 7}

Largest number that can be formed from the above two numbers is 73

Array elements present at 1-chractered indices: {1, 456, 6, 8}

Largest number that can be formed from the above two numbers is 864561

Therefore, maximum number that can be generated from the array is 87645631

Approach: Follow the steps below to solve the problem:

1. Create two arrays to store 0-charactered index elements and 1-charactered index elements from the array.
2. Sort the arrays to form largest possible numbers from these two arrays.
3. Iterate over str and based on the characters, place array elements from the sorted arrays.

Below is the implementation of the above approach:

• C++

`// C++ Program to implement`

`// the above approach`

`#include <bits/stdc++.h>`

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

`// Comparison Function to sort()`

`**int**` `myCompare(``**int**` `a,` `**int**` `b)`

`{`

`string X = to_string(a);`

`string Y = to_string(b);`

`// Append Y at the end of X`

`string XY = X.append(Y);`

`// Append X at the end of Y`

`string YX = Y.append(X);`

`// Compare and return greater`

`**return**` `XY.compare(YX) < 0 ? 1 : 0;`

`}`

`// Function to return the rearranged`

`// array in the form of largest`

`// possible number that can be formed`

`**void**` `findMaxArray(vector<``**int**``>& arr, string& str)`

`{`

`**int**` `N = arr.size();`

`vector<``**int**``> Z, O, ans(N);`

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

`**if**` `(str[i] ==` `'0'``) {`

`Z.push_back(arr[i]);`

`}`

`**else**` `{`

`O.push_back(arr[i]);`

`}`

`}`

`// Sort them in decreasing order`

`sort(Z.rbegin(), Z.rend(), myCompare);`

`sort(O.rbegin(), O.rend(), myCompare);`

`**int**` `j = 0, k = 0;`

`// Generate the sorted array`

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

`**if**` `(str[i] ==` `'0'``) {`

`ans[i] = Z[j++];`

`}`

`**else**` `{`

`ans[i] = O[k++];`

`}`

`}`

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

`cout << ans[i] <<` `" "``;`

`}`

`}`

`// Driver Code`

`**int**` `main()`

`{`

`vector<``**int**``> arr = { 1, 3, 456, 6, 7, 8 };`

`string str =` `"101101"``;`

`findMaxArray(arr, str);`

`**return**` `0;`

`}`

Output:

``````8 7 6 456 3 1
``````

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 #greedy #mathematical #searching #array-rearrange