Showing posts from December, 2020

Coding Interview Questions set 5

  Let's begin with set 5, Q11)Valid Parentheses problem. Given a string s containing only the characters '(', ')', '{', '}', '[' and ']',  determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Examples : a)Input: s = "()" Output: true Example 2: b)Input: s = "()[]{}" Output: true Example 3: c)Input: s = "(]" Output: false Solution: var isValid = function(s) {    const obj={             "}":"{",             "]":"[",             ")":"(",         },     var stack=[];            for(let i=0;i<s.length;i++){        if(s[i] in obj) {           if(!stack.length || stack[stack.length-1]!==obj[s[i]]) {               return false;            }           else stack.pop();      }else stack.push(s[i]);   }  return !stack.length; }; L

Data structure problem 1:Implement a queue using 2 stacks.

This is one of the interview questions asked in technical or data structure round. As we know stack is first in last out and queue is first in first out. Here we have to implement the behaviour of queue using 2 stacks. So let's begin with one of the approaches, For 2 stacks we have define 2 arrays; var stack1=[]; var stack2=[]; For insertion or push, we will use stack1. For any insertion, we can push it in stack1 array. a)Insert "A" stack1.push("A"); b)Insert "B" stack1.push("B"); c)Insert "C" stack1.push("C"); Now when we remove or pop, the first pushed element should be removed first i.e behaviour of a queue.    So if we poped from stack1 we will get the behaviour of stack here. stack1.pop()//"C" will be removed i.e behaviour of stack last in first out. We can't use this, so we will need stack2 for this purpose to implement the behaviour of the queue. d)Remove or pop: For first remove or pop, we will need