 1596646800

# Maximum length of subarray consisting of same type of element

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: _4

Explanation:

_{2, 3}, {3, 4}, {4, 4, 5, 5}, {5, 6}, etc, are the valid sub-arrays where both halves have only one type of element. _

{4, 4, 5, 5} is the sub-array having maximum length.

_Hence, the output is 4. _

Input:_ arr[] = {1, 7, 7, 10, 10, 7, 7, 7, 8, 8, 8, 9}_

_Output: _6

Explanation:

_{1, 7}, {7, 7, 10, 10}, {7, 7, 7, 8, 8, 8}, {8, 9}, etc, are the valid sub-arrays where both halves have only one type of element. _

{7, 7, 7, 8, 8, 8} is the sub-array having maximum length.

_Hence, the output is 6. _

Naive Approach: The naive idea is to generate all possible subarray and check any subarray with maximum length can be divided into two halves such that all the elements in both the halves are the same.

Time Complexity:_ O(N3)_

Auxiliary Space:_ O(1)_

**Efficient Approach: **To solve this problem the idea is to use the concept of Prefix Sum. Follow the steps below to solve the problem:

1. Traverse the array from the start in the forward direction and store the continuous occurrence of an integer for each index in an array forward[].
2. Similarly, traverse the array from the end in the reverse direction and store the continuous occurrence of an integer for each index in an array backward[].
3. Store the maximum of **_min(forward[i], backward[i+1])*2, _**for all the index where arr[i]!=arr[i+1].
4. Print the value obtained in the above step.

Below is the implementation of the above approach:

• C++
• Python3

`// C++ program for the above approach`

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

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

`// Function that finds the maximum`

`// length of the sub-array that`

`// contains equal element on both`

`// halves of sub-array`

`**void**` `maxLengthSubArray(``**int**` `A[],` `**int**` `N)`

`{`

`// To store continuous occurence`

`// of the element`

`**int**` `forward[N], backward[N];`

`// To store continuous`

`// forward occurence`

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

`**if**` `(i == 0`

`|| A[i] != A[i - 1]) {`

`forward[i] = 1;`

`}`

`**else**`

`forward[i] = forward[i - 1] + 1;`

`}`

`// To store continuous`

`// backward occurence`

`**for**` `(``**int**` `i = N - 1; i >= 0; i--) {`

`**if**` `(i == N - 1`

`|| A[i] != A[i + 1]) {`

`backward[i] = 1;`

`}`

`**else**`

`backward[i] = backward[i + 1] + 1;`

`}`

`// To store the maximum length`

`**int**` `ans = 0;`

`// Find maximum length`

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

`**if**` `(A[i] != A[i + 1])`

`ans = max(ans,`

`min(forward[i],`

`backward[i + 1])`

`* 2);`

`}`

`// Print the result`

`cout << ans;`

`}`

`// Driver Code`

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

`{`

`// Given array`

`**int**` `arr[] = { 1, 2, 3, 4, 4,`

`4, 6, 6, 6, 9 };`

`// Size of the array`

`**int**` `N =` `**sizeof**``(arr) /` `**sizeof**``(arr);`

`// Function Call`

`maxLengthSubArray(arr, N);`

`**return**` `0;`

`}`

Output:

``````6
``````

_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 #mathematical #prefix-sum #subarray #subarray-sum

## Buddha Community  1596646800

## Maximum length of subarray consisting of same type of element

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: _4

Explanation:

_{2, 3}, {3, 4}, {4, 4, 5, 5}, {5, 6}, etc, are the valid sub-arrays where both halves have only one type of element. _

{4, 4, 5, 5} is the sub-array having maximum length.

_Hence, the output is 4. _

Input:_ arr[] = {1, 7, 7, 10, 10, 7, 7, 7, 8, 8, 8, 9}_

_Output: _6

Explanation:

_{1, 7}, {7, 7, 10, 10}, {7, 7, 7, 8, 8, 8}, {8, 9}, etc, are the valid sub-arrays where both halves have only one type of element. _

{7, 7, 7, 8, 8, 8} is the sub-array having maximum length.

_Hence, the output is 6. _

Naive Approach: The naive idea is to generate all possible subarray and check any subarray with maximum length can be divided into two halves such that all the elements in both the halves are the same.

