Facebook Interview Question for Front-end Software Engineers


Country: United States
Interview Type: Phone Interview




Comment hidden because of low score. Click to expand.
4
of 12 vote

O(n) solution

public void reorder(char [] A, int [] B){
		   for (int i = 0 ; i < B.length ; ++i) {
			   int tmp = i ;
			   while (B[tmp] != tmp) {
				   swap(A, B[tmp], tmp);
				   swapIndex (B, B[tmp], tmp) ;				   
				   tmp = B[tmp] ;				
			   }			   
		   }
		}
		
		
		private void swap (char [] A, int i , int j){		
			char tmp = A[i] ;
			A[i] = A[j] ;
			A[j] = tmp ;
		}
		
		private void swapIndex (int [] A, int i , int j){
			int tmp = A[i] ;
			A[i] = A[j] ;
			A[j] = tmp ;

}

- Scott October 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

try for this index {4,3,1,0,2}

- Anonymous October 26, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

asdasda

- asdasdas October 26, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@asdasdas I have tried and it is working

- Scott October 27, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

yes yours works sorry for spaming some solutions that don't have that 'while (B[tmp] != tmp)' check wont work.

cheers

- sshukla6@buffalo.edu October 27, 2015 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

swap is the same as swapIndex ??? hahahaha

- gen-x-s October 28, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@gen-x-s 3 look carefully at char [] A,int [] A so they are different

- abhay0609 October 31, 2015 | Flag
Comment hidden because of low score. Click to expand.
2
of 2 votes

Why do you need the while loop? Why not just:

public static void reorder(char [] A, int [] B){
for (int i = 0 ; i < B.length ; ++i) {
if (B[i] != i) {
swap(A, B[i], i);
swapIndex (B, B[i], i) ;
}
}
}

- balboa@ November 03, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

I admit the naming convention could have been difference for swapping chars and ints. Maybe swapCharacter or swapLetter instead of just swap.

- Steve November 13, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Is the time complexity O(n) or O(n^2) ??

- arun November 15, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

balboa is correct. The while loop is redundant. The time complexity is O(n).

- Josh November 15, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Why is the while loop redundant? If you swap C with F in the first iteration of the loop in the example, F/1 is then stored at index 0. You need the outer loop pointer to stay in place until the correct element is in place (i.e. b[i] == i). Still O(n).

- Damien Diehl November 16, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

void swap(void* i, void* j, int size)
{
    void*  temp = malloc(size);
    memcpy(temp,i,size);
    memcpy(i,j,size);
    memcpy(j,temp,size);
    free(temp);
}

You can use this for generic swap, where size is sizeof(int) or sizeof(char) for this program

- Anonymous January 03, 2016 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Isn't the data in array B getting mutated? Is there a way to solve this in O(n) time complexity and O(1) space without mutating the data of B array?

- sudhansu.choudhary October 10, 2018 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

(function (temp) {
A = [];
for(let i = 0; i < B.length; i++) {
A[b[i]] = temp[i];
}
})(A)

- Anonymous March 20, 2019 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

function sort(a, b) {
  var c = new Array(b.length);
  b.forEach((val, i) => { c[val] = a[i]; });
  a.forEach((val, i) => { a[i] = c[i]; });
}

- Ule October 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 2 vote

Implemented in Java. Runtime O(n), where n equals number of elements in array. Space O(1).

/**
 * @throws NullPointerException if elements or indices are null
 */
public static void sort( String[] elements, int[] indices ) {
        if ( elements.length != indices.length ) {
                return;
        }

        for ( int i = 0; i < elements.length; i++ ) {
                while ( indices[ i ] != i ) {
                        swap( elements, indices, i, indices[ i ] );
                }
        }
}

private static void swap( String[] elements, int[] indices, int fromIndex, int toIndex ) {
        String element = elements[ fromIndex ];
        int index = indices[ fromIndex ];

        elements[ fromIndex ] = elements[ toIndex ];
        indices[ fromIndex ] = indices[ toIndex ];

        elements[ toIndex ] = element;
        indices[ toIndex ] = index;
}

- vposkatcheev October 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

try for this indexes {4,3,1,0,2}

- swapnil October 26, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

try for this indexes {4,3,1,0,2}

- sshukla6@buffalo.edu October 26, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Thanks for pointing this out. Adjusted original solution.

- vposkatcheev November 10, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

void sort(char* a, int* b, int size){
	for(int i=0;i<size;i++){
		int pos = b[i];
		char temp = a[pos]; //f 
		a[pos] = a[i];	// c
		a[i] = temp;
	}
	for(int i=0;i<size;i++)
		cout<<a[i]<<" ";
}

- suraj palwe October 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

O(n)

public static void sortByIndex(char[] array, int[] indexes) {
		if (array.length != indexes.length) return;

		for (int i = 0; i < array.length; i++) {
			// swap value
			char temp = array[indexes[i]]; 
			array[indexes[i]] = array[i];
			array[i] = temp;
			// swap index
			int tInd = indexes[indexes[i]];
			indexes[indexes[i]] = indexes[i];
			indexes[i] = tInd;
		}
	}

- ikoryf October 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I guess this problem is solved O(n) :-)

#include <iostream>
#include <utility>

