All front end Interview questions

This readme is a compilation of all the question asked during my recent COVID-19 job hunt. I’ve also attached a list of resources that I’d referred for the preparations.
The questions are divided into following sections.

  • JS
  • Coding
  • Assignments
  • Miscellaneous

The solution that were provided by me were not production ready code. Try implementing your own approach.

JS

1) Given a multidimensional array with depth of n, flatten it. Once flattened make it available as a method on array instance

Solution

/**
 * [1,2,[3,4]] -> [1,2,3,4]
 */

let arr = [1,2,[3,4, [5,6, [7, [8, 9, 10]]]]]

function flatten(arr) {
  return arr.reduce(function(acc, next){
    let isArray =  Array.isArray(next)
    return acc.concat(isArray ? flatten(next) : next)
  }, [])
}

if (!Array.prototype.flatten) {
  Array.prototype.flatten = function() {
    return flatten(this)
  }
}
console.log(arr.flatten());

2) Create a promise from scratch

Solution

class CustomPromise {
  state = "PENDING"
  value = undefined
  thenCallbacks = []
  errorCallbacks = []

  constructor(action) {
    action(this.resolver.bind(this), this.reject.bind(this))
  }

  resolver(value) {
    this.state = "RESOLVED"
    this.value = value
    this.thenCallbacks.forEach((callback) => {
      callback(this.value)
    })
  }

  reject(value) {
    this.state = "REJECTED"
    this.value = value
    this.errorCallbacks.forEach((callback) => {
      callback(this.value)
    })
  }

  then(callback) {
    this.thenCallbacks.push(callback)
    return this 
  }

  catch (callback) {
    this.errorCallbacks.push(callback)
    return this 
  }
}

let promise = new CustomPromise((resolver, reject) => {
  setTimeout(() => {
    const rand = Math.ceil(Math.random(1 * 1 + 6) * 6)
    if (rand > 2) {
      resolver("Success")
    } else {
      reject("Error")
    }
  }, 1000)
})

promise
  .then(function(response){
    console.log(response)
  })
  .catch(function(error){
    console.log(error)
  })

3) Filter movie list by average rating, name. Sort filtered list by any field inside movie object

Solution

// O(M)
function getMovies() {
  return []; // [{id, name, year}]
}

// O(R)
function getRatings() {
  return []; // [{id, movie_id, rating}]   0 <= rating <= 10   // e.g 9.3
}

/**
 * minAvgRating ->
 *    avgRating >= minAvgRating
 *
 * sort ->
 *    name -> ascending order movies by name
 *   -name -> descending
 *
 *    avgRating
 * 
 *
 * search ->
 *   'ave' -> 'Avengers'
 *   'avengers' -> 'Avengers'
 *   'AvengersInfinitywar' -> 'Avengers'
 */
const toLower = str => str.toLocaleLowerCase()

const getAvrgRating = (movie, movingWithRatings) => {
  let count = 0;
  return movingWithRatings.reduce((acc, value, index) => {
    const movieMatch = movie.id === value.movie_id
    if (movieMatch) {
      acc+=value.rating
      count++
    }
    if (index === movingWithRatings.length - 1) {
      acc = acc/count
    }
    return acc
  }, 0)
}

const isSubString = (str1, str2) => {
  str1 = toLower(str1.split(" ").join(""))
  str2 = toLower(str2.split(" ").join(""))
  if (str1.length > str2.length) {
    return str1.startWith(str2)
  } else {
    return str2.startWith(str1)
  }
}

const moviesList = getMovies()
const movingWithRatings = getRatings();
function queryMovies({ search, sort, minAvgRating }) {
  let filteredMovies = movingWithRatings.filter(movie => getAvrgRating(movie, movingWithRatings) >= minAvgRating);
  filteredMovies = filteredMovies.map(movie => moviesList.filter(listItem => listItem.id === movie.movie_id).pop())
  filteredMovies = filteredMovies.filter(movie => isSubString(toLower(movie.name), toLower(search)))
  filteredMovies = filteredMovies.sort((a, b) => {
    const isDescending = sort[0] === '-' ? true : false
    let sortCopy = isDescending ? sort.slice(1) : sort
    const value1 = a[sortCopy]
    const value2 = b[sortCopy]
    if (isDescending) {
      return value1 > value2 ? -1 : 1
    }else {
      return value1 < value2 ? -1 : 1
    }
  })
  filteredMovies = filteredMovies.map(movie => ({
    ...movie,
    avgRating: movingWithRatings.filter(ratedMovie => ratedMovie.movie_id === movie.id)[0].rating
  }))
  return filteredMovies
}

