Problem
Given two integer arrays of the same size, arr [] and index[] , reorder elements in arr [] according to the given index array.
Sample Input
[10, 11, 12] [1, 0, 2]
Sample Output
11, 10, 12 0, 1, 2
Approach
We can traverse through 0 to n-1 (where n is the size of the arrays) and keep placing the current elements at the correct indices. This will ultimately give us the required array. For this, we can swap index[i] with index[index[i]] and arr[index[i]] with arr[i] .
C++ Programming
#include<bits/stdc++.h> using namespace std; void solve(int a[], int n, int index[]){ for(int i=0;i<n;i++){ int temp = index[i]; swap(index[index[i]], index[i]); swap(a[temp], a[i]); } } int main(){ int a[] = {50, 40, 70, 60, 90}; int index[] = {3, 0, 4, 1, 2}; int n =sizeof(a)/sizeof(a[0]); solve(a, n, index); for(int i=0;i<n;i++) cout<<a[i]<<" "; cout<<"\n"; for(int i=0;i<n;i++) cout<<index[i]<<" "; }
Output
40 60 90 50 70 0 1 2 3 4
C Programming
#include<stdio.h> void swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; } void solve(int a[], int n, int index[]){ for(int i=0;i<n;i++){ int temp = index[i]; swap(&index[index[i]], &index[i]); swap(&a[temp], &a[i]); } } int main(){ int a[] = {50, 40, 70, 60, 90}; int index[] = {3, 0, 4, 1, 2}; int n =sizeof(a)/sizeof(a[0]); solve(a, n, index); for(int i=0;i<n;i++) printf("%d ", a[i]); printf("\n"); for(int i=0;i<n;i++) printf("%d ", index[i]); }
Output
40 60 90 50 70 0 1 2 3 4
Python Programming
def solve(a, index, n): for i in range(0, n): temp = index[i] t = index[index[i]] index[index[i]] = index[i] index[i] = t t = a[temp] a[temp] = a[i] a[i] = t a = [50, 40, 70, 60, 90] index = [3, 0, 4, 1, 2] n = len(a) solve(a, index, n) print(a) print(index)
Output
[40, 60, 90, 50, 70] [0, 1, 2, 3, 4]
People are also reading:
- Count the number of strictly increasing subarrays in an array
- Find duplicates within a range k in an array
- Find the longest subsequence formed by consecutive integers
- Determine the index of an element that satisfies given constraints in an array
- Find minimum sum of a subarray of size k
- Python isalpha, insumeric and isalnum(): A complete Guide
- Sort an almost sorted array where only two elements are swapped
- Reverse every consecutive m-elements of a subarray
- Find equilibrium index of the array
- Maximum Product Subset Problem
Leave a Comment on this Post