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 will create 2 pointers : left (starting from 0

Just Smaller Number: Hackerearth Problem and Solution in java

Just Smaller Number: Hackerearth Problem
Statement:

Given an array A of length N and a number K, find the greatest number in the array A that is smaller than K.
Input:
First line contains two space separated integer N,(1N105) and Q,(1Q105), number of elements in the array A, and number of queries.
Second line contains N space separated integers Ai,(1Ai109), elements of the array A.
Next Q lines contains one integer K,(1K109) each.
Output:
For each query, print the number of the greatest number in the array A that smaller than K.
SAMPLE INPUT
 
5 3
3 5 7 2 3
10
7
6
SAMPLE OUTPUT
 
7
5
5
Explanation
The greatest number that is smaller than 10 is 7.
The greatest number that is smaller than 7 is 5.
The greatest number that is smaller than 6 is 5.

SOLUTION IN JAVA:

import java.util.*;


class TestClass {
    public static void main(String args[] ) throws Exception {
       
        Scanner s = new Scanner(System.in);
        int N = s.nextInt();
        int t = s.nextInt();
        int arr[] = new int[N];

        for (int i = 0; i < N; i++) {
           // System.out.println("hello world");
           arr[i]=s.nextInt();
        }
        for(int j=0;j<t;j++){
            int var=s.nextInt();
            int min=arr[0];
             for(int k=0;k<N;k++){
               if(arr[k]<var){
                  int diff = var-arr[k];
                   if(diff<min)
                     min=diff;
                } 
             }
           System.out.println(var-min);
        }

    }

}

Comments

Popular posts from this blog

Ice Cream Parlor : Hackerrank Problem and Solution

Javascript Problem: Find the next perfect square!!

Disemvowel Trolls || Codewars problem and solution in Javascript || Topic : Strings and RegEx