Coding Interview Questions Set 1


From this article, I will be sharing with you all a series of articles on coding interview questions.
So please stay connected for the latest set of questions.
It will be a good brainstorming exercise and will also prepare
you for coding interviews and will definitely boost your confidence.

So let's start,

1)Reverse of a string with only O(1) extra memory.

Solution:

var reverse = function(string) {
    let result = ''
    for(let i= string.length -1; i >= 0; i--){
        result += string[i];
    }
    return result;
};


2)Fizz Buzz: Write a program that will accept a number n and will output number till n but for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.

Solution:

var fizzBuzz= function(n) {
    const arr=[]
    for(i=1; i<=n; i++){
        if(i%15===0) arr.push("FizzBuzz")
        else if(i%3===0) arr.push("Fizz")
        else if(i%5===0) arr.push("Buzz")
        else arr.push(i.toString())
    }
    return arr
};


3)Find a single element in an array of multiple elements where every element appears twice except the one you have to find. Do it in O(n) and with no extra memory.

Solutions:
There are multiple solutions that you can solve this in javascript,

a)     

function findSingle(nums) {
 return nums.reduce((prev, curr) => prev ^ curr, 0);
}

Logic:
The reduce method in JS reduces the array to a single value.
XOR will return 1 only on two different bits.
So if two numbers are the same, XOR will return 0.
Finally, only one number left.
A ^ A = 0 and A ^ B ^ A = B.

b)You have to find it out and have to post it in the comments section.
Hope to see someone in the comment section.

I hope you like this article.
Please stay connected for coding interview questions set 2.
   
Don't forget to subscribe to this blog.
You can also follow me on Twitter or Linkedin for the latest updates.

Written By:

Saurabh Joshi

Comments

  1. const findSingle = (arr) =>
    arr.reduce((acc, curr, idx) => {
    if (acc.includes(curr)) {
    acc.splice(acc.indexOf(curr), 1);
    return acc;
    }
    else { return acc.concat([curr])}
    }, [])

    ReplyDelete

Post a Comment

Popular Posts