Open In App

Find K-Avoiding Array

Last Updated : 07 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given two integers n and k, the task is to find such an array with the minimum possible sum that corresponds to the given condition of a k-avoiding array of length n.

Note: An array of distinct positive integers is called a k-avoiding array if there does not exist any pair of different elements that sum to k.

Examples:

Input: n = 5, k = 4
Output: 1 2 4 5 6
Explanation: Consider the k-avoiding array [1, 2, 4, 5, 6], which has a sum of 18.
It can be proven that there is no k-avoiding array with a sum less than 18.

Input: n = 15, k = 8
Output: 1 2 3 4 8 9 10 11 12 13 14 15 16 17 18

Approach: To solve the problem follow the below illustrations:

Illustration:

Let us dry-run the example:

  • Let’s take, n = 5 and target = 4, we start with 1. We find that 1 is not present in the set, so we add it to the answer, and we add k = 4 – 1 = 3 to the set. Now the set contains {3}.
  • We then increase the counter to 2, and the total number of elements we have to add is 4. Now we check for 2, which is also not present in the set, so we add it to the answer.
  • Moving on, we increase the counter to 3 and check if 3 is present in the set. Since it is present, we do not add it to the answer.
  • Continuing, we check for 4, which is not present in the set, so we add it to the answer.
  • Finally, we check for 5 and 6, and since they are not present in the set, we add them to the answer.
  • The displayed array should contain these minimum 5 numbers that need to be added to achieve the minimum sum while adhering the condition of k-avoiding array.

Follow the steps to solve the problem:

  • We will use a Set Data Structure to store the numbers that should not be included in the K-avoiding array.
  • If we include a number x then we can not include K-x in our array so that we can avoid making the sum of K.
  • By storing such numbers in the set we can skip numbers that should not be part of the array.
  • We just start with 1 and increment numbers and include which are possible.

Below is the implementation of above approach:

C++




// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
vector<int> minimumSum(int n, int k)
{
 
    // set to store the no. that
    // should not occur to store
    // result
    set<int> s;
    vector<int> v;
    int no = 1;
    int ans = 0;
 
    // no. of times the code is running
    while (n > 0) {
 
        // We are storing the number
        // that should not be present
        // to avoid k sum
        if (s.find(no) == s.end()) {
            s.insert(k - no);
            v.push_back(no);
            n--;
        }
        no++;
    }
 
    // Returning the answer
    return v;
}
 
// Driver Code
int main()
{
    int n;
    n = 5;
    int target;
    target = 4;
 
    // Function call
    vector<int> t = minimumSum(n, target);
    cout << "The K-avoiding array is : ";
    for (int x = 0; x < t.size(); x++) {
        cout << t[x] << " ";
    }
    cout << endl;
    return 0;
}


Java




import java.util.*;
 
public class Main {
    public static ArrayList<Integer> minimumSum(int n, int k) {
        // Set to store the numbers that
        // should not occur to store the result
        HashSet<Integer> s = new HashSet<>();
        ArrayList<Integer> v = new ArrayList<>();
        int no = 1;
 
        // Number of times the code is running
        while (n > 0) {
            // We are storing the number
            // that should not be present
            // to avoid k sum
            if (!s.contains(no)) {
                s.add(k - no);
                v.add(no);
                n--;
            }
            no++;
        }
        // Returning the answer
        return v;
    }
 
    public static void main(String[] args) {
        int n = 5;
        int target = 4;
 
        // Function call
        ArrayList<Integer> t = minimumSum(n, target);
        System.out.print("The K-avoiding array is : ");
        for (int x = 0; x < t.size(); x++) {
            System.out.print(t.get(x) + " ");
        }
        System.out.println();
    }
}


Python3




def minimum_sum(n, k):
    s = set()
    v = []
    no = 1
 
    while n > 0:
        if no not in s:
            s.add(k - no)
            v.append(no)
            n -= 1
        no += 1
 
    return v
 
# Driver Code
if __name__ == "__main__":
    n = 5
    target = 4
 
    # Function call
    t = minimum_sum(n, target)
    print("The K-avoiding array is:", end=" ")
    for x in t:
        print(x, end=" ")
    print()
#Contributed by Aditi Tyagi


C#




using System;
using System.Collections.Generic;
 
public class Program
{
    public static List<int> MinimumSum(int n, int k)
    {
        // HashSet to store the numbers that
        // should not occur to obtain the result
        HashSet<int> s = new HashSet<int>();
        List<int> v = new List<int>();
        int no = 1;
 
        // Number of times the code is running
        while (n > 0)
        {
            // We are storing the number
            // that should not be present
            // to avoid k sum
            if (!s.Contains(no))
            {
                s.Add(k - no);
                v.Add(no);
                n--;
            }
            no++;
        }
        // Returning the answer
        return v;
    }
 
    public static void Main(string[] args)
    {
        int n = 5;
        int target = 4;
 
        // Function call
        List<int> t = MinimumSum(n, target);
        Console.Write("The K-avoiding array is: ");
        for (int x = 0; x < t.Count; x++)
        {
            Console.Write(t[x] + " ");
        }
        Console.WriteLine();
    }
}


Javascript




// Function to generate an array of n numbers that avoids summing up to k
function minimumSum(n, k) {
    const s = new Set(); // A set to keep track of numbers that should be avoided
    const v = []; // An array to store the result
    let no = 1; // Initialize a number
 
    while (n > 0) {
        if (!s.has(no)) { // Check if the number should be avoided
            s.add(k - no); // Add the complementary number to the set
            v.push(no); // Add the current number to the result array
            n--; // Decrease the count of numbers to generate
        }
        no++; // Increment the number for the next iteration
    }
 
    return v; // Return the array of numbers that avoids summing up to k
}
 
const n = 5; // Number of elements to generate
const target = 4; // Target sum to avoid
 
// Function call to generate the K-avoiding array
const result = minimumSum(n, target);
 
// Output the result
console.log("The K-avoiding array is: " + result.join(' '));


Output

The K-avoiding array is : 1 2 4 5 6 











Time Complexity: O(N*logN)
Auxillary Space: O(N)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads