Open In App

Find the sum of medians of all odd length subarrays

Last Updated : 22 Feb, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array arr[] of size N, the task is to find the sum of medians of all sub-array of odd-length.

Examples:

Input: arr[] = {4, 2, 5, 1}
Output: 18
Explanation : Sub-Arrays of odd length and their medians are :

  • [4]  -> Median is 4
  • [4, 2, 5]  -> Median is 4
  • [2]  -> Median is 2
  • [2, 5, 1]  -> Median is 2
  • [5]  -> Median is 5
  • [1]  -> Median is 1

Their sum = 4 + 4+ 2 + 2 + 5 +1 = 18

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

 

Pre-requisites: Median of Stream of Running Integers using STL

Naive Approach: Generate each and every sub-array. If the length of the sub-array is odd, then sort the sub-array and return the middle element.

Below is the implementation of the above approach: 

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find sum of medians
// of all odd-length subarrays
int solve(vector<int> arr)
{
    int ans = 0;
    int n = arr.size();
 
    // Loop to calculate the sum
    for(int i = 0; i < n; i++)
    {
        vector<int> new_arr;
        for(int j = i; j < n; j++)
        {
            new_arr.push_back(arr[j]);
             
            // Odd length subarray
            if ((new_arr.size() % 2) == 1)
            {
                sort(new_arr.begin(), new_arr.end());
                int mid = new_arr.size() / 2;
                ans += new_arr[mid];
            }
        }
    }
    return ans;
}
 
// Driver Code
int main()
{
    vector<int> arr = { 4, 2, 5, 1 };
    cout << solve(arr);
}
 
// This code is contributed by Samim Hossain Mondal.


Java




// Java program for the above approach
import java.util.*;
 
class GFG {
    // Function to find sum of medians
    // of all odd-length subarrays
    static int solve(int[] arr) {
        int ans = 0;
        int n = arr.length;
 
        // Loop to calculate the sum
        for (int i = 0; i < n; i++) {
            List<Integer> new_arr = new LinkedList<Integer>();
            for (int j = i; j < n; j++) {
                new_arr.add(arr[j]);
 
                // Odd length subarray
                if ((new_arr.size() % 2) == 1) {
                    Collections.sort(new_arr);
                    int mid = new_arr.size() / 2;
                    ans += new_arr.get(mid);
                }
            }
        }
        return ans;
    }
 
    // Driver Code
    public static void main(String[] args) {
        int[] arr = { 4, 2, 5, 1 };
        System.out.println(solve(arr));
    }
}
// This code is contributed by 29AjayKumar


Python3




# Python program for the above approach
 
# Function to find sum of medians
# of all odd-length subarrays
def solve(arr):
        ans = 0
        n = len(arr)
         
        # Loop to calculate the sum
        for i in range(n):
            new_arr = []
            for j in range(i, n, 1):
                new_arr.append(arr[j])
 
                # Odd length subarray
                if (len(new_arr)) % 2 == 1:
                    new_arr.sort()
                    mid = len(new_arr)//2
                    ans += new_arr[mid]
        return (ans)
 
# Driver Code
if __name__ == "__main__":
    arr = [4, 2, 5, 1]
    print(solve(arr))
    


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
 
  // Function to find sum of medians
  // of all odd-length subarrays
  static int solve(int[] arr) {
    int ans = 0;
    int n = arr.Length;
 
    // Loop to calculate the sum
    for (int i = 0; i < n; i++) {
      List<int> new_arr = new List<int>();
      for (int j = i; j < n; j++) {
        new_arr.Add(arr[j]);
 
        // Odd length subarray
        if ((new_arr.Count % 2) == 1) {
          new_arr.Sort();
          int mid = new_arr.Count / 2;
          ans += new_arr[mid];
        }
      }
    }
    return ans;
  }
 
  // Driver Code
  public static void Main() {
    int[] arr = { 4, 2, 5, 1 };
    Console.Write(solve(arr));
  }
}
 
// This code is contributed by Saurabh Jaiswal


Javascript




<script>
 
