Posts

Showing posts from 2019

Dutch national flag problem in Javascript

Image
Dutch national flag problem and solution in Javascript Problem statement:   The Dutch national flag (DNF) problem is one of the most popular programming problems proposed by Edsger Dijkstra. The flag of the Netherlands consists of three colors: white, red, and blue. The task is to randomly arrange balls of white, red, and blue such that balls of the same color are placed together. Now, let's consider an array with 3 distinct values say 0, 1 and 2. We won't be using any sort method and we need to sort this array in 0(n). Input Array :  let   arr  = [ 0 ,  2 ,  1 ,  0 ,  1 ,  2 ,  0 ,  2 ]; Expected Output: [ 0, 0, 0, 1, 1, 2, 2, 2 ] Solution Approach : When we see expected output, we can clearly see that sorted array is divided into 3 sections having values 0 , 1 and 2. So, let's divide the array in 3 sections: a) from 0th index to left boundary b) from left boundary to right boundary c) from right boundary to last index. Now we...

HackerRank Problem: Halloween Sale !!!!

HackerRank Problem: Halloween Sale !!!! Problem:          You wish to buy video games from the famous online video game store Mist.  Usually, all games are sold at the same price,     dollars. However, they are planning to have the seasonal Halloween Sale next month in which you can buy games at a cheaper price. Specifically, the first game you buy during the sale will be sold at   dollars, but every subsequent game you buy will be sold at exactly     dollars less than the cost of the previous one you bought. This will continue until the cost becomes less than or equal to     dollars, after which every game you buy will cost     dollars each.  For example, if   ,     and   , then the following are the costs of the first     games you buy, in order:  You have     dollars in your Mist wallet. How many games can you buy during the Halloween Sale? Input ...