Time Complexity:_ O(N3)_

Auxiliary Space:_ O(1)_

**Efficient Approach: **To solve this problem the idea is to use the concept of Prefix Sum. Follow the steps below to solve the problem:

1. Traverse the array from the start in the forward direction and store the continuous occurrence of an integer for each index in an array forward[].
2. Similarly, traverse the array from the end in the reverse direction and store the continuous occurrence of an integer for each index in an array backward[].
3. Store the maximum of **_min(forward[i], backward[i+1])*2, _**for all the index where arr[i]!=arr[i+1].
4. Print the value obtained in the above step.

Below is the implementation of the above approach:

• C++
• Python3

`// C++ program for the above approach`

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

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

`// Function that finds the maximum`

`// length of the sub-array that`

`// contains equal element on both`

`// halves of sub-array`

`**void**` `maxLengthSubArray(``**int**` `A[],` `**int**` `N)`

`{`

`// To store continuous occurence`

`// of the element`

`**int**` `forward[N], backward[N];`

`// To store continuous`

`// forward occurence`

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

`**if**` `(i == 0`

`|| A[i] != A[i - 1]) {`

`forward[i] = 1;`

`}`

`**else**`

`forward[i] = forward[i - 1] + 1;`

`}`

`// To store continuous`

`// backward occurence`

`**for**` `(``**int**` `i = N - 1; i >= 0; i--) {`

`**if**` `(i == N - 1`

`|| A[i] != A[i + 1]) {`

`backward[i] = 1;`

`}`

`**else**`

`backward[i] = backward[i + 1] + 1;`

`}`

`// To store the maximum length`

`**int**` `ans = 0;`

`// Find maximum length`

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

`**if**` `(A[i] != A[i + 1])`

`ans = max(ans,`

`min(forward[i],`

`backward[i + 1])`

`* 2);`

`}`

`// Print the result`

`cout << ans;`

`}`

`// Driver Code`

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

`{`

`// Given array`

`**int**` `arr[] = { 1, 2, 3, 4, 4,`

`4, 6, 6, 6, 9 };`

`// Size of the array`

`**int**` `N =` `**sizeof**``(arr) /` `**sizeof**``(arr);`

`// Function Call`

`maxLengthSubArray(arr, N);`

`**return**` `0;`

`}`

Output:

``````6
``````

_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 #mathematical #prefix-sum #subarray #subarray-sum 1593156510

## Basic Data Types in Python | Python Web Development For Beginners

At the end of 2019, Python is one of the fastest-growing programming languages. More than 10% of developers have opted for Python development.

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

I Mutable objects

II Immutable objects

III Built-in data types in Python

## Mutable objects

The Size and declared value and its sequence of the object can able to be modified called mutable objects.

Mutable Data Types are list, dict, set, byte array

## Immutable objects

The Size and declared value and its sequence of the object can able to be modified.

Immutable data types are int, float, complex, String, tuples, bytes, and frozen sets.

id() and type() is used to know the Identity and data type of the object

a**=25+**85j

type**(a)**

output**:<class’complex’>**

b**={1:10,2:“Pinky”****}**

id**(b)**

output**:**238989244168

## Built-in data types in Python

a**=str(“Hello python world”)****#str**

b**=int(18)****#int**

c**=float(20482.5)****#float**

d**=complex(5+85j)****#complex**

e**=list((“python”,“fast”,“growing”,“in”,2018))****#list**

f**=tuple((“python”,“easy”,“learning”))****#tuple**

g**=range(10)****#range**

h**=dict(name=“Vidu”,age=36)****#dict**

i**=set((“python”,“fast”,“growing”,“in”,2018))****#set**

j**=frozenset((“python”,“fast”,“growing”,“in”,2018))****#frozenset**

k**=bool(18)****#bool**

l**=bytes(8)****#bytes**

m**=bytearray(8)****#bytearray**

n**=memoryview(bytes(18))****#memoryview**

## Numbers (int,Float,Complex)

Numbers are stored in numeric Types. when a number is assigned to a variable, Python creates Number objects.

#signed interger

age**=**18

print**(age)**

Output**:**18

Python supports 3 types of numeric data.

int (signed integers like 20, 2, 225, etc.)

float (float is used to store floating-point numbers like 9.8, 3.1444, 89.52, etc.)

