Thursday 12 December 2019

Coding Interview


This summer i spent most of my time preparing for coding interview for my placements, during this time i came across some of the great problems for which thinking the solution was really interesting and fun. So i have picked a few of them and discussed how i approached for the solution.

1.Majority element

Given an array you have to find the element(s) which appears more than n/2 times

This question is fairly easy as there are many methods to solve this.
The first thing that should come to your mind is how many such elements can be there.
The answer is only 1 because, suppose we have 2 elements which occurs more than n/2 times where n is the total number of elements in array then the size of array will become (n/2+x) + (n/2+y)=n+(x+y) which is greater than n (where x and y are both greater than or equal to 1) hence it is not possible to have more than 1 element as the majority element.

since we figured out what output we have to give now the question is how to find this output element, one approach is simply the brute force method where we pick every element one by one and count the number of occurrence in the array and if it is greater than the n/2 we will return it but this is not a good solution if we consider the time complexity, another approach is  to use hashmap to keep the count of every element in the array for which we have to first traverse the array and add the key value pair as the array element and it's frequency so far and then traverse the map to find the required element whose value is greater than n/2. This will solve the problem in O(n) but another interesting way to solve this is by using stack which only require one loop traversal in which we add the first element to the stack and start traversing for the rest of the element and apply condition that if top of the stack is not equal to the current element of the array then pop the top element from stack else we push the current element to the stack. After we are done with the traversal of the array, the element at top of the stack is our required majority element because  suppose we have length of array as 10 and our array looks like this {2,1,2,2,2,4,2,2,6,2} now apply the above approach and after you are done with the array traversal you will find the top of the stack has element '2' which is our final required answer.


2.Binary Tree Maximum Path Sum

Given a binary tree we have to find the path having the maximum sum where sum is the addition of the values at all the nodes through that path.
A path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.

This question seems hard at first but once you start thinking about the solution you will realize that it's not that tough of a question. The only catch in this question is that you should be able to figure out that a maximum path of a node can be a single node itself, the node plus it's left sub tree, the node plus it's right sub tree or node plus it's left sub tree plus it's right sub tree hence the solution is nothing but to apply the recursion to every node and keep track of the maximum value 

Once you will see the code you will understand everything:

int findPath(Node* root,int &res)
{
        if(!root) return 0;

        int l=findPath(root->left);
        int r=findPath(root->right);

        int local_max=max(l,r);
        local_max=max(local_max,0);
        local_max=local_max + root->val;

        res=max(res,local_max);
        res=max(res,root->val+l+r);

        return local_max;
}

// Main function which return the maximum path sum given the root
int findMaxSum(Node *root)
{
       int res=INT_MIN;
       findPath(root,res);

       return res;
}


3.Minimum Window Substring

Given 2 strings S and T find the minimum window in S having all letters of string T in O(n).

It is quiet clear from the question what we have to do. Let's say S="ADDBECODEBANC and T="ABC" then we have to return a string as "BANC" as it is the smallest substring in S having all the letters of T.

In this i am going to tell my approach through a series of steps:

First, i defined a string 'ans' which we will return and contains the substring of 'S' with minimum window size.
Now,
1) Define an empty array and initialize it with 0;
2) Traverse the string 'T' and increment the count for the respective  character in the array.
3) Initialize 4 variables: 'left=0' which will point to the first letter of 'S', 'count=0' which we will increment every time we find a letter in 'S' which is there in 'T' as well, 'min=INT_MAX' which will store the minimum value of the window and finally 'len=T.size()' which will store the length of 'T'.
4) Now we loop through 'S' and every time we encounter a letter in 'S' which is there in 'T' we will increment the count variable by 1
5) After this in the same loop we will compare if the count is equal to len, if yes then we find the length of minimum window as (i-left+1) where i is the current index we are at while traversing 'S' and if it is less than min, we will update min by that minimum length and update ans with substring which begins from 'left' till the 'min' length.
6) Now we increment the left value by 1 and before we do that we have to see if (arr[left]+1>0), if yes than the value at S[left] is also there in 'T' hence decrease the count value by 1 since we will encounter that character again as we move forward in 'S'.