void sort(char* a, int* b, int l) {

    int startIndex = 0;
    int matchCount = 0;

    while(matchCount < l) {

        if(b[startIndex] == startIndex) {
            matchCount++;
            startIndex++;
            continue;
        }

        std::swap(a[b[startIndex]], a[startIndex]);
        std::swap(b[b[startIndex]], b[startIndex]);

        matchCount++;
    }
}

int main() {
    char a[] = {'C', 'D', 'E','F', 'G'};
    int b[] = {3, 0, 4, 1, 2};
    int length = sizeof(a)/sizeof(char);

    sort(a, b, length);

    for(int i=0; i<length; i++) {
        std::cout << a[i] << "\t";
    }

    std::cout << std::endl;

    return 0;
}

- hanyoungpark October 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Solution at O(n) complexity w/o even an additional tmp variable.
- Start at the first position of the index array
- While the element at the current position is not in its proper slot
-- swap the elements in both the index and data arrays, thus putting the current element into its proper slot
-- if the element is in its proper slot, then increment the counter and continue

void sort_data(char A[], int B[], const int& size)
{
	int i = 0;
	while(i < size)
	{
		if (B[i] == i)
		{
			++i;
			continue;
		}
		// swap the elements in both arrays
		swap(A, B[i], i);
		swap(B, B[i], i);
	}
}

- Ashot Madatyan October 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Solution at O(n) complexity w/o even an additional tmp variable.
- Start at the first position of the index array
- While the element at the current position is not in its proper slot
-- swap the elements in both the index and data arrays, thus putting the current element into its proper slot
-- if the element is in its proper slot, then increment the counter and continue

void sort_data(char A[], int B[], const int& size)
{
	int i = 0;
	while(i < size)
	{
		if (B[i] == i)
		{
			++i;
			continue;
		}
		// swap the elements in both arrays
		swap(A, B[i], i);
		swap(B, B[i], i);
	}
}

- Anonymous October 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Solution at O(n) complexity w/o even an additional tmp variable.
- Start at the first position of the index array
- While the element at the current position is not in its proper slot
-- swap the elements in both the index and data arrays, thus putting the current element into its proper slot
-- if the element is in its proper slot, then increment the counter and continue

void sort_data(char A[], int B[], const int& size)
{
	int i = 0;
	while(i < size)
	{
		if (B[i] == i)
		{
			++i;
			continue;
		}
		// swap the elements in both arrays
		swap(A, B[i], i);
		swap(B, B[i], i);
	}
}

- ashot madatyan October 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
#include <vector>
#include <map>

using namespace std;

void sortArray(vector<char> & A, vector<int> & B) {
    
    map<int, char> BMap;
    
    for(int i = 0; i < B.size(); ++i) {
        BMap[B[i]] = A[i];
    }
    
    int j = 0;
    for(auto w: BMap) {
        A[j] = w.second;
        ++j;
    }
}

- Lillian October 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
#include <vector>
#include <map>

using namespace std;

void sortArray(vector<char> & A, vector<int> & B) {
    
    map<int, char> BMap;
    
    for(int i = 0; i < B.size(); ++i) {
        BMap[B[i]] = A[i];
    }
    
    int j = 0;
    for(auto w: BMap) {
        A[j] = w.second;
        ++j;
    }
}

- Lillian October 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
#include <vector>
#include <map>

using namespace std;

void sortArray(vector<char> & A, vector<int> & B) {
    
    map<int, char> BMap;
    
    for(int i = 0; i < B.size(); ++i) {
        BMap[B[i]] = A[i];
    }
    
    int j = 0;
    for(auto w: BMap) {
        A[j] = w.second;
        ++j;
    }
}

- Newbie October 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
#include <vector>
#include <map>

using namespace std;

void sortArray(vector<char> & A, vector<int> & B) {

map<int, char> BMap;

for(int i = 0; i < B.size(); ++i) {
BMap[B[i]] = A[i];
}

int j = 0;
for(auto w: BMap) {
A[j] = w.second;
++j;
}
}

- Newbie October 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
#include <vector>
#include <map>

using namespace std;
void sortArray(vector<char> & A, vector<int> & B) { 
    map<int, char> BMap;
    for(int i = 0; i < B.size(); ++i) {
        BMap[B[i]] = A[i];
    }
    
    int j = 0;
    for(auto w: BMap) {
        A[j] = w.second;
        ++j;
    }
}

- Newbie October 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

- Lillian October 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

C++ implementation

#include <iostream>
#include <vector>
#include <map>

using namespace std;

void sortArray(vector<char> & A, vector<int> & B) {
    
    map<int, char> BMap;
    
    for(int i = 0; i < B.size(); ++i) {
        BMap[B[i]] = A[i];
    }
    
    int j = 0;
    for(auto w: BMap) {
        A[j] = w.second;
        ++j;
    }
}

- Lillian October 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
#include <vector>
#include <map>

using namespace std;

void sortArray(vector<char> & A, vector<int> & B) {

map<int, char> BMap;

for(int i = 0; i < B.size(); ++i) {
BMap[B[i]] = A[i];
}

int j = 0;
for(auto w: BMap) {
A[j] = w.second;
++j;
}
}




int main(int argc, const char * argv[]) {
int arrB[] = {3, 0, 4, 1, 2};
char arrA[] = {'C','D', 'E', 'F', 'G'};

vector<int> B(arrB, arrB+5);
vector<char> A(arrA, arrA + 5);

sortArray(A, B);
for(auto iter = A.begin(); iter!=A.end(); ++iter) {
cout << *iter << endl;
}


return 0;
}