// javascript program for the above approach
    // Function to find sum of medians
    // of all odd-length subarrays
    function solve(arr) {
        var ans = 0;
        var n = arr.length;
 
        // Loop to calculate the sum
        for (var i = 0; i < n; i++) {
            var new_arr= new Array();
            for (var j = i; j < n; j++) {
                new_arr.push(arr[j]);
 
                // Odd length subarray
                if ((new_arr.length % 2) == 1) {
                    new_arr.sort();
                    var mid = Math.floor(new_arr.length / 2);
                     
                    // document.write(mid);
                    ans += new_arr[mid];
                }
            }
        }
        return ans;
    }
 
    // Driver Code
var arr = [ 4, 2, 5, 1 ];
document.write(solve(arr));
 
// This code is contributed by shikhasingrajput
</script>


Output

18

Time Complexity: O(N3 * Log(N))  
Auxiliary Space: O(N)

Note: Instead of sorting array each time, which costs (N*logN), insertion sort can be applied. But still, overall Time Complexity will be O(N3).

Efficient Approach: The median of the sorted array is the value separating the higher half from the lower half in the array. For finding out the median, we only need the middle element, rather than the entire sorted array. The approach of Median of Stream of Running Integers can be applied over here. Follow the steps mentioned below 

  1. Use max and min heaps to calculate the running median.
  2. Traverse each and every element in the array.
  3. While creating a new subarray, add an element into the heaps and return median if the size is odd else return 0.
  4. Max_heap is used to store lower half elements such that the maximum element is at the top and min_heap is used to store higher half elements such that the minimum element is at the top.
  5. The difference between both the heaps should not be greater than one, and one extra element is always placed in max_heap.

Note: Here max_heap is implemented using min_heap, by just negating the values so that the maximum negative element can be popped.

Below is the implementation of the above approach:  

C++




// C++ program for the above approach
#include <bits/stdc++.h>
 
// Class to find median
class find_median {
  public:
  // Constructor to declare two heaps
  find_median()
  {
    // Store lower half elements such that
    // maximum element is at top
    max_heap
      = std::priority_queue<int, std::vector<int>,
    std::less<int> >();
 
    // Store higher half elements such that
    // minimum element is at top
    min_heap
      = std::priority_queue<int, std::vector<int>,
    std::less<int> >();
  }
 
  // Function to add element
  int add(int val)
  {
 
    // If max_heap is empty or current element
    // smaller than top of max_heap
    if (max_heap.empty() || max_heap.top() > val) {
      max_heap.push(-val);
    }
 
    else {
      min_heap.push(val);
    }
 
    // If size of max_heap + 1 less
    // than min_heap
    if (max_heap.size() + 1 > min_heap.size()) {
      val = -max_heap.top();
      max_heap.pop();
      min_heap.push(val);
    }
 
    // If size of min_heap
    // less than max_heap
    if (min_heap.size() > max_heap.size()) {
      val = min_heap.top();
      min_heap.pop();
      max_heap.push(-val);
    }
 
    // Finally if sum of sizes is odd,
    // return median
    if ((min_heap.size() + max_heap.size()) % 2 == 1) {
      return -max_heap.top();
    }
 
    // Else return 0
    else {
      return 0;
    }
  }
 
  std::priority_queue<int, std::vector<int>,
  std::less<int> >
    max_heap;
  std::priority_queue<int, std::vector<int>,
  std::less<int> >
    min_heap;
};
 
// Function to calculate the sum of all odd length subarrays
int solve(std::vector<int> arr)
{
  int ans = 0;
 
  // Size of the array
  int n = arr.size();
  for (int i = 0; i < n; i++) {
    // Create an object of class find_median
    find_median obj;
 
    for (int j = i; j < n; j++)
    {
       
      // Add value to the heaps using object
      int val = obj.add(arr[j]);
      ans += val;
    }
  }
 
  return (ans);
}
 
// Driver Code
int main()
{
  std::vector<int> arr = { 4, 2, 5, 1 };
  std::cout << solve(arr);
  return 0;
}
 
// This code is contributed by phasing17.


Java




import java.util.*;
 
// A class to find the median of the array
class FindMedian {
 
  // Declare two heaps
  // Store lower half elements such that
  // maximum element is at top
  private List<Integer> max_heap;
 
  // Store higher half elements such that
  // minimum element is at top
  private List<Integer> min_heap;
 