In this way once we complete our traversal of 'S' we will have the minimum window size in variable 'min' and required string in variable 'ans'. The below code will explain all the steps that i mentioned. The time complexity is O(n) where n is the size of string 'S'.

Minimum Window Substring


























So these 3 were the some of the amazing question  i came across, there were many good questions but i randomly picked these 3. I hope it will be helpful and if you didn't understand any part of the code, logic/approach you can comment down below.

Note: There is one more question which i think you should know as this question was asked like 5 to 6 times either in online coding tests or in coding interview. In fact it was even asked in the latest and the final interview which i gave, the question is given an array of numbers and a target value you have to find all pairs of number in the array whose sum is equal to target in O(n). 
Try this as this also has many solutions and the best approach will test some of your basic data structure knowledge ;)

Sunday 27 October 2019

Let Us Mine!


With all this recent craze in bitcoins, many wonder how these bitcoins generate since there is no central power who controls all this. 
The answer is through MINING.  

So what exactly is bitcoin mining?


Bitcoin mining is the process of updating the ledger of bitcoin transaction known as blockchain

Anyone can do mining who posses extremely powerful computers like ASICs which compete against other miners to find a specific number which is known as the 'Target'. 
The miner who gets the target number first updates the ledger and get rewarded with 12.5 bitcoins(currently). 

But not everyone sitting at their home can do that because miners have to hash many combinations of letters, numbers and characters until the resulting hash contains the required number of leading "0"s which is called a target. 

The more powerful your computer is, the more guesses you can make per second, increasing your chances of winning this game. 

If you manage to guess right, you earn bitcoins and get to write the next page of Bitcoin transactions on the blockchain. 




What does those powerful machines solve? 


The miner takes a list of all the active transactions, and then groups them together which is called a "block", if i put it more accurately - the miner software converts all the transactions in a summary view called a "merkle root", and hashes it, which is representative of the transactions. 

The mining software then converts this to into a binary format called a Block Header, which references the previous blocks as well(also called a chain). 

The miner then changes a small portion of this block called a "nonce". The block header is hashed and compared simply to the Target like 10,000>7,000 (the real numbers are much bigger, and in hexadecimal). An expanded target looks like this: Target=0000000000000083ef000000000000000000000000000000000. And the goal is to make sure the SHA256 hash of the block is less than this value.

How to start mining?