4) Given an end point URL to fetch all the posts and comments. Do the following.

  • Map all the comments to the posts it belongs to. The resultant data after mapping should be of below structure.

Solution


//service.js
const POSTS_URL = `https://jsonplaceholder.typicode.com/posts`;
const COMMENTS_URL = `https://jsonplaceholder.typicode.com/comments`;

export const fetchAllPosts = () => {
  return fetch(POSTS_URL).then(res => res.json());
};

export const fetchAllComments = () => {
  return fetch(COMMENTS_URL).then(res => res.json());
};


import { fetchAllPosts, fetchAllComments } from "./service";



const fetchData = async () => {
  const [posts, comments] = await Promise.all([
    fetchAllPosts(),
    fetchAllComments()
  ]);

  const grabAllCommentsForPost = postId =>
    comments.filter(comment => comment.postId === postId);

  const mappedPostWithComment = posts.reduce((acc, post) => {
    const allComments = grabAllCommentsForPost(post.id);
    acc[post.id] = allComments;
    return acc;
  }, {});

  console.log("mappedPostWithComment ", mappedPostWithComment);
};

fetchData();

5) Implement a method getHashCode on string instance. The method should be available on all strings.

Solution

let s1 = "sample"

if (!String.prototype.getHashCode) {
  String.prototype.getHashCode = function(){
    console.log('String instance ', this)
    return this
  }
}

6) What does the below expressions evaluate to

    1+true
    true+true
    ‘1’+true
    ‘2’ > ’3’
    ‘two’>’three’

Solution

2
2
1true
false
true

7) Implement bind and reduce.

Solution


//bind
if (!Function.prototype.bind) {
  Function.prototype.bind = function(...arg){
    const func = this
    const context = arg[0]
    const params = arg.slice(1)
    return function(...innerParam) {
      func.apply(context, [...params, ...innerParam])
    }
  }
}

//reduce
Array.prototype.reduce = function(func, initState) {
  const arr = this
  const callback = func
  let init = initState

  arr.forEach(function(value, index){
      init=callback(init, value)
  })
  return init
}

8) Implement debounce function

Solution

const debounce = function(func, interval) {
  let timerId;
  return function(e){
    clearTimeout(timerId)
    timerId = setTimeout(function(){
      func.apply()
    }, interval)
  }
}
debounce(apiCall, 3000)

9) Design API polling mechanism. The API is called after a fixed interval. The API is a stock API that fetches the latest price of stock. Upon fetching the results, render the UI.

The question demands the design aspect of the solution and not the code. It was open ended question.

Solution

//With setInterval, throttling and flags
setInterval=>Endpoint=>Render

//with the inversion of control
//Endpoint=>Render=>setTimeout=>Endpoint=>Render=>SetTimeout...

Algorithms

1) Consider the following series:

A := 1
B := A*2 + 2
C := B*2 + 3 and so on...

Write a program that:

outputs the number corresponding to a given letter

given a string of letters like ‘GREP’, computes the sum of the numbers corresponding to all the letters in the string (i.e., G + R + E + P), as given by the above series and

given a large number (that would fit into a standard 32-bit integer), finds the shortest string of letters corresponding to it.

You may use a greedy approach for the last part. Compute the values of the numbers corresponding to letters as and when required and DO NOT pre-compute beforehand and store them in a data structure.

Solution

//A = 1
//B = A*2 +2 
//C = B*2+ 3
//D = C*2+ 3

var genCharArray = function(charA, charZ) {
    var a = [], i = charA.charCodeAt(0), j = charZ.charCodeAt(0);
    for (; i <= j; ++i) {
        a.push(String.fromCharCode(i));
    }
    return a;
}

var charMap = {};
var charArray = genCharArray('a', 'z');

charArray.forEach(function(char, index){
    charMap[char] = Number(index + 1);
});


var charSequence = function(char){
    if(typeof char==="string"){
        char = charMap[char];
    }
    if(char==1){
        return 1;
    }else{
        return char + 2 * charSequence(char-1);
    }
}

var input = process.argv[2];

if(input.length===1){
    console.log(charSequence(charMap[input]));
}else if(input.length>1){
    var charTotalSequence = input.split("").reduce(function(acc, curr){ 
        return acc + charSequence(charMap[curr]);
    },0);
    console.log(charTotalSequence);
}