  // Constructor to initialize the heaps
  public FindMedian() {
    max_heap = new ArrayList<>();
    min_heap = new ArrayList<>();
  }
 
  public int add(int val) {
    // len(max_heap) == 0 or curr_element
    // smaller than max_heap top
    if (max_heap.size() == 0 || max_heap.get(0) > val) {
      max_heap.add(-val);
    }
    else {
      min_heap.add(val);
    }
 
    // If size of max_heap + 1 greater
    // than min_heap
    if (max_heap.size() + 1 > min_heap.size()) {
      int v = max_heap.get(max_heap.size() - 1);
      max_heap.remove(max_heap.size() - 1);
      min_heap.add(-v);
    }
 
    // If size of min_heap
    // greater than max_heap
    if (min_heap.size() > max_heap.size()) {
      int v = min_heap.get(min_heap.size() - 1);
      min_heap.remove(min_heap.size() - 1);
      max_heap.add(-v);
    }
 
    // Finally if sum of sizes is odd,
    // return median
    if ((min_heap.size() + max_heap.size()) % 2 == 1) {
      return (-max_heap.get(0));
    }
 
    // Else return 0
    else {
      return 0;
    }
  }
}
 
class GFG {
  // Function to calculate the sum
  // of all odd length subarrays
  public static int solve(int[] arr) {
    int ans = 0;
 
    // Size of the array
    int n = arr.length;
 
    for (int i = 0; i < n; i++) {
      // Create an object
      // of class FindMedian
      FindMedian obj = new FindMedian();
      for (int j = i; j < n; j++) {
        // Add value to the heaps
        // using object
        int val = obj.add(arr[j]);
        ans += val;
      }
    }
 
    return (ans);
  }
 
  // Driver Code
  public static void main(String[] args) {
    int[] arr = { 4, 2, 5, 1 };
    System.out.println(solve(arr));
  }
}


Python3




# Python program for the above approach
from heapq import heappush as push, heappop as pop
 
# Find the sum of medians of odd-length
# subarrays
class find_median():
 
    # Constructor to declare two heaps
    def __init__(self):
 
        # Store lower half elements such that
        # maximum element is at top
        self.max_heap = []
 
        # Store higher half elements such that
        # minimum element is at top
        self.min_heap = []
 
    def add(self, val):
 
        # len(max_heap) == 0 or curr_element
        # smaller than max_heap top
        if (len(self.max_heap) == 0 or
            self.max_heap[0] > val):
            push(self.max_heap, -val)
 
        else:
            push(self.min_heap, val)
 
        # If size of max_heap + 1 greater
        # than min_heap
        if (len(self.max_heap)+1 >
            len(self.min_heap)):
            val = pop(self.max_heap)
            push(self.min_heap, -val)
 
        # If size of min_heap
        # greater than max_heap
        if (len(self.min_heap) >
            len(self.max_heap)):
            val = pop(self.min_heap)
            push(self.max_heap, -val)
 
        # Finally if sum of sizes is odd,
        # return median
        if (len(self.min_heap) +
            len(self.max_heap)) % 2 == 1:
            return (-self.max_heap[0])
 
        # Else return 0
        else:
            return 0
 
# Function to calculate the sum
# of all odd length subarrays
def solve(arr):
    ans = 0
     
    # Size of the array
    n = len(arr)
    for i in range(n):
         
        # Create an object
        # of class find_median
        obj = find_median()
        for j in range(i, n, 1):
             
            # Add value to the heaps
            # using object
            val = obj.add(arr[j])
            ans += val
     
    return (ans)
 
# Driver Code
if __name__ == "__main__":
    arr = [4, 2, 5, 1]
    print(solve(arr))


C#




// C# Program for the above approach
using System;
using System.Collections.Generic;
 
// A class to find the median of the array
public class FindMedian
{
 
  // Declare two heaps
  // Store lower half elements such that
  // maximum element is at top
  private List<int> max_heap;
 
  // Store higher half elements such that
  // minimum element is at top
  private List<int> min_heap;
 
  // Constructor to initialize the heaps
  public FindMedian()
  {
    max_heap = new List<int>();
    min_heap = new List<int>();
  }
 
  public int Add(int val)
  {
    // len(max_heap) == 0 or curr_element
    // smaller than max_heap top
    if (max_heap.Count == 0 || max_heap[0] > val) {
      max_heap.Add(-val);
    }
    else {
      min_heap.Add(val);
    }
 
    // If size of max_heap + 1 greater
    // than min_heap
    if (max_heap.Count + 1 > min_heap.Count) {
      int v = max_heap[max_heap.Count - 1];
      max_heap.RemoveAt(max_heap.Count - 1);
      min_heap.Add(-v);
    }
 
    // If size of min_heap
    // greater than max_heap
    if (min_heap.Count > max_heap.Count) {
      int v = min_heap[min_heap.Count - 1];
      min_heap.RemoveAt(min_heap.Count - 1);
      max_heap.Add(-v);
    }
 
    // Finally if sum of sizes is odd,
    // return median
    if ((min_heap.Count + max_heap.Count) % 2 == 1) {
      return (-max_heap[0]);
    }
 
    // Else return 0
    else {
      return 0;
    }
  }
}
 
public class GFG {
  // Function to calculate the sum
  // of all odd length subarrays
  public static int Solve(int[] arr)
  {
    int ans = 0;
 
    // Size of the array
    int n = arr.Length;
 
    for (int i = 0; i < n; i++) {
      // Create an object
      // of class find_median
      FindMedian obj = new FindMedian();
      for (int j = i; j < n; j++) {
        // Add value to the heaps
        // using object
        int val = obj.Add(arr[j]);
        ans += val;
      }
    }
 
    return (ans);
  }
 
  // Driver Code
  public static void Main()
  {
    int[] arr = { 4, 2, 5, 1 };
    Console.WriteLine(Solve(arr));
  }
}
 
// This code is contributed by vinayetbi1


Javascript




// JavaScript Program for the above approach
 
// A class to find the median of the array
class find_median {
    // Constructor to declare two heaps
    constructor() {
        // Store lower half elements such that
        // maximum element is at top
        this.max_heap = [];
 
        // Store higher half elements such that
        // minimum element is at top
        this.min_heap = [];
    }
 
    add(val) {
        // len(max_heap) == 0 or curr_element
        // smaller than max_heap top
        if (this.max_heap.length == 0 || this.max_heap[0] > val) {
            this.max_heap.push(-val);
        }
        else {
            this.min_heap.push(val);
        }
 
        // If size of max_heap + 1 greater
        // than min_heap
        if (this.max_heap.length + 1 > this.min_heap.length) {
            let val = this.max_heap.pop();
            this.min_heap.push(-val);
        }
 
        // If size of min_heap
        // greater than max_heap
        if (this.min_heap.length > this.max_heap.length) {
            let val = this.min_heap.pop();
            this.max_heap.push(-val);
        }
 
        // Finally if sum of sizes is odd,
        // return median
        if ((this.min_heap.length + this.max_heap.length) % 2 === 1) {
            return (-this.max_heap[0]);
        }
 
        // Else return 0
        else {
            return 0;
        }
    }
}
 
// Function to calculate the sum
// of all odd length subarrays
function solve(arr) {
    let ans = 0;
     
    // Size of the array
    let n = arr.length;
    for (let i = 0; i < n; i++) {
         
        // Create an object
        // of class find_median
        let obj = new find_median();
        for (let j = i; j < n; j++) {
             
            // Add value to the heaps
            // using object
            let val = obj.add(arr[j]);
            ans += val;
        }
    }
 
    return (ans);
}
 
// Driver Code
let arr = [4, 2, 5, 1];
console.log(solve(arr));
 
// This code is contributed by vinayetbi1.


Output

18

Time Complexity: O(N2 * Log(N))  
Auxiliary Space: O(N)



Similar Reads