complex (complex numbers like 8.94j, 4.0 + 7.3j, etc.)

A complex number contains an ordered pair, i.e., a + ib where a and b denote the real and imaginary parts respectively).

## String

The string can be represented as the sequence of characters in the quotation marks. In python, to define strings we can use single, double, or triple quotes.

# String Handling

‘Hello Python’

#single (') Quoted String

“Hello Python”

# Double (") Quoted String

“”“Hello Python”“”

‘’‘Hello Python’‘’

# triple (‘’') (“”") Quoted String

In python, string handling is a straightforward task, and python provides various built-in functions and operators for representing strings.

The operator “+” is used to concatenate strings and “*” is used to repeat the string.

“Hello”+“python”

output**:****‘Hello python’**

"python "*****2

'Output : Python python ’

#python web development #data types in python #list of all python data types #python data types #python datatypes #python types #python variable type 1596661200

## Print the Maximum Subarray Sum

Given an array arr[], the task is to find the elements of a contiguous subarray of numbers which has the largest sum.

Examples:

Input:_ arr = [-2, -3, 4, -1, -2, 1, 5, -3]_

Output:_ [4, -1, -2, 1, 5]_

_Explanation: _

In the above input the maximum contiguous subarray sum is 7 and the elements of the subarray are [4, -1, -2, 1, 5]

Input:_ arr = [-2, -5, 6, -2, -3, 1, 5, -6]_

Output:_ [6, -2, -3, 1, 5]_

_Explanation: _

In the above input the maximum contiguous subarray sum is 7 and the elements

of the subarray are [6, -2, -3, 1, 5]

Naive Approach: The naive approach is to generate all the possible subarray and print that subarray which has maximum sum.

Time complexity:_ O(N2)_

Auxiliary Space:_ O(1)_

Efficient Approach: The idea is to use the Kadane’s Algorithm to find the maximum subarray sum and store the starting and ending index of the subarray having maximum sum and print the subarray from starting index to ending index. Below are the steps:

1. Initialize 3 variables endIndex to 0, currMax and globalMax to first value of the input array.
2. For each element in the array starting from index(say i) 1, update currMax to max(nums[i], nums[i] + currMax) and globalMax and endIndex to i only if currMax > globalMax.
3. To find the start index, iterate from endIndex in the left direction and keep decrementing the value of globalMax until it becomes 0. The point at which it becomes 0 is the start index.
4. Now print the subarray between [start, end].

Below is the implementation of the above approach:

• C++14

`// C++ program for the above approach`

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

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

`// Function to print the elements`

`// of Subarray with maximum sum`

`**void**` `SubarrayWithMaxSum(vector<``**int**``>& nums)`

`{`

`// Initialize currMax and globalMax`

`// with first value of nums`

`**int**` `endIndex, currMax = nums;`

`**int**` `globalMax = nums;`

`// Iterate for all the elemensts`

`// of the array`

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

`// Update currMax`

`currMax = max(nums[i],`

`nums[i] + currMax);`

`// Check if currMax is greater`

`// than globalMax`

`**if**` `(currMax > globalMax) {`

`globalMax = currMax;`

`endIndex = i;`

`}`

`}`

`**int**` `startIndex = endIndex;`

`// Traverse in left direction to`

`// find start Index of subarray`

`**while**` `(startIndex >= 0) {`

`globalMax -= nums[startIndex];`

`**if**` `(globalMax == 0)`

`**break**``;`

`// Decrement the start index`

`startIndex--;`

`}`

`// Printing the elements of`

`// subarray with max sum`

`**for**` `(``**int**` `i = startIndex;`

`i <= endIndex; ++i) {`

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

`}`

`}`

`// Driver Code`

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

`{`

`// Given array arr[]`

`vector<``**int**``> arr`

`= { -2, -5, 6, -2,`

`-3, 1, 5, -6 };`

`// Function call`

`SubarrayWithMaxSum(arr);`

`**return**` `0;`

`}`

Output:

``````6 -2 -3 1 5
``````

Time complexity:_ O(N)_

Auxiliary Space:_ O(1)_

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 #dynamic programming #algorithms-dynamic programming #kadane #subarray #subarray-sum 1597935600

## Count of subarrays having sum equal to its length

