Construct an Array having K Subarrays with all distinct elements
Last Updated :
13 Dec, 2022
Given integers N and K, the task is to construct an array arr[] of size N using numbers in the range [1, N] such that it has K sub-arrays whose all the elements are distinct.
Note: If there are multiple possible answers return any of them.
Examples:
Input: N = 5, K = 8
Output: {1, 2, 3, 3, 3}
Explanation: This array has the distinct sub-arrays as {1}, {2}, {3}, {3}, {3}, {1, 2}, {2, 3}, {1, 2, 3}
Input: N = 6, K = 21
Output: {1, 2, 3, 4, 5, 6}
Explanation: This array has the 21 distinct sub-arrays.
Approach: The idea to solve the problem is based on the following mathematical observation:
- N elements will definitely form N subarrays of size 1 having unique elements.
- Now the remaining task is to form array such that (N-K subarrays) of size more than 1 have all distinct elements.
- Also it is known number of subarrays of size more than 1 from X elements are (X*(X+1))/2 - X = X*(X-1)/2.
- If X elements are distinct all these subarrays have all distinct elements.
So to form the array there is a need for such X distinct elements such that X*(X-1)/2 = K-N.
So in each step, add a distinct element until the above condition is satisfied. After that repeat the last element till the array size becomes N (because if the last element is repeated it will not effect count of subarrays with all distinct elements).
Follow these steps to solve the problem:
- Decrement K by K - N because every integer contributes to a distinct subarray of size 1.
- Now Initialize a variable num = 0 to keep track of integers that are being added to the array and the number of subarrays formed.
- From K, decrement the number of distinct subarrays formed after adding (num + 1) to the new array. (till num <= K).
- Check if array size has reached N. If not add the num - K repeated times till the array fills.
Below is the implementation for the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to construct the array
// with k distinct subarrays
vector<int> construct_array(int n, int k)
{
// Each individual integers
// contributes to one subarray
k = k - n;
// Initialize a variable to keep
// track of integers that are
// adding to the array
int num = 0;
// Initialize the res to
// store the array
vector<int> res;
// Push as many possible distinct
// integers into the vector
while (k >= num) {
res.push_back(num + 1);
// Decrement the count of
// distinct subarrays incrementing
k -= num;
num++;
}
// If still it is not possible to
// get the array of size n then
// adding n-k at the end make num-k
// more distinct subarrays
while (res.size() < n) {
res.push_back(num - k);
}
// Return the array
return res;
}
// Driver code
int main()
{
int N = 5;
int K = 8;
// Function call
vector<int> ans = construct_array(N, K);
for (int x : ans)
cout << x << " ";
return 0;
}
Java
// JAVA program for the above approach
import java.util.*;
class GFG {
// Function to construct the array
// with k distinct subarrays
public static ArrayList<Integer> construct_array(int n,
int k)
{
// Each individual integers
// contributes to one subarray
k = k - n;
// Initialize a variable to keep
// track of integers that are
// adding to the array
int num = 0;
// Initialize the res to
// store the array
ArrayList<Integer> res = new ArrayList<Integer>();
// Push as many possible distinct
// integers into the vector
while (k >= num) {
res.add(num + 1);
// Decrement the count of
// distinct subarrays incrementing
k -= num;
num++;
}
// If still it is not possible to
// get the array of size n then
// adding n-k at the end make num-k
// more distinct subarrays
while (res.size() < n) {
res.add(num - k);
}
// Return the array
return res;
}
// Driver code
public static void main(String[] args)
{
int N = 5;
int K = 8;
// Function call
ArrayList<Integer> ans = construct_array(N, K);
for (int x = 0; x < ans.size(); x++)
System.out.print(ans.get(x) + " ");
}
}
// This code is contributed by Taranpreet
Python3
# Python3 code to implement the approach
# Function to construct the array
# with k distinct subarrays
def construct_array(n, k):
# Each individual integers
# contributes to one subarray
k -= n
# // Initialize a variable to keep
# track of integers that are
# adding to the array
num = 0
# Initialize the res to
# store the array
res = []
# Push as many possible distinct
# integers into the vector
while k >= num:
res.append(num + 1)
# Decrement the count of
# distinct subarrays incrementing
k -= num
num += 1
# If still it is not possible to
# get the array of size n then
# adding n-k at the end make num-k
# more distinct subarrays
while len(res) < n:
res.append(num - k)
return res
# Driver code
N = 5
K = 8
# function call
ans = construct_array(N, K)
print(" ".join(list(map(str, ans))))
# This code is contributed by phasing17
C#
// C# program for the above approach
using System;
using System.Collections;
public class GFG{
// Function to construct the array
// with k distinct subarrays
public static ArrayList construct_array(int n,
int k)
{
// Each individual integers
// contributes to one subarray
k = k - n;
// Initialize a variable to keep
// track of integers that are
// adding to the array
int num = 0;
// Initialize the res to
// store the array
ArrayList res = new ArrayList();
// Push as many possible distinct
// integers into the vector
while (k >= num) {
res.Add(num + 1);
// Decrement the count of
// distinct subarrays incrementing
k -= num;
num++;
}
// If still it is not possible to
// get the array of size n then
// adding n-k at the end make num-k
// more distinct subarrays
while (res.Count < n) {
res.Add(num - k);
}
// Return the array
return res;
}
// Driver code
static public void Main (){
int N = 5;
int K = 8;
// Function call
ArrayList ans = construct_array(N, K);
foreach(int x in ans)
Console.Write(x + " ");
}
}
// This code is contributed by hrithikgarg03188.
JavaScript
<script>
// JavaScript program for the above approach
// Function to construct the array
// with k distinct subarrays
const construct_array = (n, k) => {
// Each individual integers
// contributes to one subarray
k = k - n;
// Initialize a variable to keep
// track of integers that are
// adding to the array
let num = 0;
// Initialize the res to
// store the array
let res = [];
// Push as many possible distinct
// integers into the vector
while (k >= num) {
res.push(num + 1);
// Decrement the count of
// distinct subarrays incrementing
k -= num;
num++;
}
// If still it is not possible to
// get the array of size n then
// adding n-k at the end make num-k
// more distinct subarrays
while (res.length < n) {
res.push(num - k);
}
// Return the array
return res;
}
// Driver code
let N = 5;
let K = 8;
// Function call
let ans = construct_array(N, K);
for (let x in ans)
document.write(`${ans[x]} `);
// This code is contributed by rakeshsahni
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
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
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
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
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