Minimum sum of medians of all possible K length subsequences of a sorted array
Given a sorted array arr[] consisting of N integers and a positive integer K(such that N%K is 0), the task is to find the minimum sum of the medians of all possible subsequences of size K such that each element belongs to only one subsequence. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6}, K = 2Output: 6Explanation:Consider the subsequences of size K
7 min read
Make all the elements of array odd by incrementing odd-indexed elements of odd-length subarrays
Given an array arr[] of size N, the task is to make all the array elements odd by choosing an odd length subarray of arr[] and increment all odd positioned elements by 1 in this subarray. Print the count of such operations required. Examples: Input: arr[] = {2, 3, 4, 3, 5, 3, 2}Output: 2Explanation:In first operation, choose the subarray {2, 3, 4}
9 min read
Minimum flips of odd indexed elements from odd length subarrays to make two given arrays equal
Given two binary arrays X[] and Y[] of size N, the task is to convert array X[] into array Y[] by minimum number of operations of selecting any subarray of odd length and flipping all odd-indexed elements from the subarray. Examples: Input: X[] = {1, 0, 0, 0, 0, 1}, Y[] = {1, 1, 0, 1, 1, 1}Output: 2Explanation:Initially, X[] is {1, 0, 0, 0, 0, 1}.O
8 min read
Area of a Triangle from the given lengths of medians
Given three integers A,B and C which denotes length of the three medians of a triangle, the task is to calculate the area of the triangle. A median of a triangle is a line segment joining a vertex to the midpoint of the opposite side, thus bisecting that side. Examples: Input: A = 9, B = 12, C = 15 Output: 72.0Input: A = 39, B = 42, C = 45 Output:
4 min read
Maximum length L such that the sum of all subarrays of length L is less than K
Given an array of length N and an integer K. The task is to find the maximum length L such that all the subarrays of length L have sum of its elements less than K.Examples: Input: arr[] = {1, 2, 3, 4, 5}, K = 20 Output: 5 The only subarray of length 5 is the complete array and (1 + 2 + 3 + 4 + 5) = 15 < 20. Input: arr[] = {1, 2, 3, 4, 5}, K = 10
8 min read
Split array into K subarrays such that sum of maximum of all subarrays is maximized
Given an array arr[] of size N and a number K, the task is to partition the given array into K contiguous subarrays such that the sum of the maximum of each subarray is the maximum possible. If it is possible to split the array in such a manner, then print the maximum possible sum. Otherwise, print "-1". Examples: Input: arr[] = {5, 3, 2, 7, 6, 4},
11 min read
Split into K subarrays to minimize the maximum sum of all subarrays
Given an Array[] of N elements and a number K. ( 1 <= K <= N ) . Split the given array into K subarrays (they must cover all the elements). The maximum subarray sum achievable out of K subarrays formed, must be the minimum possible. Find that possible subarray sum.Examples: Input : Array[] = {1, 2, 3, 4}, K = 3 Output : 4 Optimal Split is {1,
15 min read
Check if Array can be split into subarrays such that XOR of length of Longest Decreasing Subsequences of those subarrays is 0
Given an array of integers arr[] of size N, the task is to check whether arr[] can be split into different subarrays such that on taking the XOR of lengths of LDS (Longest decreasing subsequences) of all the subarrays is equal to 0. Print 'YES' if it is possible to split else print 'NO'. Examples: Input: arr[] = {1, 0, 3, 4, 5}Output: YESExplanatio
6 min read
Find odd-length Subsequences containing only odd elements
Given an array arr[] of length N, the task is to find all the possible odd-length subsequences containing odd elements only. Examples: Input: N = 6, arr[] = {2, 3, 4, 3, 7, 9}Output: {{3}, {3}, {7}, {3, 3, 7}, {9}, {3, 3, 9}, {3, 7, 9}, {3, 7, 9}} Input: N = 2, arr[] = {1, 3}Output: {{1}, {3}} Approach: The above problem can be solved with the belo
6 min read
Split given arrays into subarrays to maximize the sum of maximum and minimum in each subarrays
Given an array arr[] consisting of N integers, the task is to maximize the sum of the difference of the maximum and minimum in each subarrays by splitting the given array into non-overlapping subarrays. Examples: Input: arr[] = {8, 1, 7, 9, 2}Output: 14Explanation:Split the given array arr[] as {8, 1}, {7, 9, 2}. Now, the sum of the difference maxi
7 min read
Make sum of all subarrays of length K equal by only inserting elements
Given an array arr[] of length N such that (1 <= arr[i] <= N), the task is to modify the array, by only inserting elements within the range [1, N], such that the sum of all subarrays of length K become equal. Print the modified array, if possible. Else print "Not possible".Examples: Input: arr[] = {1, 2, 2, 1}, K = 2 Output: 1 2 1 2 1 Explana
7 min read
Generate a unique Array of length N with sum of all subarrays divisible by N
Given an integer N, the task is to make an array of unique elements of length N such that all subarrays sum modulo N equals to zero. Examples: Input: N = 6 Output: 6 12 18 24 30 36 Explanation: Since all elements are a multiple of 6. Hence all subarrays add up to a sum divisible by 6.Input: N = 4 Output: 4 8 12 16 Approach: We can observe that for
3 min read
Minimum replacements required to make sum of all K-length subarrays equal
Given an array arr[] consisting of N positive integers and an integer K, the task is to make the sum of all K-length subarrays equal by replacing minimum number of array elements with any integer. Examples: Input: arr[] = {3, 4, 3, 5, 6}, K = 2Output: 2Explanation: Operation 1: Replacing arr[3] by 4 modifies arr[] to {3, 4, 3, 4, 6}.Operation 2: Re
7 min read
Maximize product of min value of subarray and sum of subarray over all subarrays of length K
Given an array arr[] of N integers, the task is to find the maximum possible value of (min * sum) among all possible subarrays having K elements, where min denotes the smallest integer of the subarray and sum denotes the sum of all elements of the subarray. Example: Input: arr[] = {1, 2, 3, 2}, K = 3Output: 14Explanation: For the subarray {2, 3, 2}
7 min read
Count of numbers of length N having prime numbers at odd indices and odd numbers at even indices
Given a number N, the task is to calculate the count of numbers of length N having prime numbers at odd indices and odd numbers at even indices. Example: Input : N = 1Output: 5Explanation : All valid numbers length 1 are 1, 3, 5, 7, 9, here we have only 1 odd index, therefore we have 5 valid numbers. Input: N = 2Output: 20 Explanation: There are 20
5 min read
Find all K length subarrays containing only 1s in given Binary String
Given a binary string str[], the task is to find all possible K length subarrays containing only 1s and print their starting and ending index. Examples: Input: str = "0101000", K=1Output: 1 13 3Explanation: Substrings at positions 1 and 3 are the substrings with value 1. Input: str = "11111001", K=3Output: 0 21 32 4 Approach: The given problem can
6 min read
Queries to find maximum sum contiguous subarrays of given length in a rotating array
Given an array arr[] of N integers and Q queries of the form {X, Y} of the following two types: If X = 1, rotate the given array to the left by Y positions.If X = 2, print the maximum sum subarray of length Y in the current state of the array. Examples: Input: N = 5, arr[] = {1, 2, 3, 4, 5}, Q = 2, Query[][] = {{1, 2}, {2, 3}}Output:Query 1: 3 4 5
13 min read
Find an N-length permutation that contains subarrays with sum less than Bitwise XOR
Given a positive integer N, the task is to find a permutation of length N having Bitwise OR of any of its subarray greater than or equal to the length of the subarray. Examples: Input: N = 5 Output: 1 3 5 2 4 Explanation: Consider the subarray {1, 3, 5} from the permutation {1, 3, 5, 2, $}. Length of the subarray = 3 Bitwise OR of the subarray = 1
3 min read
Javascript Program for Queries to find maximum sum contiguous subarrays of given length in a rotating array
Given an array arr[] of N integers and Q queries of the form {X, Y} of the following two types: If X = 1, rotate the given array to the left by Y positions.If X = 2, print the maximum sum subarray of length Y in the current state of the array. Examples:  Input: N = 5, arr[] = {1, 2, 3, 4, 5}, Q = 2, Query[][] = {{1, 2}, {2, 3}}Output:Query 1: 3 4 5
5 min read
Generate an N-length array having length of non-decreasing subarrays maximized and minimum difference between first and last array elements
Given an array arr[ ] of size N, the task is to print an N-length array whose sum of lengths of all non-decreasing subarrays is maximum and the difference between the first and last elements is minimum. Examples: Input: N = 5, arr = {4, 3, 5, 3, 2}Output: {3, 4, 5, 2, 3}Explanation: Difference between the first and last element is minimum, i.e. 3 -
6 min read
Reduce given array by replacing subarrays of length at least K consisting of even numbers with their length
Given an array arr[] of length N, the task is to replace all subarrays of only even elements by their length if the length is greater than or equal to K. Examples: Input: arr[] = {3, 6, 10, 2, 7, 6, 4, 8}, K = 2Output: 3 3 7 3Explanation: There are two subarrays with consecutive even numbers {6, 10, 2} and {6, 4, 8}. So they are replaced by their l
6 min read
Generate an Array of length N having K subarrays as permutations of their own length
Given integers N and K, the task is to generate an array of length N which contains exactly K subarrays as a permutation of 1 to X where X is the subarray length. There may exist multiple answers you may print any one of them. If no array is possible to construct then print -1. Note: A Permutation of length N is a list of integers from 1 to N(inclu
7 min read
Split array into K disjoint subarrays such that sum of each subarray is odd.
Given an array arr[] containing N elements, the task is to divide the array into K(1 ? K ? N) subarrays and such that the sum of elements of each subarray is odd. Print the starting index (1 based indexing) of each subarray after dividing the array and -1 if no such subarray exists.Note: For all subarrays S1, S2, S3, ..., SK: The intersection of S1
8 min read
Count subarrays having sum of elements at even and odd positions equal
Given an array arr[] of integers, the task is to find the total count of subarrays such that the sum of elements at even position and sum of elements at the odd positions are equal. Examples: Input: arr[] = {1, 2, 3, 4, 1}Output: 1Explanation: {3, 4, 1} is the only subarray in which sum of elements at even position {3, 1} = sum of element at odd po
7 min read
Sum of all odd length palindromic numbers within the range [L, R]
Given two integers [Tex]L [/Tex]and [Tex]R [/Tex], the task is to find the sum of all the palindromic numbers within the range [L, R] which are of odd length.Examples: Input: L = 10, R = 130 Output: 333 101 + 111 + 121 = 333Input: L = 110, R = 1130 Output: 49399 Approach: Iterate from [Tex]L [/Tex]to [Tex]R [/Tex]and for every number check whether
10 min read
For all Array elements find Product of Sum of all smaller and Sum of all greater elements
Given an array arr[] of integers of length N, the task is to find the product of the sum of all the numbers larger than that number with the sum of all the numbers less than that number for each number in the array. Examples: Input: arr[] = {8, 4, 9, 3}, N = 4Output:- 63, 51, 0, 0Explanation:For first number 8: Sum of elements smaller than this is
15 min read
Modify Binary Tree by replacing all nodes at even and odd levels by their nearest even or odd perfect squares respectively
Given a Binary Tree consisting of N nodes, the task is to replace all the nodes that are present at even-numbered levels in a Binary Tree with their nearest even perfect square and replace nodes at odd-numbered levels with their nearest odd perfect square. Examples: Input: 5 / \ 3 2 / \ 16 19 Output: 9 / \ 4 4 / \ 9 25 Explanation: Level 1: Nearest
13 min read
Differences between number of increasing subarrays and decreasing subarrays in k sized windows
Given an array of integers and k, find the difference between the number of the strictly increasing number of subarrays (of size more than one) and the number of the strictly decreasing subarray in the window of size k. Examples: Input : nums = {10, 20, 30, 15, 15}; k = 3; Output : 3, 0, -1 Explanation For the first window of [10, 20, 30], there ar
8 min read
Split given Array in minimum number of subarrays such that rearranging the order of subarrays sorts the array
Given an array arr[] consisting of N integers, the task is to find the minimum number of splitting of array elements into subarrays such that rearranging the order of subarrays sorts the given array. Examples: Input: arr[] = {6, 3, 4, 2, 1}Output: 4Explanation:The given array can be divided into 4 subarrays as {6}, {3, 4}, {2}, {1} and these subarr
7 min read
Absolute difference between sum of even elements at even indices & odd elements at odd indices in given Array
Given an array arr[] containing N elements, the task is to find the absolute difference between the sum of even elements at even indices & the count of odd elements at odd indices. Consider 1-based indexing Examples: Input: arr[] = {3, 4, 1, 5}Output: 0Explanation: Sum of even elements at even indices: 4 {4}Sum of odd elements at odd indices: 4
5 min read
three90RightbarBannerImg