2) Given an array find a pair such that it sums to a given number

Solution

let nums = [2, 7, 10, 1, 11, 15, 9]
let target = 11
let numsMap = new Map()
let pairs = nums.reduce((acc, num) => {
  let numToFind = target - num
  if (numsMap.get(numToFind)) {
    return [...acc, [num, numToFind]]
  } else {
    numsMap.set(num, true)
    return [...acc]
  }
}, [])

console.log("Pairs ", pairs)

3) Find the local maxima in a given array. A local maxima is a element that is greater than it’s left and right neighbours. I provided a O(n) solution which was quite straight forward before going for optimisation.

Solution

let x = [1, 2, 3, 5, 4] //Outputs: 5
if x.length == 1 return x[0]
else 
 let i = 1
 for(;i<x.length-1;i++){
  if x[i-1]<x[i] and x[i] > x[i+1] return x[i]
 }
 if x.length - 1 == i return x[i]


4) Rotate a matrix clockwise by 90 degree. The solution should be in place.

leetcode

Solution

[
 [1, 2, 3],
 [4, 5, 6],
 [7, 8, 9]
]
//The solution is to first take the transpose of the matrix.
//After taking the transpose the resulting matrix is as follows.
[
 [1, 4, 7],
 [2, 5, 8],
 [3, 6, 9]
]
//After the transpose step, All we have to do is to reverse the array @ each entry.
//The resulting matrix after after reversal is as follows.
[
 [7, 4, 1],
 [8, 5, 2],
 [9, 6, 3]
]
//The above matrix is rotated 90 degree

5) Maximum subarray sum modulo m

Solution


6) Given an array find three element in array that sum to a given target

Solution

let x = [1, 2, 3, 4, 5]
let target = 7
let found = []

const twoPointer = (l ,r, current) => {
  while(l<r){
    const totalSum = current + x[l] + x[r]
    if (totalSum === target) {
      found.push([current, x[l], x[r]])
      return
    } else if (totalSum > target) {
      r--
    } else {
      l++
    }
  }
}

const threeSum = (x, target) => {
    for (let i=0;i<x.length;i++) {
      const current = x[i];
      let leftPointer = i+1
      let rightPointer = x.length - 1

      if (current+x[leftPointer]+x[rightPointer] === target) {
        found.push([current, x[leftPointer], x[rightPointer]])
      } else {
        twoPointer(leftPointer, rightPointer, current)
      }
  }
  return found
}

7) Given a string and an integer k, find number of substrings in which all the different characters occurs exactly k times.

link

Solution

const subStrHasSameCharCount = (str, startIndex, endIndex, totalHop) => {
  let charMap = {}
  for (let k=startIndex;k<endIndex;k++) {
    let currentChar = str[k]
    if (charMap[currentChar]) {
      charMap[currentChar]++
    } else {
      charMap[currentChar] = 1
    }
  }
  let totalCount = Object.values(charMap).length > 0
  return totalCount ? Object.values(charMap).every(item => item == totalHop) : false
}


const characterWithCountK = (str, k) => {
  if (k == 0) return ''
  let count = 0
  let initialHop = k
  while (initialHop < str.length) {
    for (let j=0;j<str.length;j++) {
      let startIndex = j
      let endIndex = j + initialHop
      if(endIndex > str.length) continue
      count = subStrHasSameCharCount(str, startIndex, endIndex, k)
        ? count + 1: count
    }
    initialHop+=k
  }
  count = subStrHasSameCharCount(str, 0, initialHop, k)
        ? count + 1: count
  return count
}


let str = 'aabbcc'
let k = 2
console.log(characterWithCountK(str, k))

8) Given two input strings, s1 and s2, containing characters from a-z in different orders, find if rearranging string in s1 results in a string that is equal to s2.

Solution

let s1 = 'dadbcbc'
let s2 = 'ccbbdad'
let charMap = {}

const canBeRearranged = (s1, s2) => {
  if(s1.length!==s2.length){
    return false
  }
  for(let i=0;i<s1.length;i++){
    const charFromString1 = s1[i]
    const charFromString2 = s2[i]
    if(charFromString1 in charMap){
      charMap[charFromString1]++
    } else {
      charMap[charFromString1] = 1
    }
    if(charFromString2 in charMap){
      charMap[charFromString2]--
    } else {
      charMap[charFromString2] = -1
    }
  }
  for(let x in charMap){
    if (charMap[x]!==0){
      return false
    }
  }
  return true
}

