Generate an array using given conditions from a given array
Last Updated :
15 Sep, 2022
Given an array arr[] of size N, the task is to construct a new array B[] using elements of array A such that:
- If the element is not present in B[], then append it to the end.
- If the element is present in B[], then first increment its leftmost occurrence by 1 and then append this element to the end of the array.
Examples:
Input: arr[] = {1, 2, 1, 2}
Output: { 3, 2, 1, 2 }
Explanation:
arr[0] = 1, B = {}. 1 is not present in B. So append it at the end. Therefore, B = {1}
arr[1] = 2, B = {1}. 2 is not present in B. So append it at the end. Therefore, B[] = {1, 2}
arr[2] = 1, B = {1, 2}. 1 is already present in B[]. So increment B[0] by 1 and append 1 at the end. Therefore B[] = {2, 2, 1}
arr[3] = 2, B = {2, 2, 1}. 2 is already present in B[]. So increment B[0] by 1 and append 2 at the end. Therefore B[] = {3, 2, 1, 2}
Input: arr[] = {2, 5, 4, 2, 8, 4, 2}
Output: {3, 5, 5, 3, 8, 4, 2}
Naive Approach: For every element in the array A, check if it is present in array B or not. If the element exists, then increment the leftmost occurrence by one. Finally, add the element at the end of the array B[].
Time Complexity: O(N2)
Efficient Approach: The idea is to use a map to store all the indices of every element. The array B[] is generated as:
- For every element in the array arr[], it is checked if the element is already present in the array B[] or not.
- If the element is not present in the array B[], then the element is added to the array B[] and its index is added to the map. Since this is the first occurrence of the element, this index becomes the left-most index of the element.
- If the element is already present in the array B[], then the left-most index is returned and the element at that index is incremented by one. When the value is incremented, the left-most index of the old value is updated along with the index of the new value.
Below is the implementation of the above approach:
CPP
#include <bits/stdc++.h>
using namespace std;
void newArray( int A[], int n)
{
unordered_map< int , set< int > > idx;
std::vector< int > B;
for ( int i = 0; i < n; ++i) {
if (idx.find(A[i]) != idx.end()) {
int pos = *idx[A[i]].begin();
idx[A[i]].erase(idx[A[i]].begin());
B[pos]++;
idx[B[pos]].insert(pos);
}
B.push_back(A[i]);
idx[A[i]].insert(i);
}
for ( int i = 0; i < n; ++i)
cout << B[i] << " " ;
}
int main()
{
int arr[] = { 1, 2, 1, 2 };
int n = sizeof (arr) / sizeof ( int );
newArray(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static void newArray( int [] A, int n)
{
HashMap<Integer, HashSet<Integer> > idx
= new HashMap<Integer, HashSet<Integer> >();
ArrayList<Integer> B = new ArrayList<Integer>();
for ( int i = 0 ; i < n; ++i) {
if (idx.containsKey(A[i])) {
HashSet<Integer> h1 = idx.get(A[i]);
int pos = Collections.min(h1);
h1.remove(pos);
idx.put(A[i], h1);
B.set(pos, B.get(pos) + 1 );
HashSet<Integer> h2;
if (!idx.containsKey(B.get(pos)))
idx.put(B.get(pos),
new HashSet<Integer>());
h2 = idx.get(B.get(pos));
h2.add(pos);
idx.put(B.get(pos), h2);
h1.add(B.size());
idx.put(A[i], h1);
}
else {
HashSet<Integer> h1
= new HashSet<Integer>();
h1.add(B.size());
idx.put(A[i], h1);
}
B.add(A[i]);
}
for ( int i = 0 ; i < B.size(); i++)
System.out.print(B.get(i) + " " );
}
public static void main(String[] args)
{
int [] arr = { 1 , 2 , 1 , 2 };
int n = arr.length;
newArray(arr, n);
}
}
|
Python3
def newArray(A, n):
idx = dict ();
B = [];
for i in range (n):
if A[i] in idx:
pos = min (idx[A[i]])
idx[A[i]].discard(pos)
B[pos] = B[pos] + 1
if B[pos] not in idx:
idx[B[pos]] = set ()
idx[B[pos]].add(pos)
idx[A[i]].add( len (B))
else :
idx[A[i]] = set ()
idx[A[i]].add( len (B))
B.append(A[i]);
print ( * B)
arr = [ 1 , 2 , 1 , 2 ];
n = len (arr)
newArray(arr, n);
|
C#
using System;
using System.Linq;
using System.Collections.Generic;
class GFG {
static void newArray( int [] A, int n)
{
Dictionary< int , HashSet< int > > idx
= new Dictionary< int , HashSet< int > >();
List< int > B = new List< int >();
for ( int i = 0; i < n; ++i) {
if (idx.ContainsKey(A[i])) {
int pos = (idx[A[i]]).Min(c => c);
idx[A[i]].Remove(pos);
B[pos]++;
if (!idx.ContainsKey(B[pos]))
idx[B[pos]] = new HashSet< int >();
idx[B[pos]].Add(pos);
idx[A[i]].Add(B.Count);
}
else {
idx[A[i]] = new HashSet< int >();
idx[A[i]].Add(B.Count);
}
B.Add(A[i]);
}
for ( int i = 0; i < B.Count; i++)
Console.Write(B[i] + " " );
}
public static void Main( string [] args)
{
int [] arr = { 1, 2, 1, 2 };
int n = arr.Length;
newArray(arr, n);
}
}
|
Javascript
function newArray(A, n)
{
let idx = {};
let B = [];
for ( var i = 0; i < n; ++i) {
if (idx.hasOwnProperty(A[i])) {
let pos = Math.min.apply( this , [...idx[A[i]]]);
idx[A[i]]. delete (pos)
B.splice(pos, 1, B[pos] + 1);
if (!idx.hasOwnProperty(B[pos]))
idx[B[pos]] = new Set()
idx[B[pos]].add(pos)
idx[A[i]].add(B.length)
}
else
{
idx[A[i]] = new Set();
idx[A[i]].add(B.length)
}
B.push(A[i]);
}
console.log(B.join( " " ))
}
let arr = [ 1, 2, 1, 2 ];
let n = arr.length
newArray(arr, n);
|
Time Complexity: O(n)
Auxiliary Space: O(n)
Share your thoughts in the comments
Please Login to comment...