- Anonymous October 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>
#include <vector>
#include <map>

using namespace std;

void sortArray(vector<char> & A, vector<int> & B) {
    
    map<int, char> BMap;
    
    for(int i = 0; i < B.size(); ++i) {
        BMap[B[i]] = A[i];
    }
    
    int j = 0;
    for(auto w: BMap) {
        A[j] = w.second;
        ++j;
    }
}




int main(int argc, const char * argv[]) {
    int arrB[] = {3, 0, 4, 1, 2};
    char arrA[] = {'C','D', 'E', 'F', 'G'};
    
    vector<int> B(arrB, arrB+5);
    vector<char> A(arrA, arrA + 5);
    
    sortArray(A, B);
    for(auto iter = A.begin(); iter!=A.end(); ++iter) {
        cout << *iter << endl;
    }
    
    
    return 0;
}

- Testing October 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

This problem is sort
A = [3, 0, 4, 1, 2]
B = [3, 0, 4, 1, 2]
to
A = [0, 1, 2, 3, 4].

Not sort
A = [0, 1, 2, 3, 4]
B = [3, 0, 4, 1, 2]
to
A = [3, 0, 4, 1, 2].

See result carefully.

- Anonymous October 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

python implementation O(n)

def reOrderFromIndexes(orig, indexes):
    for i in range(len(orig)):
        index = indexes[i]
        orig[i], orig[index] = orig[index], orig[i]
        indexes[i], indexes[index] = indexes[index], indexes[i]
    return orig

- Anonymous October 27, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void Sort(std::vector<char>& a, std::vector<int>& b)
{
    int i = 0;
    while (i < b.size())
    {
        if (b[i] == i)
        {
            ++i;
            continue;
        }

        std::swap(a[b[i]], a[i]);
        std::swap(b[i], b[b[i]]);
    }
}

- artur.ghandilyan October 27, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

class Solution {
  
  public static <T> void swap(T[] arr, int i, int j){
    T temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
  }
  
  
  public static void reindex(char[] chars, int[] indexes){
    
  }

  public static void main(String[] args) {
    Character[] chars = 
      new Character[]{'C', 'D', 'E', 'F', 'G'};
    Integer[] indexes = new Integer[]{  3,   0,   4,   1,   2 };
    Character[] target = new Character[]{'D', 'F', 'G', 'C', 'E'};
    
    for(int i = 0; i < chars.length; i++){
      while(i != indexes[i]){
        swap(chars, i, indexes[i]);
        swap(indexes, i, indexes[i]);
      }
    }
    
    System.out.println( Arrays.toString(chars) );
  }
}

- Meow October 29, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Letter/number at each location should be moved to its destination. In the end everything will be in place

def move_to_destination(chars, numbers):
    for idx in range(len(numbers)):
        if numbers[idx] != idx:
            swap(idx, numbers[idx], chars, numbers)


def swap(from_idx, to_idx, chars, numbers):
    chars[from_idx], chars[to_idx] = chars[to_idx], chars[from_idx]
    numbers[from_idx], numbers[to_idx] = numbers[to_idx], numbers[from_idx]

- rizTaak November 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void sortArraybyIdx()
{
	char[] A = {'C', 'D', 'E', 'F', 'G'};
	int[] B = {3, 0, 4, 1, 2};//DFGCE
	int currIdx = 0;
	int shldbeIdx = 0;
	int k = 0;
	while(k < B.length)
	{
		shldbeIdx = B[shldbeIdx];//3
		currIdx = k;//0
		//
		char temp = A[shldbeIdx];
		A[shldbeIdx] = A[currIdx];
		A[currIdx] = temp;
		//
		int tempInt = B[shldbeIdx];
		B[shldbeIdx] = B[currIdx];
		B[currIdx] = tempInt;
		
		if(B[currIdx] == k)
		k++;
	}
	
	for(char l : A)
	{
		System.out.print(l);
	}
}

- CodeKnight November 08, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

var A = ['C', 'D', 'E', 'F', 'G'],
      B = [3, 0, 4, 1, 2];
A.forEach(function(value, index) {
    C[B[index]] = value;
});

console.log(C);

- Utkarsh Shrivastava November 09, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Implemented in Java. Runtime O(n), where n equals number of elements in array. Space O(1).

public class OrderArrayProblem {

	public static void main( String[] args ) {
		String[] elements = { "C", "D", "E", "F", "G" };
		int[] indices = { 3, 0, 4, 1, 2 };

		System.out.println( Arrays.asList( elements ) );
		sort( elements, indices );
		System.out.println( Arrays.asList( elements ) );
	}

	/**
	 * @throws NullPointerException if elements or indices are null
	 */
	public static void sort( String[] elements, int[] indices ) {
		if ( elements.length != indices.length ) {
			return;
		}

		for ( int i = 0; i < elements.length; i++ ) {
			while ( indices[ i ] != i ) {
				swap( elements, indices, i, indices[ i ] );
			}
		}
	}

	private static void swap( String[] elements, int[] indices, int fromIndex, int toIndex ) {
		String element = elements[ fromIndex ];
		int index = indices[ fromIndex ];

		elements[ fromIndex ] = elements[ toIndex ];
		indices[ fromIndex ] = indices[ toIndex ];

		elements[ toIndex ] = element;
		indices[ toIndex ] = index;
	}

}