Now that we know what is mining you might wanna start doing it BUT [Satoshi Nakamoto](https://en.wikipedia.org/wiki/Satoshi_Nakamoto) made some rules regarding mining in a way that the more mining power the network has, the harder it is to guess the target to the mining math problem. 

So the difficulty of the mining process is actually self-adjusting to the accumulated mining power the combined network has. If more miners join, it will get harder to solve the problem; if many of them drop off, it will get easier. This is known as bitcoin mining difficulty.
Mining difficulty is set so that, on average, a new block will be added every ten minutes (i.e., the number will be guessed every ten minutes on average).

Another thing is Bitcoin Mining pool, assuming you’re just entering the Bitcoin mining game, you’re up against some heavy competition. Even if you buy the best possible mining machine out there, you’re still at a huge disadvantage compared to professional Bitcoin miners That’s where mining pool comes into existence. 

The idea is, multiple miners group together to form a pool (i.e., combine their mining power to compete more effectively). Once the pool manages to win the competition, the reward is spread out between the pool members depending on how much mining power each of them contributed. This way, even small miners can join the mining game and have a chance of earning Bitcoin.

Final Words


So the bottom line is that bitcoin and other cryptocurrencies like ethereum are a high risk high reward investment, if you can afford to spend heavily on expensive equipment and energy bills then it is the right thing to do but still with a little uncertainity about the economic role it will have in future since in many countries digital coins are ban.

Monday 7 October 2019

Why Fortnite is boring now?


Just few months back i talked about how and why fornite has become a phenomenon in gaming. But today i also want to share my thoughts on how and why it's becoming boring at the same time.

I first started playing fortnite back in april 2018 when it's season 3 was going on and infact it was my first Battle royale game as well. During that time the game play and the battle royale genre really made me interested in trying this game. I used to have a lot of fun because of their unique building mechanics and also every time i encounter a opponent we just build few walls or ramps and try to shoot each other but now the picture is far different as every time someone sees an opponent even from far behind players starts to sweat out by building huge layers of walls,floors and ramps and starts to crank 90s and what not building strategy they have been practicing in creative.

Basically the problem is that you need to completely become obsessed with the game and have to grind it everyday for hours to win consistently and there is a huge skill gap between people who does that and people who just need to play for fun.Not only you need good aim, you must be quite good at building, editing and experience in playing in some tricky situations. People try way to hard in it making it irritating to play to someone who plays video games for pleasure, everyone plays like they've got millions of dollar son the line. For someone who just need fun can't compete with the level of sweats this game has. It ultimately gets little bit boring and unsatisfied after a point of time.

Another and the utmost big thing is that epic games are just trying to bring their weirdest of things and items in this game that nobody wants. Yes i agree that to keep game fresh and exciting they need to keep adding and removing stuffs but still items like swords, Airplane-"with a turret", and now mechs don't make any sense to when it comes to battle royale. 
Even the competitive is not great to play when you have whole lobby left in the final circles.

Bringing various rifts zone, and doing some of the weirdest changes in map to continue their story line which haven't made any sense so far, apart from it numerous hitching and performance bugs makes it hard to play. If epic try to fix these bugs first rather than introducing new items that would be far better for the game. And since now next season is on its way so let's see what they got in it for their community and hopefully something brill.

Monday 19 August 2019

Fortnite Phenomenon


Recently we have witnessed a 16 year young boy getting $3 million richer at Arthur Ashe stadium in New York. Yes i am talking about Fortnite world cup.
Fortnite battle royale came in July 2017 since than it has only seen it's rise in popularity and not only it has benifit the game makers at epic games but also the various streamers streaming fortnite around the world. Fortnite has definitly become a phenomenon as there is no one in their competition as far as battle royale genre is considered. Many games have even tried of competing with fortnite like call of duty blackout and EA sports' Apex legends but they were unable to attract fortnite players due to various reasons.There are tons of videos and clips out on the internet that had helped many youtubers to become successful too.But why fortnite is like this, why fortnite is so popular among gamers, what different epic games did? There are many points to answer these questions, let me mention the top 5 reasons which i think are the biggest reasons of all:

1) Fortnite is a free to play game
Unlike may other games fortnite is free to play and the only way epic earns money is by in-game purchases which are only the cosmetics like new skins, pickaxes, gliders which provides no competitive advantage. This model of earning has become more popular recently among games.Even the biggest fortnite streamer Tyler "Ninja" blevins also believed that it's free to play nature is the biggest reason for it's high popularity.



2)American pop superstars involving in the game 
When hip hop artist Drake played this game with Ninja the internet exploded with their videos because of which fortnite gained over 50% growth in player base. Not only Drake the fellow artists Travis Scott, Marshmallow, American footballer Juju Smith contributed in increasing the popularity of the game in it's initial months. 


3)Fortnite is noob friendly
Although there are many players who have the mastery on the game after hours of practice but still if a new player wants to come he can become the master too, picking up the basics by playing with friends in playground, practice building in creative and also learning new tactics by watching streams.



4)Fortnite map and their in game events
Fortnite game has only 1 map since the beginning, they only change the locations in the same map keeping it familiar yet novel to it's players from season 1 to season 10(X) fortnite map has changed a lot but they have changed it gradually this makes sure that game is fresh and old players keep coming back for more. Apart from it they also do in game events which makes sure to keep players entertain when they are not grinding for wins. Fortnite even have done the first ever virtual concert with marshmallow which was a huge deal as it attracted 10 million concurrent players.



5)Epic games' huge investments in it's competitive games
Epic recently invested a total of $30 million dollars in it's first ever world cup not only this they have been continuously investing in their competitive scenes through various other in game tournaments to make sure that players stick to their game and show their skills and earn huge money.