Given an array** arr[]** of size N, the task is to find the number of subarrays having the sum of its elements equal to the number of elements in it.

Examples:

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

Output:_ 3_

Explanation:

Total number of subarrays are 6 i.e., {1}, {0}, {2}, {1, 0}, {0, 2}, {1, 0, 2}.

_Out of 6 only three subarrays have the number of elements equals to sum of its elements i.e., _

1) {1}, sum = 1, length = 1.

2) {0, 2}, sum = 2, length = 2.

3) {1, 0, 2}, sum = 3, length = 3.

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

Output:_ 3_

Explanation:

Total number of subarrays are 6 i.e. {1}, {1}, {0}, {1, 1}, {1, 0}, {1, 1, 0}.

_Out of 6 only three subarrays have the number of elements equals to sum of its elements i.e., _

1) {1}, sum = 1, length = 1.

2) {1}, sum = 1, length = 1.

3) {1, 1}, sum = 2, length = 2.

Naive Approach: The idea is to generate all the subarrays of the array and if the sum of elements of the subarray is equal to the number of elements in it then count this subarray. Print the count after checking all the subarrays.

_Time Complexity: _O(N2)

Auxiliary Space:_ O(N)_

**Efficient Approach: **This problem can be converted into a simpler problem by using observation. If all the elements of the array are decremented by 1, then all the subarrays of array arr[] with a sum equal to its number of elements are same as finding the number of subarrays with sum 0 in the new array(formed by decrementing all the elements of arr[ ] by 1). Below are the steps:

1. Decrement all the array elements by 1.
2. Initialize a prefix array with prefix = arr.
3. Traverse the given array arr[] from left to right, starting from index 1 and update a prefix sum array as pref[i] = pref[i-1] + arr[i].
4. Initialize the answer to 0.
5. Iterate the prefix array pref[] from left to right and increment the answer by the value of the current element in the map.
6. Increment the value of the current element in the map.
7. Print the value of answer after the above steps.

Below is the implementation of the above approach:

• C++
• Python3

`// C++ program for the above approach`

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

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

`// Function that counts the subarrays`

`// with sum of its elements as its length`

`**int**` `countOfSubarray(``**int**` `arr[],` `**int**` `N)`

`{`

`// Decrementing all the elements`

`// of the array by 1`

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

`arr[i]--;`

`// Making prefix sum array`

`**int**` `pref[N];`

`pref = arr;`

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

`pref[i] = pref[i - 1] + arr[i];`

`// Declare map to store count of`

`// elements upto current element`

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

`**int**` `answer = 0;`

`// To count all the subarrays`

`// whose prefix sum is 0`

`mp++;`

`// Iterate the array`

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

`// Increment answer by count of`

`// current element of prefix array`

`answer += mp[pref[i]];`

`mp[pref[i]]++;`

`}`

`// Return the answer`

`**return**` `answer;`

`}`

`// Driver Code`

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

`{`

`// Given array arr[]`

`**int**` `arr[] = { 1, 1, 0 };`

`**int**` `N =` `**sizeof**` `arr /` `**sizeof**` `arr;`

`// Function call`

`cout << countOfSubarray(arr, N);`

`**return**` `0;`

`}`

Output:

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

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

Auxiliary Space:_ O(N)_

#arrays #competitive programming #dynamic programming #greedy #mathematical #cpp-map #subarray #subarray-sum 1594238700

## Find array elements equal to sum of any subarray of at least size 2

Given an array arr[], the task is to find the elements from the array which are equal to the sum of any sub-array of size greater than 1.

Examples:

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

Output:_ 3, 5, 6_

Explanation:

The elements 3, 5, 6 are equal to sum of subarrays {1, 2},{2, 3} and {1, 2, 3} respectively.

Input:_ arr[] = {5, 6, 10, 1, 3, 4, 8, 16}_

Output:_ 4, 8, 16_

Explanation:

The elements 4, 8, 16 are equal to the sum of subarrays {1, 3}, {1, 3, 4}, {1, 3, 4, 8} respectively

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

Approach: The idea is to use prefix sum array to solve the given problem. Create a prefix[] array that stores the prefix sum of all its preceding elements for every index. Store the sum of all subarrays in a map and search if any array element is present in the map or not.

#arrays #hash #prefix-sum #subarray #subarray-sum