- vposkatcheev November 10, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

groovy
without creating a new array

class ArraySorting {

    static void main(String... args) {
        String[] elements = ["C", "D", "E", "F", "G"]
        int[] indexes = [3, 0, 4, 1, 2]
        if (elements.length == indexes.length) {
            println(sort(elements, indexes))
        }
    }

    static String[] sort(String[] elements, int[] indexes) {
        for (int i = 0; i < indexes.length; i++) {
            String tmp = elements[i]
            elements[i] = elements[indexes[i]]
            elements[indexes[i]] = tmp
            int iTemp = indexes[i]
            int iTempIndex = indexes.findIndexOf { it == i }
            indexes[i] = i
            indexes[iTempIndex] = iTemp
        }
        elements
    }
}

- simona.valenti.0 December 06, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

runtime O(n).

A=['C', 'D', 'E', 'F', 'G']
B=[3, 0, 4, 1, 2]

dict = {}

for i in range(len(A)):
    dict[i] = 0

count = 0
tmpA = A[0]
tmpB = B[0]

for i in range(len(A)):
    tmpA2 = A[tmpB]
    tmpB2 = B[tmpB]

    dict[tmpB] = 1

    A[tmpB] = tmpA
    B[tmpB] = tmpB
    tmpA = tmpA2
    tmpB = tmpB2

    if dict[tmpB] == 1:
        for j in dict:
            if dict[j] == 0:
                tmpA = A[j]
                tmpB = B[j]
print A
print B

- HiuH December 07, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static void resortArray(char []A ,int[] B){
        char tmp;
        for(int i : B){
            tmp = A[i];
            for(int j = 0 ; j<A.length ; j ++){
                A[i] = tmp;
            }
        }
        System.out.println(A);
    }

- Erez bk December 08, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

function sort(a,b){
  for(var i  = 0; i < b.length;){
    if( b[i] === i ) i++;
    else{
      var tmp = a[i];
      a[i] = a[b[i]];
      a[b[i]] = tmp ;
    
      var nTmp = b[i];
      b[i] = b[b[i]];
      b[nTmp] = nTmp;
      
    }
  }
  
  return a;
  
}

- Anonymous December 09, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

class P:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __lt__(self, other):
        return self.y < other.y

def sort(a, b):
    p = []
    for i in xrange(len(a)):
        p.append(P(a[i], b[i]))
    p.sort()
    return [ i.x for i in p ]

- Python solution December 20, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void swap(void* i, void* j, int size)
{
    void*  temp = malloc(size);
    memcpy(temp,i,size);
    memcpy(i,j,size);
    memcpy(j,temp,size);
    free(temp);
}

Use this for generic swap.

- Ankit January 03, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

[x[0] for x in sorted(zip(A,B))]

- AEGaddy February 02, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

C++ Solution:
O(n) complexity, O(1) space

void sort(std::vector<char0> &v1, std::vector<int> &v2) {

for ( int i = 0; i < v2.size(); i++){
char tmp = v1[v2[i]];
v1[v2[i]]= v1[i];
v1[i] = tmp;

int t = v2[v2[i]];
v2[v2[i]] = v2[i];
v2[i] = t;
}
// your code goes here
return;
}

- Anonymous February 07, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

C++: O(n) time complexity, O(1) space complexity

void sort(std::vector<char0> &v1, std::vector<int> &v2) {
	
	for ( int i = 0; i < v2.size(); i++){
		char tmp = v1[v2[i]];
		v1[v2[i]]= v1[i];
		v1[i] = tmp;
		
		int t =  v2[v2[i]];
		v2[v2[i]] = v2[i];
		v2[i] = t;
	}
	// your code goes here
	return;
}

- **super** February 07, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Javascript solution:

function reorderArray() {
    return indices.map(function (val, i) {
        return array[indices.indexOf(i)];
    });
}

- Raul Rivero March 11, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

var a = [ "C", "D","E","F","G" ];
var b = [ 3, 0, 4, 1, 2 ];

function sort( a, b ) {
  var bl = b.length ;
  var al = a.length ;
  var obj = {};

  for( var i = 0 ; i<bl ; i ++ ) {
    
    obj[b[i]] = a[i];
  }
  console.log( obj )
}

   
sort( a, b)

- Riturathin Sharma April 12, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

var a = [ "C", "D","E","F","G" ];
var b = [ 3, 0, 4, 1, 2 ];

function sort( a, b ) {
  var bl = b.length ;
  var al = a.length ;
  var obj = {};

  for( var i = 0 ; i<bl ; i ++ ) {
    
    obj[b[i]] = a[i];
  }
  console.log( obj )
}

   
sort( a, b)

- Riturathinsharma April 12, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

var A = ['C', 'D', 'E', 'F', 'G'];
var B = [3, 0, 4, 1, 2];

sort(A, B);
// A is now [D, F, G, C, E];

function sort(){
var i = 0;
for(i=0;i<A.length;i++){

var pos = B[i];
var temp = A[pos];

if(i !== pos){
//Swap A
A[pos] = A[i];
A[i] = temp;
//Swap B
var temp1 = B[i];
B[i] = B[pos];
B[pos] = temp1;
}

}
console.log(A);
}

- Rakesh April 20, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Python:

def reorder(a,b):
	result = dict(zip(b,a))
	result = [ x for x in result.values()]
	return result

