January 10, 2019

Solution to Fibonacci series by Recursion through Dynamic Programming

Context: In mathematics, the Fibonacci numbers are the numbers in the following integer sequence, called the Fibonacci sequence, and characterized by the fact that every number after the first two is the sum of the two preceding ones:
  • 1,1,2,3,5,8,13,21,34,55...
Here, the first two numbers in the Fibonacci sequence are 1 and each subsequent number is the sum of the previous two.
The sequence Fn of Fibonacci numbers is defined by the recurrence relation:
  • Fn = Fn-1 + Fn-2 with Base values F1=1 and F2=1

Problem: Find the Fibonacci number at the given position entered by the user through Recursion.

Conventional Solution

package com.practice.recursion;

import java.util.Scanner;

public class Fibonacci
{
    public static void main(String...s)
    {
Scanner sc= new Scanner(System.in);
System.out.println("Please Enter the number");
int num=sc.nextInt();
int fibonacciNumber=getFibonacci(num);
System.out.println("The Fibonacci Number at Postion "+ num+" is:"+fibonacciNumber);
sc.close();
    }
    public static int getFibonacci(int n)
    {
if(n==1|| n==2)
{
           return 1;
}
return getFibonacci(n-1)+getFibonacci(n-2);
    }
 }

Output:
Please Enter the number
12
The Fibonacci Number at Position 12 is:144

The problem with this solution is that this solution will have serious performance issues for large numbers.

So we will use the technique of Memoization to reduce the time.
What we will do is, we will store each calculated Fibonacci in a storage array and use this value in the calculation of the upcoming calculation of Fibonacci.

Memoization Solution
package com.practice.recursion;

import java.util.Scanner;
public class Fibonacci
{
    public static void main(String...s)
    {
Scanner sc= new Scanner(System.in);
System.out.println("Please Enter the number");
int n=sc.nextInt();
int fibonacciNumber=fibonacciMemo(n,new int[n+1]);
System.out.println("The Fibonacci Number at Postion "+ n+" is:"+fibonacciNumber);
sc.close();
}

        public static int fibonacciMemo(int n, int strg[]) 
      {

if (n == 0 || n == 1) {

return n;
}
if (strg[n] != 0) {
return strg[n];
}
int fnm1 = fibonacciMemo(n - 1,strg);
int fnm2 = fibonacciMemo(n - 2,strg);
int res = fnm1 + fnm2;
strg[n] = res;
return res;
}
}
Please Enter the number
43
The Fibonacci Number at Position 43 is:433494437

PS: Try to notice that I have made a storage array of size equal to n+1.
The reason for that is the zeroth index value will contain the value of 0th Fibonacci and 43rd index value will contain the value of 43rd Fibonacci but to accommodate the 43rd value we should also have an index 43rd. And for the 43rd index, the array should be made of size 44 !!








March 17, 2018

Simple Solution 2 Scenario --(Odd or Even length ) 
Base condition &  Algo recursive(str, i, j)
  1. i==j //even len
  2. if i< j  recurve call (str, i +1,j-1)
  3. else ch[i] ==ch[j] // Extra base condition odd len

public class HelloWorld {

 static boolean ispalindrome(char ch[], int i, int j) {
  if (i == j) return true;
  if (i < j) {
   if (ch[i] != ch[j])
    return false;
   else
    return ispalindrome(ch, i + 1, j - 1);
  }
  if (ch[i] != ch[j])
   return false;
  else
   return true;
 }
 public static void main(String[] args) {
  System.out.println(ispalindrome("jatin".toCharArray(), 0, 4));
  System.out.println(ispalindrome("nitin".toCharArray(), 0, 4));
  System.out.println(ispalindrome("jatinn".toCharArray(), 0, 5));
  System.out.println(ispalindrome("nittin".toCharArray(), 0, 5));
 }
}

March 16, 2018

Josh : playtime with array

