Split array into K disjoint subarrays such that sum of each subarray is odd.
Last Updated :
06 Jan, 2023
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, S2, S3, ..., SK should be NULL.
- The union of S1, S2, S3, ..., SK should be equal to the array.
Examples:
Input: N = 5, arr[] = {7, 2, 11, 4, 19}, K = 3
Output: 1 3 5
Explanation:
When the given array arr[] is divided into K = 3 parts, the possible subarrays are: {7, 2}, {11, 4} and {19}
Input: N = 5, arr[] = {2, 4, 6, 8, 10}, K = 3
Output: -1
Explanation:
It is impossible to divide the array arr[] into K = 3 subarrays as all the elements are even and the sum of every subarray is even.
Approach: It can be easily observed that for any subarray to have odd sum:
- Since only odd values can lead to odd sum, hence we can ignore the even values.
- The number of odd values must also be odd.
- So we need at least K odd values in the array for K subarrays. If K is greater than the number of odd elements then the answer is always -1.
Below is the implementation of the above approach:
C++
// C++ program to split the array into K
// disjoint subarrays so that the sum of
// each subarray is odd.
#include <iostream>
using namespace std;
// Function to split the array into K
// disjoint subarrays so that the sum of
// each subarray is odd.
void split(int a[], int n, int k)
{
// Number of odd elements
int odd_ele = 0;
// Loop to store the number
// of odd elements in the array
for (int i = 0; i < n; i++)
if (a[i] % 2)
odd_ele++;
// If the count of odd elements is < K
// then the answer doesnt exist
if (odd_ele < k)
cout << -1;
// If the number of odd elements is
// greater than K and the extra
// odd elements are odd, then the
// answer doesn't exist
else if (odd_ele > k && (odd_ele - k) % 2)
cout << -1;
else {
for (int i = 0; i < n; i++) {
if (a[i] % 2) {
// Printing the position of
// odd elements
cout << i + 1 << " ";
// Decrementing K as we need positions
// of only first k odd numbers
k--;
}
// When the positions of the first K
// odd numbers are printed
if (k == 0)
break;
}
}
}
// Driver code
int main()
{
int n = 5;
int arr[] = { 7, 2, 11, 4, 19 };
int k = 3;
split(arr, n, k);
}
Java
// Java program to split the array into K
// disjoint subarrays so that the sum of
// each subarray is odd.
class GFG{
// Function to split the array into K
// disjoint subarrays so that the sum of
// each subarray is odd.
static void split(int a[], int n, int k)
{
// Number of odd elements
int odd_ele = 0;
// Loop to store the number
// of odd elements in the array
for (int i = 0; i < n; i++)
if (a[i] % 2==1)
odd_ele++;
// If the count of odd elements is < K
// then the answer doesnt exist
if (odd_ele < k)
System.out.print(-1);
// If the number of odd elements is
// greater than K and the extra
// odd elements are odd, then the
// answer doesn't exist
else if (odd_ele > k && (odd_ele - k) % 2==1)
System.out.print(-1);
else {
for (int i = 0; i < n; i++) {
if (a[i] % 2==1) {
// Printing the position of
// odd elements
System.out.print(i + 1+ " ");
// Decrementing K as we need positions
// of only first k odd numbers
k--;
}
// When the positions of the first K
// odd numbers are printed
if (k == 0)
break;
}
}
}
// Driver code
public static void main(String[] args)
{
int n = 5;
int arr[] = { 7, 2, 11, 4, 19 };
int k = 3;
split(arr, n, k);
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 program to split the array into K
# disjoint subarrays so that the sum of
# each subarray is odd.
# Function to split the array into K
# disjoint subarrays so that the sum of
# each subarray is odd.
def split(a, n, k) :
# Number of odd elements
odd_ele = 0;
# Loop to store the number
# of odd elements in the array
for i in range(n) :
if (a[i] % 2) :
odd_ele += 1;
# If the count of odd elements is < K
# then the answer doesnt exist
if (odd_ele < k) :
print(-1);
# If the number of odd elements is
# greater than K and the extra
# odd elements are odd, then the
# answer doesn't exist
elif (odd_ele > k and (odd_ele - k) % 2) :
print(-1);
else :
for i in range(n) :
if (a[i] % 2) :
# Printing the position of
# odd elements
print(i + 1 ,end= " ");
# Decrementing K as we need positions
# of only first k odd numbers
k -= 1;
# When the positions of the first K
# odd numbers are printed
if (k == 0) :
break;
# Driver code
if __name__ == "__main__" :
n = 5;
arr = [ 7, 2, 11, 4, 19 ];
k = 3;
split(arr, n, k);
# This code is contributed by AnkitRai01
C#
// C# program to split the array into K
// disjoint subarrays so that the sum of
// each subarray is odd.
using System;
class GFG{
// Function to split the array into K
// disjoint subarrays so that the sum of
// each subarray is odd.
static void split(int []a, int n, int k)
{
// Number of odd elements
int odd_ele = 0;
// Loop to store the number
// of odd elements in the array
for (int i = 0; i < n; i++)
if (a[i] % 2 == 1)
odd_ele++;
// If the count of odd elements is < K
// then the answer doesnt exist
if (odd_ele < k)
Console.Write(-1);
// If the number of odd elements is
// greater than K and the extra
// odd elements are odd, then the
// answer doesn't exist
else if (odd_ele > k && (odd_ele - k) % 2 == 1)
Console.Write(-1);
else {
for (int i = 0; i < n; i++) {
if (a[i] % 2 == 1) {
// Printing the position of
// odd elements
Console.Write(i + 1 + " ");
// Decrementing K as we need positions
// of only first k odd numbers
k--;
}
// When the positions of the first K
// odd numbers are printed
if (k == 0)
break;
}
}
}
// Driver code
public static void Main(string[] args)
{
int n = 5;
int []arr = { 7, 2, 11, 4, 19 };
int k = 3;
split(arr, n, k);
}
}
// This code is contributed by AnkitRai01
JavaScript
<script>
// Javascript program to split the array into K
// disjoint subarrays so that the sum of
// each subarray is odd.
// Function to split the array into K
// disjoint subarrays so that the sum of
// each subarray is odd.
function split(a, n, k)
{
// Number of odd elements
let odd_ele = 0;
// Loop to store the number
// of odd elements in the array
for (let i = 0; i < n; i++)
if (a[i] % 2)
odd_ele++;
// If the count of odd elements is < K
// then the answer doesnt exist
if (odd_ele < k)
document.write(-1);
// If the number of odd elements is
// greater than K and the extra
// odd elements are odd, then the
// answer doesn't exist
else if (odd_ele > k && (odd_ele - k) % 2)
document.write(1);
else {
for (let i = 0; i < n; i++) {
if (a[i] % 2) {
// Printing the position of
// odd elements
document.write(i + 1 + " ");
// Decrementing K as we need positions
// of only first k odd numbers
k--;
}
// When the positions of the first K
// odd numbers are printed
if (k == 0)
break;
}
}
}
// Driver code
let n = 5;
let arr = [ 7, 2, 11, 4, 19 ];
let k = 3;
split(arr, n, k);
// This code is contributed by gfgking
</script>
Time Complexity: O(N)
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Related Topic: Subarrays, Subsequences, and Subsets in Array
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read