a = ['c','d', 'e', 'f', 'g']
b = [3,0,4,1,2]

print reorder(a,b)

- vinamelody May 12, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

var b = [3,0,4,1,2];
var a = ['C','D','E','F','G'];
function bSort(b,a){
do {
var trigger = true;
for(var i=0,l=b.length;i<l;i++) {
if ((b[i] > b[i+1])) {
var temp = b[i];
var tempA = a[i];
b[i] = b[i+1];
a[i] = a[i+1];
b[i+1] = temp;
a[i+1] = tempA;
trigger = false;
}
}
} while (!trigger)
return a;
}
bSort(b,a);

- glkesgg May 24, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

var b = [3,0,4,1,2];
var a = ['C','D','E','F','G'];
function bSort(b,a){
  do {
    var trigger = true;
    for(var i=0,l=b.length;i<l;i++) {
      if ((b[i] > b[i+1])) {
        var temp = b[i];
        var tempA = a[i];
        b[i] = b[i+1];
        a[i] = a[i+1];
        b[i+1] = temp;
        a[i+1] = tempA;
        trigger = false; 
      }
    }
  } while (!trigger)
  return a;
}
bSort(b,a);

- glkesgg May 24, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

var b = [3,0,4,1,2];
var a = ['C','D','E','F','G'];
function bSort(b,a){
  do {
    var trigger = true;
    for(var i=0,l=b.length;i<l;i++) {
      if ((b[i] > b[i+1])) {
        var temp = b[i];
        var tempA = a[i];
        b[i] = b[i+1];
        a[i] = a[i+1];
        b[i+1] = temp;
        a[i+1] = tempA;
        trigger = false; 
      }
    }
  } while (!trigger)
  return a;
}
bSort(b,a);

- glkesgg May 24, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

function Sort(a, b) {
var result = {};
var final = [];
for (var i = 0; i < a.length; i++) {

result[b[i]] = a[i];
}
console.log(result);

for(var key in result){
final.push(result[key]);
}

return final;

}
Sort(["C", "D", "E"], [2, 0, 1]);

- Anonymous May 27, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

function Sort(a, b) {
  var result = {};
  var final = [];
  for (var i = 0; i < a.length; i++) {

    result[b[i]] = a[i];
  }
    console.log(result);

  for(var key in result){
  final.push(result[key]);
  }
  
  return final;

}
Sort(["C", "D", "E"], [2, 0, 1]);

- Anonymous May 27, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

function Sort(a, b) {
  var result = {};
  var final = [];
  for (var i = 0; i < a.length; i++) {

    result[b[i]] = a[i];
  }
    console.log(result);

  for(var key in result){
  final.push(result[key]);
  }
  
  return final;

}
Sort(["C", "D", "E"], [2, 0, 1]);

- Anonymous May 27, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

function Sort(a, b) {
var result = {};
var final = [];
for (var i = 0; i < a.length; i++) {

result[b[i]] = a[i];
}
console.log(result);

for(var key in result){
final.push(result[key]);
}

return final;

}
Sort(["C", "D", "E"], [2, 0, 1]);

- sonia ramnani May 27, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

function Sort(a, b) {
  var result = {};
  var final = [];
  for (var i = 0; i < a.length; i++) {

    result[b[i]] = a[i];
  }
    console.log(result);

  for(var key in result){
  final.push(result[key]);
  }
  
  return final;

}
Sort(["C", "D", "E"], [2, 0, 1]);

- sonia ramnani May 27, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Javascript solution.
If it's possible to make another array, it's easier. But here I just mutated array A.

var C={C:"C"}, D={D:"D"}, E={E:"E"}, F={F:"F"}, G={G:"G"};
var A = [C,D,E,F,G];
var B = [3,0,4,1,2];
sort(a,b);
// [D, F, G, C, E] 1, 3, 4, 0, 2

function sort1(x, y) {  
  for(var i=0; i< a.length-1; i++) {
    for(var j =i+1; j < b.length; j++) {
        if(y[i]>y[j]) {
          var tempA = x[i];
          x[i] = x[j];
          x[j] = tempA;
          var tempB = y[i];
          y[i] = y[j];
          y[j] = tempB;
        }
    }
  }
}
console.log(a);
console.log(b);

- monad June 14, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

var a = ['C', 'D', 'E', 'F', 'G'];
var b = [ 3, 0, 4, 1, 2 ];

for (let i = 0; i< b.length; i++) {
var temp = a[i];
a[i] = a[b[i]];
a[b[i]] = temp;

var tempIndex = b[i];
b[i] = b[b[i]];
b[tempIndex] = tempIndex;
}

console.log(a);

- Rohan July 29, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void Sort(char[] A, int[] B)
        {
             // handle invalid cases 
            // A.len != B.len
            // B[i] >= A.Length 
            // Depulicate entries in B
            for (int i = 0; i < B.Length; i++)
            {
                if (i != B[i])
                {
                    // A
                    var temp = A[i];
                    A[i] = A[B[i]];
                    A[B[i]] = temp;

                    // B
                    var temp2 = B[i];
                    B[i] = B[B[i]];
                    B[temp2] = temp2;
                }

            }

}

