Algorithmic problems with JavaScript

May 23, 2018 0 Comments

Algorithmic problems with JavaScript

 

 

YoYo. This article is for people who are bored doing trivial tasks every day. This might cheer you up a bit. You might also encounter these kind of questions in some interviews.

1.Soooo, here is the first one — Imagine we have a string which is a math expression (e.g. (1+(2*3–2))+3). We have to create a function to decide whether or not its parentheses are valid. This means that every opening parenthesis should have it’s own closing one. 1+(2+3) is valid, (1+(2))) is not.

Think of a good algorithm which will be the fastest and use minimum amount of memory…

Answer ahead!!!

If you have thought of creating a stack you are good! As we are not interested in keeping the actual data in stack, we can just use a simple counter. Here is the algorithm I suggest:

The solution
Will be glad to see better ideas, just add a response :)

2.Imagine you have an array and you want to find the item in the middle of that array(let’s consider only the case when the array length is even). You can’t use .length. But what you can use is just a for loop.

Think of a good algorithm which will be the fastest and use minimum amount of memory…

Answer ahead!!!

Will be glad to see better ideas, just add a response :)

There are 2 indexes, one going twice as faster than the other. Once the first one gets to the end, the other one get right to the middle.

3.How to remove duplicate values from an array?

Answer ahead!!!

With ES6, you can do the following:

With ES5,

That’s it for today!! I hope to add some more stuff soon. Thank you.


Tag cloud