Front End Engineer Interview Questions | Glassdoor

# Front End Engineer Interview Questions

657

Front end engineer interview questions shared by candidates

## Top Interview Questions

Sort: RelevancePopular Date

### Front End Engineer at Facebook was asked...

Apr 7, 2013
 Given an input array and another array that describes a new index for each element, mutate the input array so that each element ends up in their new index. Discuss the runtime of the algorithm and how you can be sure there won't be any infinite loops.22 Answerspublic static void permute(String[] a, int[] b) { int n = a.length; for (int i = 0; i < n; i++) { while (b[i] != i) { swap(i, b[i], a, b); } for (int j = 0; j < n; j++) { System.out.print(a[j]); } System.out.println(); } } public static void swap(int i, int j, String[] a, int[] b) { int bt = b[j]; b[j] = b[i]; b[i] = bt; String at = a[j]; a[j] = a[i]; a[i] = at; } // you know there aren't infinite loops because the algorithm reduces the number of misplaced elements at each stepJavascript Version: function mutate(input, specArr) { var visited = []; specArr.forEach(function(newIdx, i) { var tmp; visited.push(newIdx); if (visited.indexOf(i) < 0) { tmp = input[i]; input[i] = input[newIdx]; input[newIdx] = tmp; } }); } Trick is to keep track of visited indices and make sure you're not performing unecessary replacements. Run time is THETA(n) as indexOf is a constant-time operation since an array in javascript is simply an object (see http://es5.github.io/#x15.4.4.14 ).function repositionElements(arr, indices) { // assert(arr.length === indices.length) var moved = []; for (var i = 0; i < arr.length; i++) { moved.push(false); } var moveFrom, moveTo, itemToMove; for (moveFrom = 0; moveFrom < arr.length; moveFrom++) { itemToMove = arr[moveFrom]; while (!moved[moveFrom]) { moveTo = indices[moveFrom]; var tmpItem = arr[moveTo]; arr[moveTo] = itemToMove; itemToMove = tmpItem; moved[moveFrom] = true; moveFrom = moveTo; } } return arr; } var arr = ["a", "b", "c", "d", "e", "f"], indices = [2, 3, 4, 0, 5, 1]; repositionElements(arr, indices); // returns: ["d", "f", "a", "b", "c", "e"]Show More Responsesfunction reposition(arr, indices) { var newArr = []; // I'm not sure if extra space is allowed. If it is, the solution should be this simple. for(var i = 0; i < arr.length; ++i) { var newIndex = indices[i]; newArr[newIndex] = arr[i]; } return newArr; } var arr = ["a", "b", "c", "d", "e", "f"]; var indices = [2, 3, 4, 0, 5, 1]; reposition(arr, indices); // returns: ["d", "f", "a", "b", "c", "e"]Essentially the same as Anh's answer but less code, assuming ES5 is available var arr = ["a","b","c","d","e","f"]; var indices = [2, 3, 4, 0, 5, 1]; arr = indices.map(function (item, index) { return arr[indices.indexOf(index)]; });//Bringing 2 UNIDEAL solutions var A = ['a', 'b', 'c', 'd', 'e', 'f']; var B = [4, 3, 2, 5, 1, 0]; //PROBLEM we need a copy of an A to get a proper base index of an element in the sort function var BaseA = A.concat([]); A.sort(function(a, b){ return A.indexOf(a) < B.indexOf(BaseA.indexOf(a)); }); alert[A); //OR We'll just add up to A sorted values and then cut off the tail, I believe it's //almost same performace as to create new array but well, it does mutate A //so is it "Done is better then perfect" after all? :) for(var i = 0, l = B.length; i < l; i++){ A.push(A.splice(B[i], 1, undefined).pop()) } A.splice(0, B.length); alert[A);void swap(int a[],int b[], int i,int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; temp = b[i]; b[i] = b[j]; b[j] = temp ; } void mutate(int a[], int b[], int n) { // solutions 1 . we can sort an array b and while doing that we will // adjust the A[] elements as well // but it is going to be nlogn // Solution 2: swap the elements of b[] ( together with a[] elements) until the number in the b[i] matches the index i then move on to i+1 // for each swap we are placing one item in the right place. // so the complexity would be O(n) for(int i=0;i= n) { cout << "Index out of bound " << b[i] <<< endl; break; } if(i != b[i]) // this may go in infinite loop, if the indices are not good in b like two 0s in the b[] { if(b[i] == b[b[i]]) { cout << "Infinite Loop Detected for the index " << b[i] << endl; break; } swap(a,b,i,b[i]); } else { i++; } } }var assert = require('assert'); var arr = ['a','b','c','d','e','f','g', 'a']; var indexes = [2,1,0,3,4,5,7,6] var mutate = function mutate(arr, ind){ var swapped = {}; indexes.forEach(function(nI, i){ var newEl, el; el = arr[i]; arr[i] = swapped[nI] || arr[nI]; swapped[i] = el; }); }; mutate(arr, indexes) assert.deepEqual(arr, ['c','b','a','d','e','f','a', 'g']);function remap(arr1, arr2){ var tmp1 = arr1.slice(); arr2.map(function(newIdx, realIdx){ arr1[newIdx] = tmp1[realIdx]; }); }Working off of Travis' answer, but removing the need for a new array: function swap(arr, idx1, idx2) { var temp = arr[idx1]; arr[idx1] = arr[idx2]; arr[idx2] = temp; } function reposition(input, indices) { indices.forEach(function(newIdx, i) { if (indices.indexOf(i) > i) { swap(input, i, newIdx) } }); }The idea with "indices.indexOf(i) > i" doesn't work. Counterexample: input: ['A', 'B', 'C', 'D', 'E', 'F', 'G'] indices: [ 4, 0, 5, 3, 1, 6, 2 ] output: [ 'B', 'E', 'F', 'D', 'A', 'C', 'G' ] expected output: [ 'B', 'E', 'G', 'D', 'A', 'C', 'F' ]Here's my take on this, though I think my approach is cheating a little bit since I'm mutating, but not directly in place. It does add a little space complexity since I'm adding a new array, but there are no infinite loop problems and the runtime is just O(n) (I think...I'm really bad at big O notation calculation). function mutateArray(arr,indexes) { var newArr = []; indexes.forEach((ix) => { newArr.push(arr[ix]); }); arr.splice(0).push.apply(arr,newArr); }OK, and after seeing that there's some confusion amongst expected outputs, I've updated my implementation based on the other take on the expected output. This version assumes that each index in the provided index array is the index value of where the element is in the starting array. So if the value at indexes = 3, that would mean the first value in the output would be originalArray; function mutateArray(arr,indexes) { var newArr = new Array(arr.length); indexes.forEach((ix, i) => { newArr[ix] = arr[i]; }); arr.splice(0).push.apply(arr,newArr); } var original = [2, 3, 1, 6, 4]; var ixes = [1, 2, 0, 4, 3]; expected results: [1, 2, 3, 4, 6] For clarity, the other variant is in my answer above. That assumes that the value of each element in the indexes array represents the index of the value of the original array. So in the example above, the output would be [3, 1, 2, 4, 6]. Apparently a common twist is to then ask the interviewee to do this without a new array. So that's worth practicing too.Show More ResponsesOK, and here's my in place version. It could definitely be improved since I just wrote it using the bubble sort algorithm. Any other sorting algorithm would work just fine too. Basically it works by sorting the index array and every time something in the index array is moved, it moves the same elements on the original array. function mutateArray(arr,indexes) { var swapped = true; while(swapped) { swapped = false; for(var i = 1; i indexes[i]) { swap(arr,i-1,indexes[i-1]); swap(indexes, i-1, indexes[i-1]); swapped = true; } } } } function swap(arr, oldIx, newIx) { var temp = arr[newIx]; arr[newIx] = arr[oldIx]; arr[oldIx] = temp; } An example: var arr = [5,2,1,8,9,1]; var indexes = [2,4,1,0,3,5]; var expectedResult = [8,1,5,9,2,1];function changeArr(arr,indArr) { var i, retArr = []; for( i = 0; iSimple solution using .map() & ES6: const inputArray = ["one", "two", "three", "four", "five", "six"] const indexArray = [2, 1, 3, 5, 4, 6] function mutate(input, index) { const newArray = index.map(i => input[i - 1]) return newArray } // output: ["two", "one", "three", "five", "four", "six"]or if you truly want to mutate the array rather than outputting a new array: let inputArray = ["one", "two", "three", "four", "five", "six"] const indexArray = [2, 1, 3, 5, 4, 6] inputArray = indexArray.map(i => inputArray[i-1]) // output: ["two", "one", "three", "five", "four", "six"]const sortBy = (inputArr, idxArr) => idxArr.reduce((acc, x) => acc.concat(inputArr[x]), [])For all of the answer using map, and visited arrays, just to say that you are creating a new array, and from the word "mutate" I assume they don't want any extra space being used at all (also it takes longer) My solution using ES6 is: function mutate(input, indices) { const swap = (i, j) => { let tmp = input[i]; input[i] = input[j]; input[j] = tmp; }; indices.forEach((newIndex, i) => swap(newIndex, i)); return input; }Also for those using indexOf that's an extra O(n) you're using there!let input = [1,2,3,4,5]; let newIndex = [3,1,0,4,2]; function transform(input, newIndex) { let res = []; for (let i = 0; i < input.length; i++) { let index= newIndex[i]; let val = input[i]; res[index] = val; } return res; } function transform2(input, newIndex) { let i = 0; while (i < input.length) { if (i == newIndex[i]) { i++; } else { swap(input, i, newIndex[i]); swap(newIndex, i, newIndex[i]); } } } function swap(arr, i, j) { let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; }function sort(a,b){ for(let i=0, l=b.length; i