- Berhe August 20, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void sort(char a[], int b[])
	{
		for (int i = 0; i < a.length; i++)
		{
			while (i != b[i])
			{
				char c = a[b[i]];
				a[b[i]] = a[i];
				a[i] = c;
				swap(b, i, b[i]);
			}
		}
	}

	public static void swap(int arr[], int i, int j)
	{
		int temp = arr[i];
		arr[i] = arr[j];
		arr[j] = temp;
	}

- koustav.adorable August 21, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Simple solution
The key is that all numbers are in range 0 to n-1

for i from 1 to n:
x = A[A[i]]%n
A[i]+=n*x

for i from 1 to n:
A[i]-= (A[i]%n)
A[i] = (A[i] / n)

- kevseb1993 November 26, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

JavaScript solution O(n).

function reorderArray(array, newOrder) {
    var i;
    var itemToMove;
    var itemToMoveIndex;
    
    for (i = 0; i < newOrder.length; i++) {
        while(newOrder[i] !== i) {
            itemToMove = array[i];
            itemToMoveIndex = newOrder[i];
            array[i] = array[itemToMoveIndex];
            newOrder[i] = newOrder[itemToMoveIndex];
            array[itemToMoveIndex] = itemToMove;
            newOrder[itemToMoveIndex] = itemToMoveIndex;
        }    
    }
   
    return array;
}

- nabilgod January 15, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

You are all insane.

function weirdSort(a,b) {                                                                                                                                                                                
  a.concat().forEach((t,i) => a[b[i]] = t);                                                                                                                                                              
}

- Anonymous January 19, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

You are all insane.

function sort(A, B) {
    A.concat().forEach((t,i) => A[B[i]] = t);
}

- Winner January 19, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

var A = ['C','D','E','F','G'];
var B = [3,0,4,1,2];

var sort = function (A,B){
		var arrLength = A.length;
    var key = {};
    for (var i= 0; i<arrLength; i++){
    	key[B[i]] = A[i];
    }
    
    
    for (var idx = 0; idx<arrLength; idx++){
        A[idx] = key[idx];
    }
    console.log(JSON.stringify(A));
    
}

sort(A,B);

- Ethan Wyatt July 04, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

var A = ['C','D','E','F','G'];
var B = [3,0,4,1,2];

var sort = function (A,B){
		var arrLength = A.length;
    var key = {};
    for (var i= 0; i<arrLength; i++){
    	key[B[i]] = A[i];
    }
    
    
    for (var idx = 0; idx<arrLength; idx++){
        A[idx] = key[idx];
    }
    console.log(JSON.stringify(A));
    
}

sort(A,B);

- Ethan Wyatt July 04, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

var a = ['C', 'D', 'E', 'F', 'G'];
var b = [3, 0, 4, 1, 2];
var sorted = [];
  
for(var i = 0; i < a.length; i++) {
  sorted[b[i]] = a[i];
}

console.log(sorted.join(','));

- mmcdonald39 July 15, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def sort(self,A,B):
  temp=0
  d={}
  for i in xrange(len(A)):
     d[i] = A[B.index(i)]
  for i in xrange(len(A)):
     if A[i] == d[i]:
        continue
     temp = A[B.index(i)]
     A[B.index(i)]=A[i]
     A[i]=temp
  return A

- deepjoarder July 21, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

var A = ['C', 'D', 'E', 'F', 'G'];
var B = [3, 0, 4, 1, 2];
var swapShifter = 0;
for (var i = 0; i < B.length; i++) {
    while(B[i] !== i){
        var key = B[swapShifter];
        if(key === i){
            var temp = B[i];
            var tempChar= A[i];
            B[i] = B[swapShifter];
            A[i] = A[swapShifter];
            B[swapShifter] = temp;
            A[swapShifter] = tempChar;
            swapShifter=i;
        }
        else{
            swapShifter++;
        }

    }


}

- Okeowo Aderemi August 20, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

var A = ['C', 'D', 'E', 'F', 'G'];
var B = [3, 0, 4, 1, 2];
var swapShifter = 0;
for (var i = 0; i < B.length; i++) {
while(B[i] !== i){
var key = B[swapShifter];
if(key === i){
var temp = B[i];
var tempChar= A[i];
B[i] = B[swapShifter];
A[i] = A[swapShifter];
B[swapShifter] = temp;
A[swapShifter] = tempChar;
swapShifter=i;
}
else{
swapShifter++;
}

}


}

- Okeowo Aderemi August 20, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

var A = ['C', 'D', 'E', 'F', 'G'];
var B = [3, 0, 4, 1, 2];
var swapShifter = 0;
for (var i = 0; i < B.length; i++) {
    while(B[i] !== i){
        var key = B[swapShifter];
        if(key === i){
            var temp = B[i];
            var tempChar= A[i];
            B[i] = B[swapShifter];
            A[i] = A[swapShifter];
            B[swapShifter] = temp;
            A[swapShifter] = tempChar;
            swapShifter=i;
        }
        else{
            swapShifter++;
        }

    }


}

- Okeowo Aderemi August 20, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

var A = ['C', 'D', 'E', 'F', 'G'];
var B = [3, 0, 4, 1, 2];
var swapShifter = 0;
for (var i = 0; i < B.length; i++) {
while(B[i] !== i){
var key = B[swapShifter];
if(key === i){
var temp = B[i];
var tempChar= A[i];
B[i] = B[swapShifter];
A[i] = A[swapShifter];
B[swapShifter] = temp;
A[swapShifter] = tempChar;
swapShifter=i;
}
else{
swapShifter++;
}
}
}

