Divide array into two arrays which does not contain any pair with sum K

Given an array arr[] consisting of N non-negative distinct integers and an integer K, the task is to distribute the array in two arrays such that both the arrays does not contain a pair with sum K.
Examples:
Input: arr[] = {1, 0, 2, 3, 4, 7, 8, 9}, K = 4
Output:Â
3, 2, 4, 7, 8, 9Â
0, 1Â
Explanation: Pairs (1, 3) and (0, 4) from the given array cannot be placed in the same array. Therefore, 0, 1 can be placed in an array and 3, 4 can be placed in the other array. The remaining array elements can be placed in any of the two arrays.Input: arr[] = {0, 1, 2, 4, 5, 6, 7, 8, 9}, K = 7
Output:Â
0, 1, 2, 4Â
5, 6, 7, 9, 8Â
Â
Approach: The idea is to traverse the array and place the array elements greater than K / 2 in one array and the remaining elements in the other array. Follow the steps below to solve the problem:
- Initialize two separate vectors first and second to store the two distributed arrays.
- Since all the array elements are distinct, elements greater than K/2 can be stored in one array and the remaining elements in the other.
- Traverse the given array and for each element, check if arr[i] is greater than K/2 or not. If found to be true, insert that element into vector second. Otherwise, insert it into vector first.
- After complete traversal of the array, print elements in both the vectors.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;Â
// Function to split the given// array into two separate arrays// satisfying given conditionvoid splitArray(int a[], int n,                int k){    // Stores resultant arrays    vector<int> first, second;Â
    // Traverse the array    for (int i = 0; i < n; i++) {Â
        // If a[i] is smaller than        // or equal to k/2        if (a[i] <= k / 2)            first.push_back(a[i]);        else            second.push_back(a[i]);    }Â
    // Print first array    for (int i = 0; i < first.size();         i++) {        cout << first[i] << " ";    }Â
    // Print second array    cout << "\n";    for (int i = 0; i < second.size();         i++) {        cout << second[i] << " ";    }}Â
// Driver Codeint main(){Â
    // Given K    int k = 5;Â
    // Given array    int a[] = { 0, 1, 3, 2, 4, 5,                6, 7, 8, 9, 10 };Â
    // Given size    int n = sizeof(a)            / sizeof(int);Â
    splitArray(a, n, k);Â
    return 0;} |
Java
// Java program for the above approach import java.util.*;Â
class GFG{  // Function to split the given// array into two separate arrays// satisfying given conditionstatic void splitArray(int a[], int n,                       int k){         // Stores resultant arrays    Vector<Integer> first = new Vector<>();    Vector<Integer> second = new Vector<>();Â
    // Traverse the array    for(int i = 0; i < n; i++)    {                 // If a[i] is smaller than        // or equal to k/2        if (a[i] <= k / 2)            first.add(a[i]);        else            second.add(a[i]);    }      // Print first array    for(int i = 0; i < first.size(); i++)    {        System.out.print(first.get(i) + " ");    }      // Print second array    System.out.println();    for(int i = 0; i < second.size(); i++)    {        System.out.print(second.get(i) + " ");    }}  // Driver Codepublic static void main(String[] args){         // Given K    int k = 5;      // Given array    int a[] = { 0, 1, 3, 2, 4, 5,                6, 7, 8, 9, 10 };      int n = a.length;         splitArray(a, n, k);}}Â
// This code is contributed by code_hunt |
Python3
# Python3 program for the above approachÂ
# Function to split the given# array into two separate arrays# satisfying given conditiondef splitArray(a, n, k):         # Stores resultant arrays    first = []    second = []Â
    # Traverse the array    for i in range(n):                 # If a[i] is smaller than        # or equal to k/2        if (a[i] <= k // 2):            first.append(a[i])        else:            second.append(a[i])Â
    # Print first array    for i in range(len(first)):        print(first[i], end = " ")Â
    # Print second array    print("\n", end = "")    for i in range(len(second)):        print(second[i], end = " ")Â
# Driver Codeif __name__ == '__main__':         # Given K    k = 5         # Given array    a = [ 0, 1, 3, 2, 4, 5,           6, 7, 8, 9, 10 ]                n = len(a)         splitArray(a, n, k)     # This code is contributed by bgangwar59 |
C#
// C# program for the above approachusing System;using System.Collections.Generic;Â
class GFG{   // Function to split the given// array into two separate arrays// satisfying given conditionstatic void splitArray(int[] a, int n,                       int k){         // Stores resultant arrays    List<int> first = new List<int>();    List<int> second = new List<int>();Â
    // Traverse the array    for(int i = 0; i < n; i++)    {                 // If a[i] is smaller than        // or equal to k/2        if (a[i] <= k / 2)            first.Add(a[i]);        else            second.Add(a[i]);    }       // Print first array    for(int i = 0; i < first.Count; i++)    {        Console.Write(first[i] + " ");    }       // Print second array    Console.WriteLine();    for(int i = 0; i < second.Count; i++)    {        Console.Write(second[i] + " ");    }}   // Driver Codepublic static void Main(){         // Given K    int k = 5;       // Given array    int[] a = { 0, 1, 3, 2, 4, 5,                6, 7, 8, 9, 10 };       int n = a.Length;          splitArray(a, n, k);}}   // This code is contributed by susmitakundugoaldanga |
Javascript
<script>// Javascript program for the above approachÂ
// Function to split the given// array into two separate arrays// satisfying given conditionfunction splitArray(a, n, k){Â
    // Stores resultant arrays    let first = [];    let second = [];Â
    // Traverse the array    for (let i = 0; i < n; i++) {Â
        // If a[i] is smaller than        // or equal to k/2        if (a[i] <= parseInt(k / 2))            first.push(a[i]);        else            second.push(a[i]);    }Â
    // Print first array    for (let i = 0; i < first.length;         i++) {        document.write(first[i] + " ");    }Â
    // Print second array    document.write("<br>");    for (let i = 0; i < second.length;         i++) {        document.write(second[i] + " ");    }}Â
// Driver CodeÂ
// Given Klet k = 5;Â
// Given arraylet a = [ 0, 1, 3, 2, 4, 5,    6, 7, 8, 9, 10 ];Â
// Given sizelet n = a.length;splitArray(a, n, k);Â Â Â Â Â Â Â Â Â // This code is contributed by rishavmahato348.</script> |
0 1 2 3 4 5 6 7 8 9 10
Â
Time Complexity: O(N), where N is the size of the given array.
Auxiliary Space: O(1)
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



