Reorder an Array according to given indices with repetition allowed
Last Updated :
26 Sep, 2022
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 index.
Note: It is given that all the indices that in the index array lie in the range [0, N).
Examples:
Input: arr = [0, 1, 2, 3, 4], index = [0, 1, 2, 2, 1]
Output: [0, 4, 1, 3, 2]
Explanation:
First we insert at 0th, 1st and 2nd index so the array will become [0, 1, 2]
Then we insert again at 2nd position and rightshift all rightside elements so array will be [0, 1, 3, 2]
Then we insert 4 at first index so final array will become: [0, 4, 1, 3, 2].
Input: arr = [1, 2, 3, 4, 0], index = [0, 1, 2, 3, 0]
Output: [0, 1, 2, 3, 4]
Approach (Using static array):
If we use a static array, then the given problem can be solved using the following steps:
- Create a new array finalArr of size N, to store the resultant output.
- For each element in the given arr array, insert it at the corresponding given index given by the index array, simply using:
finalArr[index[i]] = arr[i]
where i is the current
position during iteration
- If the index is repeated, then right shift all right-side element and then finally insert at that position.
Approach (Using dynamic array):
If we use a dynamic array-like structure, like Vectors, etc; then we can simply insert the given element at the given index, without worrying about the repetition. The vector-like data structure takes care of the right shifting by itself, when it expands at each insertion.
- Create a new vector vec, to store the resultant output.
- For each element in the given arr array, insert it at the corresponding given index given by the index array, simply using insert() function of vector. This will insert at a particular position, and take care of repeating positions automatically.
Below is the implementation of the above approach:
C++
// C++ program to reorder an Array
// according to given indices
// with repetition allowed
#include <bits/stdc++.h>
using namespace std;
// Function that returns the
// modified vector according to indices
vector<int> createTargetArray(
vector<int>& nums, vector<int>& index)
{
// create an ans vector
vector<int> ans;
int n = nums.size();
for (int i = 0; i < n; i++)
// insert at particular position
// mention in index array.
ans.insert(ans.begin() + index[i],
nums[i]);
// finally return ans
return ans;
}
// Function to reorder and
// print the given array
void reorder(
vector<int>& arr, vector<int>& index)
{
vector<int> ans;
ans = createTargetArray(arr, index);
// print ans vector
for (int i = 0; i < ans.size(); i++) {
cout << ans[i] << " ";
}
}
// Driver Code
int main()
{
vector<int> arr = { 0, 1, 2, 3, 4 };
vector<int> index = { 0, 1, 2, 2, 1 };
reorder(arr, index);
return 0;
}
Java
// Java program to reorder an Array
// according to given indices
// with repetition allowed
import java.util.*;
class GFG {
// Function that returns the
// modified List according to indices
static List<Integer> createTargetArray(List<Integer> nums,
List<Integer> index)
{
// Create an ans List
List<Integer> ans = new ArrayList<>();
int n = nums.size();
for(int i = 0; i < n; i++)
{
// Insert at particular position
// mention in index array
ans.add(index.get(i), nums.get(i));
}
// Finally return ans
return ans;
}
// Function to reorder and
// print the given array
static void reorder(List<Integer> arr,
List<Integer> index)
{
List<Integer> ans;
ans = createTargetArray(arr, index);
// Print ans list
for(int i = 0; i < ans.size(); i++)
{
System.out.print(ans.get(i) + " ");
}
}
// Driver code
public static void main(String[] args)
{
List<Integer> arr = Arrays.asList(0, 1, 2, 3, 4);
List<Integer> index = Arrays.asList(0, 1, 2, 2, 1);
reorder(arr, index);
}
}
// This code is contributed by offbeat
Python3
# Python3 program to reorder an array
# according to given indices
# with repetition allowed
# Function that returns the modified
# vector according to indices
def createTargetArray(nums, index):
# Create an ans vector
ans = []
n = len(nums)
for i in range(n):
# Insert at particular position
# mention in index array.
ans.insert(index[i], nums[i])
# Finally return ans
return ans
# Function to reorder and
# print the given array
def reorder(arr, index):
ans = createTargetArray(arr, index)
# Print ans vector
for i in range(len(ans)):
print(ans[i], end = " ")
# Driver Code
if __name__ == "__main__":
arr = [ 0, 1, 2, 3, 4 ]
index = [ 0, 1, 2, 2, 1 ]
reorder(arr, index)
# This code is contributed by chitranayal
C#
// C# program to reorder an Array
// according to given indices
// with repetition allowed
using System;
using System.Collections.Generic;
class GFG{
// Function that returns the
// modified List according to indices
static List<int> createTargetArray(List<int> nums,
List<int> index)
{
// Create an ans List
List<int> ans = new List<int>();
int n = nums.Count;
for(int i = 0; i < n; i++)
{
// Insert at particular position
// mention in index array
ans.Insert(index[i], nums[i]);
}
// Finally return ans
return ans;
}
// Function to reorder and
// print the given array
static void reorder(List<int> arr,
List<int> index)
{
List<int> ans;
ans = createTargetArray(arr, index);
// Print ans list
for(int i = 0; i < ans.Count; i++)
{
Console.Write(ans[i] + " ");
}
}
// Driver code
public static void Main()
{
List<int> arr = new List<int>{ 0, 1, 2, 3, 4 };
List<int> index = new List<int>{ 0, 1, 2, 2, 1 };
reorder(arr, index);
}
}
// This code is contributed by akhilsaini
JavaScript
<script>
// Javascript program to reorder an Array
// according to given indices
// with repetition allowed
// Function that returns the
// modified vector according to indices
function createTargetArray( nums, index)
{
// create an ans vector
var ans = [];
var n = nums.length;
for (var i = 0; i < n; i++)
// insert at particular position
// mention in index array.
ans.splice(index[i],0,
nums[i]);
// finally return ans
return ans;
}
// Function to reorder and
// print the given array
function reorder( arr, index)
{
var ans = [];
ans = createTargetArray(arr, index);
// print ans vector
for (var i = 0; i < ans.length; i++) {
document.write( ans[i] + " ");
}
}
// Driver Code
var arr = [0, 1, 2, 3, 4 ];
var index = [0, 1, 2, 2, 1 ];
reorder(arr, index);
</script>
Time complexity: O(N2), for performing insert operations in the loop.
Auxiliary space: O(N), for storing elements in the answer array.
Similar Reads
Reorder an array according to given indexes
Given two integer arrays of the same length, arr[] and index[], the task is to reorder the elements in arr[] such that after reordering, each element from arr[i] moves to the position index[i]. The new arrangement reflects the values being placed at their target indices, as described by index[] arra
15+ min read
Generate an array of size N according to the given rules
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 pre
10 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
Count of Derangements of given Array with Repetition
Given an array arr[] of N numbers (N ⤠20), the task is to find the number of Derangements of the array where array elements can be repeated. A derangement is a permutation of N elements, such that no element appears in its original position. For example, a derangement of {0, 1, 2, 3} is {2, 3, 1, 0
13 min read
Print All Distinct Permutations of an Array
Given an array arr[], Print all distinct permutations of the given array. Examples: Input: arr[] = [1, 3, 3]Output: [[1, 3, 3], [3, 1, 3], [3, 3, 1]]Explanation: Above are all distinct permutations of given array. Input: arr[] = [2, 2] Output: [[2, 2]]Explanation: Above are all distinct permutations
6 min read
Ways to form an array with distinct adjacent
You are given three integers: n, m, and x (1 ⤠x ⤠m). Your task is to determine the number of valid arrays of length n that satisfy the following conditions: The first element of the array is fixed and equal to x.The last element of the array is fixed and equal to 1.For every index i from 2 to n -
13 min read
Rearrange the given array to minimize the indices with prefix sum at least arr[i]
Given an array arr[] consisting of N positive integers, rearrange the array to minimize the number of indices i such that the prefix sum from index 1 to index i-1 is greater than or equal to the current element arr[i] i.e. arr[1]+arr[2]+...+arr[i-1] >= arr[i]. Examples: Input: arr[] = [4, 2, 1]Ou
6 min read
Count indices with Specific Frequency in Array Range
Given an array of N elements and num queries, In each query, you are given three numbers L, R, and K and you have to tell, how many indexes are there in between L and R(L <= i <= R) such that the frequency of a[i] from index i to n-1 is K. Follow 0-based indexing Examples: Input: N = 5, num =
11 min read
Find all duplicate and missing numbers in given permutation array of 1 to N
Given an array arr[] of size N consisting of the first N natural numbers, the task is to find all the repeating and missing numbers over the range [1, N] in the given array. Examples: Input: arr[] = {1, 1, 2, 3, 3, 5}Output: Missing Numbers: [4, 6]Duplicate Numbers: [1, 3]Explanation:As 4 and 6 are
8 min read
Find the indices which will hold the Array sum after given operations
Given an array arr[], the task is to print the indices that have the highest probability of holding the entire sum of the array after performing the given operations: Choose any two elements say arr[i] and arr[j], store their sum in a variable KAssign K at index of max(arr[i], arr[j]) and assign 0 a
10 min read