- Okeowo Aderemi August 20, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

const A = ['C', 'D', 'E', 'F', 'G'];
const B = [ 3,   0,   4,   1,   2 ];

const reorder = (xs, ys) => {
  const map = ys.reduce((acc, x, i) => Object.assign(acc, {[x]: xs[i] }), {});
  return Array(xs.length)
    .fill(null)
    .map((_, i) => map[i])
}

reorder(A,B)

- Javascripter October 09, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

JS
function sort(a,b){
var result = [];
B.map(function(item, i){
return result[item]=A[i];
})
return result;
}

- Una October 10, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

If we could use some memory space this could do the trick.
const sort = (A, B) => {
A = B.reduce((prev, curr, index) => {prev[curr] = A[index]; return prev;}, []);
}

- Tom December 17, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

My answer:

import { expect } from 'chai';


var A = ['C', 'D', 'E', 'F', 'G'];
var B = [3, 0, 4, 1, 2];
// A is now [D, F, G, C, E];

function sort(aa, bb) {
  const res = [];

  bb.forEach((newIndex, index) => {
    res[newIndex] = aa[index];
  });

  return res;
}

describe.only('leo: ', function() {
  it(`array sort`, function() {

    expect(sort(A, B)).to.deep.equal(['D', 'F', 'G', 'C', 'E']);
  });
});

- LeoCorrea March 19, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import { expect } from 'chai';


var A = ['C', 'D', 'E', 'F', 'G'];
var B = [3, 0, 4, 1, 2];
// A is now [D, F, G, C, E];

function sort(aa, bb) {
const res = [];

bb.forEach((newIndex, index) => {
res[newIndex] = aa[index];
});

return res;
}

describe.only('leo: ', function() {
it(`array sort`, function() {

expect(sort(A, B)).to.deep.equal(['D', 'F', 'G', 'C', 'E']);
});
});

- LeoCorrea March 19, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

var a = ['C', 'D', 'E', 'F', 'G'];
	var b = [3, 0, 4, 1,2];
	var c = {};
	b.forEach((val, i) => c[val] = a[i]);
	a = Object.keys(c).map(k => c[k]);

- Anonymous June 25, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Javascript solution, O(n) time, O(1) space

function swap(list, a, b) {
  const temp = list[a];
  list[a] = list[b];
  list[b] = temp;
}

function sortIndexes(list, indexes) {
  let start = 0;
  while (start < list.length) {
    if (indexes[start] !== start) {
      swap(list, start, indexes[start]);
      swap(indexes, start, indexes[start]);
    } else {
      start++;
    }
  }
  return list;
}

const list = ['C', 'D', 'E', 'F', 'G'];
const indexes = [ 3, 0, 4, 1, 2 ];

console.log(sortIndexes(list, indexes));

- Vic July 08, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

const reArrange = (a, b) => {
	let c = [];
	let i = 0;
  while(i < a.length || i< b.length){
  	c.splice(b[i], 0, a[i]);
    i++;
  }
  return c;
}

console.log(reArrange(a, b));

- Ambica August 23, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

const reArrange = (a, b) => {
	let c = [];
	let i = 0;
  while(i < a.length || i< b.length){
  	c.splice(b[i], 0, a[i]);
    i++;
  }
  return c;
}

console.log(reArrange(a, b));

- Ambica August 23, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

{{ var A = ['C', 'D', 'E', 'F', 'G'];
var B = [3, 0, 4, 1, 2];
var c = [];
var tempVal;
var tempInd;
var i;

for(i = 0; i < A.length; i++) {
console.log(i);
tempVal = A[B[i]]; //set temp to index from B in A
tempInd = B[B[i]]
A[B[i]] = A[i]; //Swap the two values
B[B[i]] = B[i];
B[i] = tempInd;
A[i] = tempVal;
}
}}

- Greg October 02, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

for (var i = 0; i < a.length; i++) {
if(b[i] != i) {
var temp = a[b[i]];
a[b[i]] = a[i];
a[i] = temp;

temp = b[b[i]];
b[b[i]] = b[i];
b[i] = temp;
}
}

- NKurapati May 09, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

First Brute-force solution using JS

function sortByIndex(list, indexes) {
  if (list.length !== indexes.length ){
    throw new Error("the list length must match the indexes length");
  }

  for (let i=0;i<list.length;i++){
      const index= indexes[i];
      const tmp = list[index];
      list[index] = list[i];
      list[i]  = tmp;

      const tmp2 =  indexes[i];
      indexes[i] = indexes[index];
      indexes[index] = tmp2;
  }
  return list;
}

- Aiman October 09, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

var A = ['C', 'D', 'E', 'F', 'G'];
var B = [3, 0, 4, 1, 2];

const sort = (arr, indexes) => {
  let result = new Array(arr.length);
  for (var i = 0; i < arr.length; ++i) {
    result[indexes[i]] = arr[i];
  }
  
  return result;
}

A = sort(A,B);

- Mike Tempest January 27, 2020 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

var A = ['C', 'D', 'E', 'F', 'G'];
var B = [3, 0, 4, 1, 2];

const sort = (arr, indexes) => {
  let result = new Array(arr.length);
  for (var i = 0; i < arr.length; ++i) {
    result[indexes[i]] = arr[i];
  }
  
  return result;
}

A = sort(A,B);