Question:Sorted Array have given to you.now a hacker swap odd index value with other odd index value.WAP that serach the element and return it's index in logn complexity.
Example: original sorted  array :{1,2,3,4,5,6,7,8}
              swapped given array:{1,4,3,2,5,8,7,6},key,5(element for searching)
              Output 4(it's index).

March 14, 2018

Print Start Pattern Using Recursion

Output :
X 
X X 
X X X 
X X X X 
---------------------
X X X X 
X X X 
X X 
X 
JAVA Code:
public class HelloWorld {

 static int count = 0;

 public static void print(int i, int j) {

  if (i <= 0 || j < 0 ) return;

  System.out.print("X ");

  print(i, j - 1);

  if (j == 0) {

   count++;

   System.out.println();

   print(i - 1, count);





  }

 }

   public static void print2(int i, int j) {

  if (i <= 0 || j < 0 ) return;

System.out.print("X ");

print2(i, j - 1);





  if (j == 0) {



   System.out.println();

   print2(i - 1, i-2);





  }

}





 public static void main(String[] args) {

  //System.out.println("Hello World2");

  print(4, 0);

  System.out.println("---------------------");



  print2(4, 3);

 }

}

June 15, 2015

Big Data Analytics:Deep Findings

Question
You are given a tree with N nodes. Each node is given an integer value from 0 to N­1 . Tree given as an input will be an array of parent nodes.
You need to find following (all mandatory):
1 . The depth of the tree (Aim for O(N))
2. Maximum number of children for any node in whole tree (Aim for O(N))
3. Nearest Common Ancestor for two given nodes (Aim for O(log(N)))
INPUT FORMAT
First line has the value of N
Second line has list of N values where the number at index ‘i’ is the parent of node ‘i’. The parent of root is
­1 . ( The index has the range [0,N­1 ] )
Third line contains two integers within the range of [0,N­1 ] whose common ancestor you have to find.
OUTPUT FORMAT
First line has the depth of the tree. Second line has the max children.
Third has the nearest common ancestor to two
given nodes n1 and n2.

May 22, 2015

Sorting Tutorial

What is Sorting ? Why Sorting?

Sotring is an algorithms  that arranges the elements of a list in certain order.it can be in ascending , descending or any other fashion.sometimes sorting reduces the problem complexity.we can reduce the search complexity.

Classification  categories of sorting ?

1.Number of Comparision 
2.Number of Swap
3.Memory Usages
4.By Recursion
5.Adaptability

Other ways are :
1.INTERNAL(uses main memory only) 
2.EXTERNAL SORT(uses external memory ).

3. others








Bubble Sort

Bubble Sort is the simplest sorting algorithm. It works by iterating the input from the first to last.Comparing each pair and swapping them if needed. Bubble sort continues until no swapping needed.it got its name  from the way smaller elements "bubble"  to the top of the list.

April 16, 2015

Google code jam :Standing Ovation

Problem
It's opening night at the opera, and your friend is the prima donna (the lead female singer). You will not be in the audience, but you want to make sure she receives a standing ovation -- with every audience member standing up and clapping their hands for her.

April 11, 2015

Sorting : Tournament sort algorithm

Question:Given a team of N players. How many minimum games are required to  find kth best player in O(n+klog(n)) ?

April 3, 2015

JOSH :Diameter of a Binary Tree


Question: WAP that find out longest Diameter of Tree. The diameter of a tree (sometimes called the width) is the number of nodes on the longest path between two leaves in the tree.

April 1, 2015

Vinsol : Defected Meter

Question :A Defected meter is given with missing number 4 from it's rim.WAP that convert the wrong  reading into right one.
Example:
input 100
output 81

March 30, 2015

Google code jam :Alien Language

Question:
After years of study, scientists at Google Labs have discovered an alien language transmitted from a faraway planet. The alien language is very unique in that every word consists of exactly L lowercase letters. Also, there are exactly D words in this language.

March 27, 2015

Google code jam :Minimum Scalar Product

Problem
You are given two vectors v1=(x1,x2,...,xn) and v2=(y1,y2,...,yn). The scalar product of these vectors is a single number, calculated as x1y1+x2y2+...+xnyn.
Suppose you are allowed to permute the coordinates of each vector as you wish. Choose two permutations such that the scalar product of your two new vectors is the smallest possible, and output that minimum scalar product.

March 26, 2015

Google Code jam:Reverse Words in O(nm)


Problem
Given a list of space separated words, reverse the order of the words. Each line of text contains L letters and W words. A line will only consist of letters and space characters. There will be exactly one space character between each pair of consecutive words.

March 25, 2015

Nagarro:GenerateNextDate

Question: Write a function char[] GenerateNextDate(char[]) such that if a date of the format "23Jan201 2" is input, the next date should be produced.

Eg: Input ­ "12-Dec-1987"
Output ­ "13-Dec-1987"
Please remember the input and output are both strings.

March 22, 2015

Google Code jam:StoreCredit

Problem

You receive a credit C at a local store and would like to buy two items. You first walk through the store and create a list L of all available items. From this list you would like to buy two items that add up to the entire value of the credit. The solution you provide will consist of the two integers indicating the positions of the items in your list (smaller number first).

March 21, 2015

JOSH:Question: WAP that sum up all one child parent nodes without globle variable


//Question: WAP that sum up all one child parent nodes without globle variable
//             3
//            / \
//          4    5
//         / \   \
//        6   8    9
//            /
//           7
//output 8+5=13

March 20, 2015

Algorithms:Round Robin scheduling Algorithm

Concept:Round-robin (RR) is one of the algorithms employed by process and network schedulers in computing.As the term is generally used, time slices are assigned to each process in equal portions and in circular order, handling all processes without priority (also known as cyclic executive). Round-robin scheduling is simpleeasy to implement, and starvation-free. Round-robin scheduling can also be applied to other scheduling problems, such as data packet scheduling in computer networks. It is an Operating System concept.

Pseudo Code : 
* CPU scheduler picks the process from the circular/ready queue , set a timer to interrupt it after 1 time slice    / quantum  and dispatches it .
*  If  process has burst time less than 1 time slice/quantum             
             >  Process will leave the CPU after the completion
             >  CPU will proceed with the next process in the ready queue / circular queue .
    else If process has burst time longer than 1 time slice/quantum
             >  Timer will be stopped . It cause interruption to the OS .
             >   Executed process is then placed at the tail of the circular / ready  querue by applying  the context                   switch
             >  CPU scheduler then proceeds by selecting the next process in the ready queue .        
Here , User can calculate the average turnaround time and average waiting time along with the starting and finishing time of each process


Turnaround time   :   Its the total time taken by the process between starting and the completion.(Completion Time-Arrival Time).

Waiting time         :   Its the time for which process is ready to run but not executed by CPU scheduler(Turnaround time-Burst time )
for example ,
we have three processes arrives at  0 ms.
     
                          Burst time             Waiting time         Turnaround time


P1                          20                          7                          (27-0)27

P2                          3                             4                            7

P3                          4                              7                           11

So here we can see the turnaround time for the process 1 is 30 while 7 and 10 for 2nd and 3rd process
 A Gantt chart is a chart which shows the start and finish times of  all the processes .use time Quantum 4ms.
  Gantt chart for the round robin algorithm with  is

  |--------|-------|-----|------|------|------|-----|
  |   P1    |    P2  | P3  |  P1  | P1  |  P1  | P1  |
  |--------|-------|-----|------|------|------|-----|
 0         4        7     11    15     19     23    27
The major features of the Round Robin algorithm is that

* Throughput is low as the large process is holding up the Central processing unit for execution .
* The main advantage of Round robin is to remove starvation  . As long as all processes completes the execution then we  dont have any trouble, But the problem starts when any of the process fails to complete . The incomplete   execution of any process leads to starvation .
* Queuing is done without using any prioritization of the processes.




AMCAT: INACTIVE AND ACTIVE Puzzle solution in C

Question :There are 8 peoples which are standing in a row. They can have two states on a  respective day: Inactive(0) or Active(1). We were given an array of 8 elements which shows the states of these people today and we have to calculate the state of these people after the given no. of days.
Assumption 1: State of person will be Inactive on the next day if both the adjacent persons are having the Active state or Inactive state today.
Assumption 2: State of person will be Active on the next day if one adjacent person is having Active state and other adjacent person is having Inactive state or vice versa.
Assumption 3: Person on the extreme left and extreme right have only one adjacent person, so we can imagine, the other adjacent person is Inactive.
Ex- 1
Input 1: [0,1,1,0,0,1,0,1], 1
Output 1: [1,1,1,1,1,0,0,0]
Ex-2
Input 2: [0,1,0,1,1,0,1,1], 2
Output 2: [0,1,1,1,1,0,1,1]

 /* After day 1, states will be like this [1,0,0,1,1,0,1,1]