### Front End Software Engineer at Yahoo was asked...

Oct 29, 2010
 Design a data structure to store sparse 2D matrix which contains only 0 or 1. then write function to add 2 such matrix. 4 AnswersI first proposed to use array to remember each 1 location. then find out it is quite expensive to do the addition. with the interviewer's help, I result in using hash table. then I was asked to write hash function. It was quite challenge for me. But the interviewer was really nice and very helpful to push me to the limit.use run-length encoding.store each row as a decimal for ex: if the row is 1011 -> store it as 13!Show More ResponsesSince all values are mod 2 you can pack 64 entries together into on int64_t. You can then add two matrices by XORing each entry.

### Search Engineer, Front End at LinkedIn was asked...

Jun 30, 2010
 Find the Kth hisghest element in a given array.5 Answers1. Sort the array and get the element. 2. Put in binary tree. Travel from root and get the kth node.binary tree would not work unless it was balanced and even then searching for the kth highest node would be overly complex. Better answer - Perform k iterations of a bubble sort. Run time would be O(kn). To prevent O(n^2) (k ~ n) reverse bubble sort if k > n/2.http://en.wikipedia.org/wiki/Selection_algorithmShow More Responsesborrow the way of splitting array in quicksort, which can achieve O(n) time in average for any k. The more detail of this algorithm is: select a pivot value, and split the array into three parts. The elements in the first part are less or equal to the pivot value or empty, the second part is one element which is equal to the pivot, and elements in the last part is great them the pivot value or empty. If the index of the second part element is equal to k, then just return it, else if it is greater than k, then go to split the first part recursively, else go to split the third part recursively.function _kth(array, k) { return array.sort(function (a, b) { return b - a; }).slice(0, k); } _kth([1, 23, 12, 9, 30, 2, 50], 3); // [50, 30, 23]