So, fortnite is a different game whose creators and developers are smart and knows the formula for keeping the game exciting to build a true titan in the gaming world that's the reason of it's popularity.

Wednesday 24 July 2019

Magical Python


Python nowadays has been considered as one of the most prominent and powerful language that's the reason many programmer are using it as their primary language and also many recruit are also stating their programming in python. So now let's talk about what python can really do that most of the language can't or if they can why people still prefer python over those languages.
Firstly python was introduced in 1991 hence it's a pretty new language as compared to most of the languages we have with us like C,C++ and Java. It has a very user friendly syntax too so that for beginners programming can become an easy start moreover it is popular because of it's scalability, productivity,  and usage in many data science and machine learning problems.
I myself had some beautiful experience with this particular language because you can make some fun scripts which can at times comes out to be useful. So let's discuss about those scripts one by one:
(I have used Jupyter Notebook for all my scripts and in case you don't have any particular library installed you can use 'pip install' command)


1.Playing random Youtube video


I made a script with GUI which can open up the random youtube video in your default browser you just have to put the name of the channel in the input label and BAM! your youtuber's video is right in front of you.

#importing dependencies
from tkinter import *
import random
import webbrowser
import feedparser

#defining the function

def play():
    str1=key.get()
    try:
        url=feedparser.parse("https://www.youtube.com/feeds/videos.xml?user="+''.join(str1))
        video=url.entries[random.randint(1,50)]
        webbrowser.open(video.link)
    except:
        print()

#GUI

window = Tk() 

#Window    
window.title("Youtube Random Play")
window.geometry('400x100')
window.configure(background="#a1dbcd")         

#Label 

msgLabel= Label(window, text="Channel Name: ", font=("Serif", 16), bg="#a1dbcd")
msgLabel.grid(column=1,row=2) 

key=StringVar() 


#Input Entry    
input_msg = Entry(window,textvariable = key, width=20, font=("Serif", 12))
input_msg.grid(column=2, row=2)
input_msg.focus()  

#Button

finalStr = Button(window, text="Open", font=("Serif", 16),command = play) 
finalStr.grid(column=2, row=27)  

window.mainloop() 

P.S. you have to make sure that the channel name you type is the actual channel name that appears in the URL of the youtube channel because most of the youtubers change their channel name but the name youtube provides doesn't change even after that and appears in the URL. For example Youtuber Ninja has his channel name as Ninja but actual/youtube name is NinjasHyper.



2.Check if website is up or down at any point 


Sometimes you may need to check if a website is not working or it is really down for everyone. For this you can use the below script where we scrap the website 'isitup.org' using beautifulsoup library.

from bs4 import BeautifulSoup
import requests

url=input('Enter URL:')

res=requests.get('https://isitup.org/'+url)

soup=BeautifulSoup(res.text,'lxml')

scrap=soup.find('div',{'id':'container'})#finding all div with id=container

output=scrap.find('p').text #getting the result from paragraph tag

print(output)


3.Audio to text converter


This is one of the best thing i believe python can do, if you want to convert the audio file to text then python provides 7 methods for recognising speech from audio source using various APIs.(here i have used a '.wav' file for conversion)

import speech_recognition as sr

r=sr.Recognizer()

audio=sr.AudioFile('harvard.wav')

with audio as source:

    text=r.record(source)
r.recognize_google(text)



If you compare the output with the actual input you will see that it is not 100% accurate but still is pretty nice thing for a programming language to do.


4.Forming a Word Cloud


Word cloud is an image formed from the input words with the size of the word depends upon the frequency of that word in the input.

from wordcloud import WordCloud
import matplotlib.pyplot as plt #for making a plot

text=input("ENTER THE TEXT:")

cloud=WordCloud(background_color="white").generate(text)

plt.imshow(cloud)

plt.axis('off')
plt.show()


5.Spamming on WhatsApp with GUI


Sometimes you want to just want to have fun by spamming a particular messages to your particular contact you can do so by using the below python application the only thing is you have to scan the QR code everytime you run the script and also you need to have the chrome driver downloaded and have to provide it's path in webdriver.chrome() function.
I am only writing the function here for GUI i have used same Tkinter library that i used in 'random youtube play'.

from selenium import webdriver
from tkinter import *

def whatsapp():


        name=key1.get()
        msg=key2.get()
        count=int(key3.get())

        driver=webdriver.Chrome(executable_path='C:/users/tyagi/Downloads/chromedriver.exe')

        driver.get('https://web.whatsapp.com/')


        user = driver.find_element_by_xpath('//span[@title = "{}"]'.format(name))

        user.click()

        msg_box = driver.find_element_by_class_name('_3u328')


        for i in range(count):

            msg_box.send_keys(msg)
            driver.find_element_by_class_name('_3M-N-').click()
        #print('Done...')



I have uploaded all of these code along with all necessary explanation and outputs on my Github:https://github.com/ApoorvTyagi/Magical-Python. Feel free to Pull/fork/contribute to it.

Tuesday 9 July 2019

India in cricket world cup 2019

Now that we have got our 4 semi finalists for this year's cricket world cup it's a good time to analyse and talk about the performance of team India and also to go deep down into questions like what we expected what happened and what to expect in the semi finals.



India entered this world cup as favorites and started its campaign against south africa which they won quite easily thanks to Rohit's brilliant 122* and then kept on winning every match until they encountered the hosts and their new away jersey with one match being washed off against New Zealand but still their run was good enough to keep them at the top of table at the end of league matches.
The only set back for India occurred when Shikhar got injured after scoring a match winning century against the most dominated team in world cups- Australia, though Rahul is doing well in the opening with Rohit  to fill the void created therefore India got rid of their first problem .
Now coming to middle order Virat is doing what he is best known for by playing some important innings through the middle overs just the only thing he is struggling with is he is not able to convert his scores to a big number and our new no. 4 batsman another Delhi boy Rishabh Pant is doing just fine and then comes the most interesting part of this team, the finishers first lets talk about Hardik Pandya. He definitely is playing some good knocks but still if you observe his shot selection you can see that he is not mature enough for that role that's the reason we have Dhoni in our team, but the thing is people always find a way to criticize him even though at the end of the innings his S.R. is
always more than or near to 100 this is the thing that sometimes bother me. If we look at Dhoni's playing style he always started slow initially and hits the boundaries in few last overs i definitely agree that he is not playing the innings he is known for but the fact is he is 38 now it's not easy for him to be in same form as he was in his peak time even the Sachin took a lot of innings to score his 100th century against Bangladesh and we even lose the match and his strike rate was even below 80. And if at the end of the day in a pressure game like world cup if we are winning the match than it doesn't matter if Dhoni played with the sr of 70 or of 120 because at the end of the day in a world cup match what matter the most is who won that particular match.
Now talking about our our bowling which is one of the best bowling lineup because in every other team either they have good pacers or they have good spinners but india is the only team with good pace attack with bowlers like Bumrah and a nice pair of kul-cha for the middle overs and the best part is our all rounder Pandya can now bowl all his 10 overs anyhow for which he was struggling before that's the reason that bowling is not concern anymore and so is the fielding, India has the lowest catch drop percentage in the world cup so far.



Now in the semis India is going against New zealand which has shown some good play so far in the tournament too although they found themselves little stuttering in their last 3 games with but still their excellent bowling performance by Boult and Fergueson & a few match winning knocks by their captain Kane Williamson made sure that they reach the semi final. So the way to tackle them is to
make sure that Williamson and Taylor doesn't remain at the crease for long and it will be easy for India to break their opening stand because none of their opener has performed so far in the league stages but still if their opening partnership goes good then they have a deep batting lineup that can capitalize to that and can put India under pressure easily with a big total.We have to keep on getting 1-2 wickets every 10 overs in order keep the momentum with us and we definitely got good bowlers to do that and as far as batting is concerned we can expect some good knocks from our inform batsmen Rohit and Kohli just like every match we just need to make sure that if we are chasing we need atleast one of them to play till  the 35-40 over otherwise it can put pressure on our middle order batsman and New zealand bowlers are good enough to take advantage of the situation from there.