Javascript/Frontend DS&A Interview questions

No Frontend interview is complete without DS/Logic question. Interviewers usually look at your problem solving skills in this round. In this series of blogs, we will go through most frequently asked Data Structure and Algorithms questions in Javascript/Frontend interviews. Let's start 🚀

1. Sum(1)(2)(3)….(n)( )

We need to write a function Sum which when called should give output as below:

1. sum(1)(2)() = 3

2. sum(1)(2)(3)(4)() = 10

As we can see here when we call sum function with an argument it should return a new function, we need to conditionally return a new function. The condition for this, would be the argument to second call.

When we don’t have argument in the second call, then we need to return the result else we need to return a function which call sum function with sum as parameters.

Let’s have look at the solution for this problem now.

const sum  = function (a) {
  return function (b) {
    if (b) {
      return sum(a+b); //  we call sum function again with argument as a+b and return a function which again can take an argument.
    }
    return a; // it will keep on adding 1+2+3+4..
  }
}

const result= sum(1)(2)(3)();
console.log(result); // prints 6

2. Recursively flatten an array

This is one of the most asked question in Javascript interviews. In this problem we will given an recursive array. We need to write a function which will accept array as argument and should return flattened version of array.

Example:

1. [1,[2,3],[4,5],6]→[1,2,3,4,5,6]

2. [1,2,3,[4,5,6],7,[8,9,[10,11],],12]→[1, 2,3,4,5,6,7,8,9,10,11,12]

Let's have look at the solution for this problem now

function flat(a) {
  const result = [];
  for (let element of a) {   // loop over every element in the array
    if (Array.isArray(element)) {  // check if the element is itself an array
      result.push(...flat(element));    // recursively call the flat method , spread it's result and push into 
      resultant array
    } else {  // element is not an array
      result.push(element);    // push the element into the result array
    }
  } 
  return result;
}

var a = [1, 2, 3, [4, 5, 6, [7, 8]]];
const result = flat(a);
console.log(result);  // prints [1,2,3,4,5,6,7,8]

Sometimes interviewers tweak this problem a little bit and give you a depth d up to which you need to flatten the array. The solution to this problem is same as original problem with a condition. Here's a challenge for you, post the answer to this problem in the comment section.

This was the first blog from Javascript/Frontend DS&A Interview questions series. I hope this blog will help you in your interviews.

I'd love to connect with you at LinkedIn

Stay tuned for more blogs. Happy coding!