### Front End Engineer, Infrastructure at Facebook was asked...

May 9, 2012
 Given 2 very large numbers, each of which is so large it can only be represented as an array of integers, write a function to multiply them.3 AnswersThis is similar to implementing add, subtract or multiply functions. A good way to do this is use the same mechanism as we do in high school on paper i.e. you have two arrays. Put one as multiplier and the other as multiplicant. Take the right most digit of multiplier, and multiply with last digit of multiplicant, assign the right into start of result (we either reverse result in the end or we assign it in the end of result ensuring result array's size can accommodate number of digits that result from the multiplication. So we have two nested loops, outer one going through each digit of multiplier and inner one going through each of multiplicant. There are special things to cater 1. Carry result of each multiplication to the next. 2. As in standard multiplication each next digit of multiplier results in as many digits of result for e.g. when multiplying 778 with 64 there is one row of results obtained when 4 is multiplied with each of 7,7 and 8 and another row when the same is done with 6. So either we store all these rows first and add corresponding indexes latter or we keep adding them into the final array as we go (without storing them separately)I just coded this too out of curiosity since i only coded big integer + and - in university which was like 6 years ago. So thought of making sure i was right. Here is the function and sample main call. One thing i only found while debugging that two possibilities of carry exist 1. When simply the result of multiplying two numbers 2. When adding a result into existing array. I missed 2 in my implementation at first and only discovered this through testing. Now it's resolved and working. void multiply(int a[], int b[], int sa, int sb) { int sr = sa+sb; int *r = new int[sr]; int res_indx = sr-1; memset(r,0, sr * sizeof(int)); //for(int i=0; i=0; mul--) { int c_indx = res_indx; int carry = 0; for(int mcnt=sb-1; mcnt>=0; mcnt--) { int m = b[mcnt] * a[mul] + carry; int sum = r[c_indx] + (m%10); r[c_indx--] = sum%10; carry = sum/10 + m/10; // two possibilities of carry one in the m and the other in sum if(mcnt == 0) r[c_indx] += carry; // copy the carry digit for the last operand } res_indx--; // X.. moving starting index one column back in each iteration } for(int i=0; iconst unsigned MULTIPLY_BASE = 10; void multiplyLittleEndian(const vector &a, const vector &b, vector &r) { r.assign(a.size()+b.size(), 0); unsigned ri=0; for(unsigned ai=0; ai

### Search Engineer, Front End at LinkedIn was asked...

Jun 30, 2010
 randomize an array.4 Answersjust run the random funtion and replace elements.To perform perfect randomization of an array of elements there is a well known method (all n! permutations of the array are equally probable assuming a perfect random number generator) public static void randomize(int[] a) { int tmp, index; for (int i = 0; i < a.length; i++){ index = (int) (Math.random() * (a.length - i)) + i; tmp= a[i]; a[i] = a[index]; a[index] = tmp; } }Use the Knuth shuffle: http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffleShow More Responses[1, 2, 3, 4, 5].sort(function () { return 0.5 - Math.random(); });

### Front End Software Engineer at eBay was asked...

Sep 25, 2012
 How would you pick the middle element of a list4 AnswersI said by dividing the length with 2. He said there would be two passes involved with that (?). He wanted some way with one pass.int[] intArray = {12,34,56,78,98,31,47}; int startIndex=0; int endIndex=intArray.length -1 ; while(startIndexits a list (assuming not an array).... Take two pointer....increment 1st pointer by 2 everytime & second by 1 [Rabbit & tortoise problem] if 1st pointer(rabbit) reaches the end of the list.... the position of the tortoise is the location of the middle element of the list.Show More ResponsesYou guys are overthinking this var arr = [1,2,3,4,5,6,7]; console.log(arr[Math.floor((arr.length - 1) / 2)]);

### Front End Engineer, Infrastructure at Facebook was asked...

May 9, 2012
 Write a function to compute the square root of a number without using any built-in functions.2 AnswersThey want you to remember your numerical methods/analysis class in college, specifically Newton's method. Or at the least, remember that the square root of a number as calculated by a computer is just a really close guess. Of course, this is like asking a civil engineer questions about lumberjacking. Great question if you're writing a math library for a new language, stupid interview question if you're making a glorified MySpace.A good way to do this is using binary search. Given the number, assume your square root is between 0 and n. Make 0 as your left and n as right. Compute their mid, if mid is less than square root i.e. mid * mid is less than n, assign left as mid as right as mid and continue looping. double sqroot(double n) { double tol = 0.00001; double left = 0; double right = n; double sq = 0; double res=1; while (right-left > tol) { sq = (left + right) / 2; cout << "Low:" << left << " High: " << right << " MID:" << sq << endl; if(sq*sq < n) // n is greater left = sq; else right = sq; } return sq; }

### Search Engineer, Front End at LinkedIn was asked...

Jun 30, 2010
 In a given list of words, find matching words in the list that can be generated from the patterns of a given word.2 Answers1.Get all the permutations of the given word and store them into a hashtable(O(k!), where k is the length of the given word), which can have constant look up time in average. 2. The go through the list of words (O(n), where n is the lengh of the list), to find the words that can also found in the hashtable. So, the total computation time is O(k! + n). If k is assumed a limited constant, then the time will be O(n), and hashtable can also be replaced by the prefix tree (trie).just sort the letters of each word in the list and pattern and find what you need with a string compare.

### Front-end Software Engineer at Playdom was asked...

Oct 26, 2011
 Write a function to reverse a linked-list.1 AnswerCan be done with a simple recursion.

### Front-end Software Engineer at Playdom was asked...

Oct 26, 2011
 Given two set of numbers find all matching pairs.1 AnswerUse hash tables.
110 of 657 Interview Questions