canBeRearranged(s1, s2)

9) Given an array or variable input size, write a function to shuffle the array.

Solution

const swap = (index1, index2, arr) => {
  let temp = arr[index1]
  arr[index1] = arr[index2]
  arr[index2] = temp
}

const shuffle = (arr) => {
  let totalLength = arr.length
  while(totalLength > 0) {
    let random = Math.floor(Math.random() * totalLength)
    totalLength--
    swap(totalLength, random, arr)
  }
  return arr
}


let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
arr = shuffle(arr)

10) Calculate the sum of all elements in a multidimensional array of infinite depth.

Solution

let arr = [4, 5, 7, 8, [5, 7, 9, [3, 5, 7]]]
let sum = 0

const calculateSum = (arr) => {
  arr.reduce(function(acc, currentVal) {
    const isEntryArray = Array.isArray(currentVal)
    if (isEntryArray) {
      return acc.concat(calculateSum(currentVal))
    } else {
      sum+=currentVal
      return acc.concat(currentVal)
    }
  }, [])
}
calculateSum(arr)
console.log(sum)

11) Flatten a nested object of varying debt.

Solution

const obj = {
  level1: {
    level2: {
      level3: {
        more: 'stuff', 
        other: 'otherz',
        level4: {
          the: 'end',
        },
      },
    },
    level2still: {
      last: 'one',
    },
    am: 'bored',
  },
  more: 'what',
  ipsum: {
    lorem: 'latin',
  },
};

var removeNesting = function(obj, parent){
  for (let key in obj){
    if (typeof obj[key] === "object") {
      removeNesting(obj[key], parent+"."+key)
    } else {
      flattenedObj[parent+'.'+key] = obj[key]
    }
  }
}

let flattenedObj = {}
const sample = removeNesting(obj, "");
console.log(flattenedObj);

12) Given a json input, where each entry represents a directory such that each directory in turn can have a nested entry of it’s own. Create the resulting directory structure.

Solution


Assignments

1) Design a parking lot system with following requirements:

  • It can hold up to N vehicles. Handle availability of parking lot.
  • Entry and exit log of vehicles.
  • Automated ticketing system for every vehicle entering/exiting the parking lot will have vehicle registration with vehicle details like: Registration No., Color, allocated parking slot.

I should be able to query:

  • Registration No. of all vehicles of a particular color.
  • Parking slot of a vehicle given registration no.
  • Parking slots for vehicles given a color.
  • List of available slots in the parking lot.

Requirements:

  • Can use anything to structure the code: Classes/Structs.
  • Your solution should be extendable for future use cases.

Few code design principles:

  • Modularity of code.
  • Naming conventions.
  • SOLID principles.

Solution


2) Create a react component Ping that makes an API call to a given URL. If the API calls returns status code 200 that means the user is online. However, if the API call receives status code other than 200 it means, the user is offline.

Try changing status form dev tools network panel

Solution


3) Create a dynamic form builder from a json input. The form can be grouped based on id. Each group can have a nested group of it’s own.

Solution


4) Create a minimal excel sheet in pure javascript that supports adding and removing rows, columns. There was time limit on this question of 40 minutes.

Solution


5) You have to make a search input box which will search over a list of users.

The user object has the following fields

   id: a unique id
   name: user’s name
   items: list of items ordered by user
   address: address of the user
   pincode: user address pin code

You have to implement search on all of the fields.

The search results will show up as a list of User Cards.

To Summarize
On typing in the search input box, the search results list opens up. The search could be just a string matching search.

The list of cards can be navigated through keyboard or mouse
only one card should highlight at a time if both mouse and keyboard are used for navigation

(keyboard will take preference if mouse is kept hovered on the list, similarly mouse will take preference if keyboard navigation is not used).

This behaviour is similar to how youtube search works

When no search results are found, an empty card is displayed
The card list would be scrollable.

The highlighted card (via keyboard/mouse) will scroll into view

Solution

Miscellaneous

1) How would you architect a front end application click
1) Implement Lazy loading click
2) What is Server Side Rendering.
3) How to deploy a react app to production.
4) What are service worker/web worker.
5) How to optimise a web app and make it more performant.
6) Explain different type of client side cache strategies.
7) What is CORS.
8) What are higher order component in react.
9) How does connect function work in redux.
10) What are pure components in React.

Resources

link