- Michael Tempest January 27, 2020 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

const reorder = (arr, ind) => {
const result = [];
ind.forEach((el, i) => result[el] = arr[i]);
return result;
}

- Dmytro February 02, 2020 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

const sortBy = (A, B) => {

    for (let i = 0; i < A.length; i++) {
        let index = B[i];
        [A[i], A[index]] = [A[index], A[i]]; // swap 
        [B[i], B[index]] = [B[index], B[i]]; // swap 
    }

    return A;

}

- far00q es6 May 22, 2020 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

A = ['C','D','E','F','G']

B =[3,0,4,1,2]

new_A = []
loop = len(A)
k = 0
least = 0
while k<loop:
for i in B:

if i == least:
x = B.index(i)
print (x)
new_A.append(A[x])
least += 1
k += 1

print (new_A)

- davenyauchi October 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

#answer in python

A = ['C','D','E','F','G']

B =[3,0,4,1,2]

new_A = []
loop = len(A)
k = 0
least = 0
while k<loop:
    for i in B:
        
        if i == least:
            x = B.index(i)
            print (x)
            new_A.append(A[x])
            least += 1
    k += 1
    


print (new_A)

- davenyauchi October 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

Python implementation. Time complexity O(n)

def twosets(s,t):
    table =dict()
    lis = []
    q = s+t
    point = 0
    for i in t:
        table[i] = s[point]
        point = point +1
   for i in table.iteritems():
        lis.append(i)
    return lis



A = ['C', 'D', 'E', 'F', 'G']
B = [4,3,1,0,2]

print twosets(A,B)

- revanthpobala October 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

Here's a JavaScript implementation

function sort(A,B) {
	var newA = [];
	for (var i=0; i<B.length; i++) {
		var x = B.indexOf(i);
		newA.push(A[x]);
	}
	return newA;
}

var A = ['C','D','E','F','G'];
var B = [3,0,4,1,2]
A = sort(A,B);

- Sudheesh Singanamalla October 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

c++, implementation

struct Object {
	char value;
	Object(char v) {
		value = v;
	}
};

void solve(vector<Object>& A, vector<int> B) {
	int from, to, i;
	Object temp(' ');

	if (A.size() != B.size()) return;

	for (from = 0; from < A.size(); from++) {
		to = B[from];
		if (from == to) continue;
		temp = A[from];
		A[from] = A[to];
		A[to] = temp;
		i = from + 1;
		while (i < A.size()) {
			if (B[i] == from) {
				B[i] = to;
				break;
			}
			i++;
		}
	}
}

- kyduke October 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

You can do it in O(n) time and O(n) space. For each index, swap the current index in A with the index specified in B. If the current index has been swapped to before, skip. The indices that were swapped to can be kept in a hash table for O(1) look up. Here's a c++ code for it.

include <stdlib.h>                                                            
#include <stdio.h>
#include <vector>
#include <set>

void sort(std::vector<char>& a, std::vector<int>& b){
  std::set<int> swapped;  //using a set, but ideally, a hash table for O(1) lookup

  if(a.size() == b.size()){
    for(unsigned int i = 0; i < a.size(); i++){
      if(swapped.find(i) == swapped.end()){
        char temp = a[b[i]];
        a[b[i]] = a[i];
        a[i] = temp;
        swapped.insert(b[i]);
      }
    }
  }
}

int main(){
  std::vector<char> a;
  a.push_back('C');
  a.push_back('D');
  a.push_back('E');
  a.push_back('F');
  a.push_back('G');
  std::vector<int> b;
  b.push_back(3);
  b.push_back(0);
  b.push_back(4);
  b.push_back(1);
  b.push_back(2);

  sort(a, b);
  for(unsigned int i = 0; i < a.size(); i++)
    printf("%c, ", a[i]);
  printf("\n");

  return 0;
}

- zkaiwen October 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

I do not make new array and do not change array size.

javascript, implementation, O(n) without indexOf

function sort(A, B) {
	var temp, from, to, idx;
	
	if (!(A instanceof Array) || !(B instanceof Array)) return;
	if (A.length != B.length) return;
	
	for (from = 0; from < A.length; from++) {
		to = B[from];
		if (from == to) continue;
		temp = A[from];
		A[from] = A[to];
		A[to] = temp;
		idx = B.indexOf(from);
		if (idx > from) {
			B[idx] = to;
		}
	}
}

- kyduke October 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Does making a new array affect its time complexity?

- davenyauchi October 26, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

how this algo is O(n) ???
here you are using "idx = B.indexOf(from);", this is library function it takes O(n).
so complexity of this code is O(n^2)

- Anonymous October 26, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

try it for {'C','D','E','F','G'} and {4,3,1,0,2}

- Anonymous October 26, 2015 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

O(n) JavaScript solution in 3 lines

A.forEach(function(value, index) {
    A[B[index]] = value;
});

console.log(C);

- Utkarsh Shrivastava November 09, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

var a = ['C', 'D', 'E', 'F', 'G'];
var b = [ 3,   0,   4,   1,   2 ];

for (let i = 0; i< b.length; i++) {
	var temp = a[i]; 
	a[i] =  a[b[i]]; 
	a[b[i]] = temp; 
	
	var tempIndex = b[i]; 
	b[i] = b[b[i]]; 
	b[tempIndex] = tempIndex; 
}

console.log(a);

- Rohan July 29, 2016 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More