Generate an array of size N according to the given rules
Last Updated :
21 May, 2024
Given a number N, the task is to create an array arr[] of size N, where the value of the element at every index i is filled according to the following rules:
- arr[i] = ((i – 1) – k), where k is the index of arr[i – 1] that has appeared second most recently. This rule is applied when arr[i – 1] is present more than once in the array
- arr[i] = 0. This rule is applied when arr[i – 1] is present only once or when i = 1.
Examples:
Input: N = 8
Output: 0 0 1 0 2 0 2 2
Explanation:
For i = 0: There is no element in the array arr[]. So, 0 is placed in the first index. arr[] = {0}.
For i = 1: There is only one element in the array arr[]. The occurrence of arr[i – 1] (= 0) is only one. Therefore, the array is filled according to the rule 2. arr = {0, 0}.
For i = 2: There are two elements in the array. The second most occurrence of arr[i – 1] = arr[0] = 0. So, arr[2] = 1. arr[] = {0, 0, 1}.
For i = 3: There is no second occurrence of arr[i – 1] = 1. Therefore, arr[3] = 0. arr[] = {0, 0, 1, 0}
For i = 4: The second recent occurrence of arr[i – 1] = 0 is 1. Therefore, (i – 1 – k) = (4 – 1 – 1) = 2. arr[] = {0, 0, 1, 0, 2}.
For i = 5: There is only one occurrence of arr[i – 1] = 2. Therefore, arr[5] = 0. arr[] = {0, 0, 1, 0, 2, 0}.
For i = 6: The second recent occurrence of arr[i – 1] = 0 is 3. Therefore, (i – 1 – k) = (6 – 1 – 3) = 2. arr[] = {0, 0, 1, 0, 2, 0, 2}.
For i = 7: The second recent occurrence of arr[i – 1] = 2 is 4. Therefore, (i – 1 – k) = (7 – 1 – 4) = 2. arr[] = {0, 0, 1, 0, 2, 0, 2, 2}
Input: N = 5
Output: 0 0 1 0 2
Approach: The idea is to first create an array filled with zeroes of size N. Then for every iteration, we search if the element has occurred in the near past. If yes, then we follow rule 1. Else, rule 2 is followed to fill the array.
Below is the implementation of the above approach:
Java
// Java implementation to generate
// an array of size N by following
// the given rules
class GFG
{
static int a[];
// Function to search the most recent
// location of element N
// If not present in the array
// it will return -1
static int search(int a[],int k, int x)
{
int j;
for ( j = k - 1; j > -1 ; j--)
{
if(a[j] == x)
return j ;
}
return -1 ;
}
// Function to generate an array
// of size N by following the given rules
static void genArray(int []arr, int N)
{
// Loop to fill the array
// as per the given rules
for(int i = 0; i < N - 1; i++)
{
// Check for the occurrence
// of arr[i - 1]
if(search(arr, i, arr[i]) == -1)
arr[i + 1] = 0 ;
else
arr[i + 1] = (i-search(arr, i, arr[i])) ;
}
}
// Driver code
public static void main (String[] args)
{
int N = 5 ;
int size = N + 1 ;
int a[] = new int [N];
genArray(a, N) ;
for (int i = 0; i < N ; i ++)
System.out.print(a[i]+" " );
}
}
// This code is contributed by Yash_R
Python
# Python implementation to generate
# an array of size N by following
# the given rules
# Function to search the most recent
# location of element N
# If not present in the array
# it will return -1
def search(a, k, x):
for j in range(k-1, -1, -1) :
if(a[j]== x):
return j
return -1
# Function to generate an array
# of size N by following the given rules
def genArray(arr, N):
# Loop to fill the array
# as per the given rules
for i in range(0, N-1, 1):
# Check for the occurrence
# of arr[i - 1]
if(search(arr, i, arr[i])==-1):
arr[i + 1]= 0
else:
arr[i + 1]=(i-search(arr, i, arr[i]))
# Driver code
if __name__ == "__main__":
N = 5
size = N + 1
a =[0]*N
genArray(a, N)
print(a)
C#
// C# implementation to generate
// an array of size N by following
// the given rules
using System;
public class GFG
{
static int []a;
// Function to search the most recent
// location of element N
// If not present in the array
// it will return -1
static int search(int []a,int k, int x)
{
int j;
for ( j = k - 1; j > -1 ; j--)
{
if(a[j] == x)
return j ;
}
return -1 ;
}
// Function to generate an array
// of size N by following the given rules
static void genArray(int []arr, int N)
{
// Loop to fill the array
// as per the given rules
for(int i = 0; i < N - 1; i++)
{
// Check for the occurrence
// of arr[i - 1]
if(search(arr, i, arr[i]) == -1)
arr[i + 1] = 0 ;
else
arr[i + 1] = (i-search(arr, i, arr[i])) ;
}
}
// Driver code
public static void Main (string[] args)
{
int N = 5 ;
int size = N + 1 ;
int []a = new int [N];
genArray(a, N) ;
for (int i = 0; i < N ; i ++)
Console.Write(a[i]+" " );
}
}
// This code is contributed by AnkitRai01
JavaScript
<script>
// Javascript implementation to generate
// an array of size N by following
// the given rules
// Function to search the most recent
// location of element N
// If not present in the array
// it will return -1
function search( a, k, x)
{
var j;
for ( j = k - 1; j > -1 ; j--)
{
if(a[j] == x)
return j ;
}
return -1 ;
}
// Function to generate an array
// of size N by following the given rules
function genArray(arr, N)
{
// Loop to fill the array
// as per the given rules
for(var i = 0; i < N - 1; i++)
{
// Check for the occurrence
// of arr[i - 1]
if(search(arr, i, arr[i]) == -1)
arr[i + 1] = 0 ;
else
arr[i + 1] = (i-search(arr, i, arr[i])) ;
}
}
// Driver code
var N = 5 ;
var size = N + 1 ;
var a = [0, 0, 0, 0, 0];
genArray(a, N) ;
document.write("["+a+"]");
// This code is contributed by rutvik_56.
</script>
C++
// C++ implementation to generate
// an array of size N by following
// the given rules
#include <bits/stdc++.h>
using namespace std;
// Function to search the most recent
// location of element N
// If not present in the array
// it will return -1
int search(int a[], int k, int x)
{
int j;
for ( j = k - 1; j > -1 ; j--)
{
if(a[j] == x)
return j ;
}
return -1 ;
}
// Function to generate an array
// of size N by following the given rules
void genArray(int arr[], int N)
{
// Loop to fill the array
// as per the given rules
for(int i = 0; i < N - 1; i++)
{
// Check for the occurrence
// of arr[i - 1]
if(search(arr, i, arr[i]) == -1)
arr[i + 1] = 0 ;
else
arr[i + 1] = (i-search(arr, i, arr[i])) ;
}
}
// Driver code
int main()
{
int N = 5 ;
int size = N + 1 ;
int a[] = {0, 0, 0, 0, 0};
genArray(a, N) ;
for (int i = 0; i < N ; i ++)
cout << a[i] << " " ;
return 0;
}
// This code is contributed by shivanisinghss2110
Time Complexity: O(N2)
Auxiliary Space: O(1)
Using Dictionary:
To generate the array of size N while adhering to the given rules with improved efficiency, we can utilize an approach that avoids searching for elements in the array for each iteration. Instead, we can maintain a dictionary to store the most recent index of each element encountered. This approach reduces the time complexity significantly compared to the provided solution by eliminating the need for repeated linear searches.
- We initialize a dictionary to store the most recent index of each element encountered in the array.
- We start filling the array with zeroes.
- For each iteration, we check if the current element has occurred previously.
- If yes, we calculate the difference between the current index and the second most recent occurrence of the element.
- If not, we continue filling the array with zeroes.
- Finally, we return the generated array.
C++
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
vector<int> genArray(int N)
{
vector<int> arr(N);
unordered_map<int, int>
recentIndex; // Map to store most recent index of
// elements
for (int i = 1; i < N; i++) {
if (recentIndex.find(arr[i - 1])
!= recentIndex.end()
&& recentIndex[arr[i - 1]] != i - 1) {
arr[i] = (i - 1) - recentIndex[arr[i - 1]];
}
recentIndex[arr[i - 1]] = i - 1;
}
return arr;
}
// Driver code
int main()
{
int N = 5;
vector<int> result = genArray(N);
for (int num : result) {
cout << num << " ";
}
cout << endl;
return 0;
}
Java
import java.util.HashMap;
import java.util.Map;
public class GenArray {
public static int[] genArray(int N)
{
int[] arr = new int[N];
Map<Integer, Integer> recentIndex
= new HashMap<>(); // Dictionary to store most
// recent index of elements
for (int i = 1; i < N; i++) {
if (recentIndex.containsKey(arr[i - 1])
&& recentIndex.get(arr[i - 1]) != i - 1) {
arr[i]
= (i - 1) - recentIndex.get(arr[i - 1]);
}
recentIndex.put(arr[i - 1], i - 1);
}
return arr;
}
// Driver code
public static void main(String[] args)
{
int N = 5;
int[] result = genArray(N);
for (int num : result) {
System.out.print(num + " ");
}
}
}
// This code is contributed by shivamgupta0987654321
Python
def genArray(N):
arr = [0] * N
recent_index = {} # Dictionary to store most recent index of elements
for i in range(1, N):
if arr[i - 1] in recent_index and recent_index[arr[i - 1]] != i - 1:
arr[i] = i - 1 - recent_index[arr[i - 1]]
recent_index[arr[i - 1]] = i - 1
return arr
# Driver code
if __name__ == "__main__":
N = 5
result = genArray(N)
print(result)
JavaScript
function genArray(N) {
let arr = new Array(N).fill(0);
let recentIndex = {}; // Object to store most recent index of elements
for (let i = 1; i < N; i++) {
if (recentIndex[arr[i - 1]] !== undefined && recentIndex[arr[i - 1]] !== i - 1) {
arr[i] = i - 1 - recentIndex[arr[i - 1]];
}
recentIndex[arr[i - 1]] = i - 1;
}
return arr;
}
// Driver code
let N = 5;
let result = genArray(N);
console.log(result);
Time Complexity: O(N)
Space Complexity: O(N)
Similar Reads
Generate an array of size K which satisfies the given conditions
Given two integers N and K, the task is to generate an array arr[] of length K such that: arr[0] + arr[1] + ... + arr[K - 1] = N.arr[i] > 0 for 0 ? i < K.arr[i] < arr[i + 1] ? 2 * arr[i] for 0 ? i < K - 1. If there are multiple answers find any one of them, otherwise, print -1. Examples:
8 min read
Generate an Array from given Array according to given conditions
Given an array a[] and two integers l and r, the task is to create another array b[] which satisfies the following conditions: l < b[i] < rb[i]-a[i] < b[i+1] - a[i+1], for every i less than n-1 (where n is the size of the array a).b[i] < b[i+1], for every i less than n-1 (where n is the
6 min read
Find an array of size N that satisfies the given conditions
Given three integers N, S, and K, the task is to create an array of N positive integers such that the bitwise OR of any two consecutive elements from the array is odd and there are exactly K subarrays with a sum equal to S where 1 ? K ? N / 2. Examples: Input: N = 4, K = 2, S = 6 Output: 6 7 6 7 Her
8 min read
Generate an Array such that Average of triplet exist in given Array
Given an array A[] of length N and your task is to find an array B[] of size N+2, such that Average of (B[i], B[i+1], B[i+2]) equals to A[i] for each i (1 <= i <= N) . Note: First two elements B[] must be zero. Examples:Input: N = 1, A[] = {3} Output: B[] = {0, 0, 9} Explanation: Let us unders
5 min read
Generate an array having Bitwise AND of the previous and the next element
Given an array of integers arr[] of N elements, the task is to generate another array having (Bitwise) AND of previous and next elements with the following exceptions. The first element is the bitwise AND of the first and the second element.The last element is the bitwise AND of the last and the sec
5 min read
Reorder an Array according to given indices with repetition allowed
Given two integer arrays arr and index of size N, the task is to create a new array by inserting the elements given in the arr array at the indices given by the index array. If a particular position occur multiple time then right shift the right-side array elements and then insert element at given i
6 min read
Generate a N size Array where MEX of every K sized Subarray is X
Given three integers N, K and X. The task is to construct an array of size N where MEX of every K sized subarray is X. Print the constructed array elements, if not possible print -1. Examples: Input: N = 4, K = 3, X = 2Output: 1 3 4 1Explanation: Subarray of size K = 3 are: {1, 3, 4} and {3, 4, 1} a
6 min read
Generate an Array with XOR of even length prefix as 0 or 1
Given an integer N, the task is to construct an array of N distinct elements (arr[i] ⤠N+1) such that the bitwise XOR of every prefix having an even length is either 0 or 1. Examples: Input: N = 5Output = 2 3 4 5 6Explanation: XOR from arr[1] to arr[2] = XOR(2, 3) = 1XOR from arr[1] to arr[4] = XOR(
5 min read
Minimum removals required to convert given array to a Mountain Array
Given an array arr[] consisting of N integers???, the task is to find the minimum number of array elements required to be removed to make the given array a mountain array. A mountain array has the following properties: Length of the array ? 3.There exists some index i (0-based indexing) with 0 <
15+ min read
Generate all possible sorted arrays from alternate elements of two given sorted arrays
Given two sorted arrays A and B, generate all possible arrays such that the first element is taken from A then from B then from A, and so on in increasing order till the arrays are exhausted. The generated arrays should end with an element from B. Example: A = {10, 15, 25} B = {1, 5, 20, 30} The res
12 min read