Friday, November 24, 2017

Installing Python

Well we talked much about Python. now and next logical steps is installing python.
So installing Python involves a download from pyhton website"https://www.python.org/downloads/" and as of now latest version is Python 3.6.3 released in 2017-10-03.

Once the download finished .open the setup file and remember you will see a check box at the very bottom and written like "Add Python 3.6.3 to PATH".just check it and then click on install now.
Once it is done then let's verify that Python is installed on the system or not.

using the CMD or PowerShell whicherver you prefer.

1) Search for Windows PowerShell or CMD.

2)Then type Python  --version 
if you get the message like below

Python 3.6.3

then your installation was successful.
If not then try to repeat the steps. it usually helps.

You can install Python on Windows,Mac and Linux.steps are same for Mac and windows but usually on Linux pyhton comes along. I mean it is bundled with the Linux os but one thing  can be different that it comes with Python version 2 but you can install separate Python version 3 on the Linux system.

Standard procedure for installing is same and also you can verify the Python version repeating the same steps.

For Mac OS there is another way also to install python using "www.brew.sh".
just search it on Google and I am sure you will get the link and using it you can easily install python 3 on Mac OS.
now you must be thinking of it's advantages.what it's worth So it has some certain advantages during my teaching I will always be referring to be python  terminal command.

Alright our pyhton is all setup.

Python 2 vs. Python 3

Python 2 vs. Python 3:

Actually if you know anything about Python then you must be thinking of which version of Python I should use.the iternal debate.
online forums are full of speeches that you should use python 2 because of this and you should use python 3  because of that but in reality just use python 3.
Actually, pyhton 3 is facing adoption problem.it doesn't go smoothly as it should go thats why people  using Python 2 still comes bundled on many default systems.however Python 2 is going to end his life in 2020.

Python 2  vs.Pyhton 3:

Python 2 :

1)Maintained, but no new features
2)End of Life(EOL) in 2020;
3)Still default on many systems.
print " Hello World"

Python 3 :

1)New fetaures being added.
2)Unicode support by default.
3)Cleared some Pyhton 2 confusion
print("Hello World")

Minor differences from Python 2

Pyhton released in December 2008 but still facing adoption problems.There are not differences between Pyhtonh 2 and Pyhtonh 3 as far as Sytaxes are concerned.as a developer you must have noticed that in Python 2 printing hello world is different and in Python 3 is different.if tell you in more detail in Python 3 ,it is a funtion but as you can see in python 2 it is simple print and double quotes .                    

Thursday, November 23, 2017

Getting Started with Python

So Guys I am going to teach you about Python .as it is very powerful language.With Python you can build web app,desktop app,do scientific computation, creates scripts,artificial intelligence etc.
To learn Python you don't need any prior Python experience I will teach you first basics and then probably will go for live applications and advance concepts.

So now I am going to tell you first that what are the things required to write Python programs.i am going to cover the following contents.

1)Installing Python
2)Learning the Syntax
3)Developing a console app
4) creating executable files

So there are many tools and libraries,Frameworks  are available for Python such as

1)DJANGO
  for web developemnt
2)TENSORFLOW
for Artificial Intelligence
3)SCIPY
for scientific computations
4)PYQT
for cross-platform applications desktop applications.

I am also going to tell about basics of Python such as data types,functions,classes So by learning all these you can easily write programs in Python and later on we also create console applications.Python is very simple ,powerful and cross-platform language.

Why I am saying Python is so amazing .

let's have a look.using Python you can easily do automation work by writing scripts, Scientific calculation,can write cross-platform desktop applications,Android Development,Web backend adminstrative controls ,Machine Learning .

Use of Python:

1)cross platform desktop applications.
2)Website development using DJANGO and Flask frameworks.
3)Can work with sensors such as you can do home automation using Humidity sensors.

Let me show the simplicity of Python:

//java

public class HelloWorld
{
  public static void main (String args[])
  {
    System.out.println("Hello World");
  }
}

//Pyhton 3

print("Hello World")

So you can see I have to write lot just to write simple hello world program but in Python it's not.Actually python uses indentation yes pyhton uses tabs and spaces instead of curly braces.Pyhton follows PEPS.its a coding guidelines for Python.Now PEP 8 is there it usually integrated in your editor So don't worry.As of now I am not going in much details.

Continue..................

Friday, November 17, 2017

Backtracking | The Knight’s tour problem


So what is "The Knight's tour problem"?


A knight's tour is a sequence of moves of a knight on a chessboard such that the knight visits every square only once. If the knight ends on a square that is one knight's move from the beginning square (so that it could tour the board again immediately, following the same path), the tour is closed, otherwise it is open.

The knight's tour problem is the mathematical problem of finding a knight's tour. Creating a program to find a knight's tour is a common problem given to computer science students. Variations of the knight's tour problem involve chessboards of different sizes than the usual 8 × 8, as well as irregular (non-rectangular) boards.

The knight's tour problem is an instance of the more general Hamiltonian path problem in graph theory. The problem of finding a closed knight's tour is similarly an instance of the Hamiltonian cycle problem. Unlike the general Hamiltonian path problem, the knight's tour problem can be solved in linear time.

So,Backtracking is an algorithmic paradigm that tries different solutions until finds a solution that “works”. Problems which are typically solved using backtracking technique have following property in common. These problems can only be solved by trying every possible configuration and each configuration is tried only once. A Naive solution for these problems is to try all configurations and output a configuration that follows given problem constraints. Backtracking works in incremental way and is an optimization over the Naive solution where all possible configurations are generated and tried.


Naive Algorithm for Knight’s tour

The Naive Algorithm is to generate all tours one by one and check if the generated tour satisfies the constraints.

while there are untried tours
{
   generate the next tour
   if this tour covers all squares
   {
      print this path;
   }
}


Now,Backtracking works in an incremental way to attack problems. Typically, we start from an empty solution vector and one by one add items (Meaning of item varies from problem to problem. In context of Knight’s tour problem, an item is a Knight’s move). When we add an item, we check if adding the current item violates the problem constraint, if it does then we remove the item and try other alternatives. If none of the alternatives work out then we go to previous stage and remove the item added in the previous stage. If we reach the initial stage back then we say that no solution exists. If adding an item doesn’t violate constraints then we recursively add items one by one. If the solution vector becomes complete then we print the solution.

Backtracking Algorithm for Knight’s tour

Following is the Backtracking algorithm for Knight’s tour problem.

If all squares are visited
    print the solution
Else
   a) Add one of the next moves to solution vector and recursively
   check if this move leads to a solution. (A Knight can make maximum
   eight moves. We choose one of the 8 moves in this step).
   b) If the move chosen in the above step doesn't lead to a solution
   then remove this move from the solution vector and try other
   alternative moves.
   c) If none of the alternatives work then return false (Returning false
   will remove the previously added item in recursion and if false is
   returned by the initial call of recursion then "no solution exists" )
 
   Following are implementations for Knight’s tour problem. It prints one of the possible solutions in     2D matrix form. Basically, the output is a 2D 8*8 matrix with numbers from 0 to 63 and these   numbers show steps made by Knight.
   
Sample program:
 
 
class KnightTourTest
{
static int N = 8;
static boolean isSafe(int x, int y, int sol[][])
{
return (x >= 0 && x < N && y >= 0 &&
y < N && sol[x][y] == -1);
}

static void printSolution(int sol[][])
{
for (int x = 0; x < N; x++)
{
for (int y = 0; y < N; y++)
System.out.print(sol[x][y] + " ");
System.out.println();
}
}
static boolean solveKT()
{
int sol[][] = new int[8][8];

for (int x = 0; x < N; x++)
for (int y = 0; y < N; y++)
sol[x][y] = -1;

int xMove[] = {2, 1, -1, -2, -2, -1, 1, 2};
int yMove[] = {1, 2, 2, 1, -1, -2, -2, -1};

sol[0][0] = 0;

if (!solveKTUtil(0, 0, 1, sol, xMove, yMove))
{
System.out.println("Solution does not exist");
return false;
}
else
printSolution(sol);

return true;
}

/* A recursive utility function to solve Knight
Tour problem */
static boolean solveKTUtil(int x, int y, int movei,
int sol[][], int xMove[],
int yMove[]) {
int k, next_x, next_y;
if (movei == N * N)
return true;

/* Try all next moves from the current coordinate
x, y */
for (k = 0; k < 8; k++) {
next_x = x + xMove[k];
next_y = y + yMove[k];
if (isSafe(next_x, next_y, sol)) {
sol[next_x][next_y] = movei;
if (solveKTUtil(next_x, next_y, movei + 1,
sol, xMove, yMove))
return true;
else
sol[next_x][next_y] = -1;// backtracking
}
}

return false;
}

public static void main(String args[]) {
solveKT();
}
}

Output:

0 59 38 33 30 17 8 63
37 34 31 60 9 62 29 16
58 1 36 39 32 27 18 7
35 48 41 26 61 10 15 28
42 57 2 49 40 23 6 19
47 50 45 54 25 20 11 14
56 43 52 3 22 13 24 5
51 46 55 44 53 4 21 12

Note that Backtracking is not the best solution for the Knight’s tour problem. 


  

Backtracking question asked in Samsung and Amazon - Write a program to print all permutations of a given string.

Backtracking question asked in Samsung and Amazon - Write a program to print all permutations of a given string.

A permutation, also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation.

Below are the permutations of string ABC.

ABC ACB BAC BCA CBA CAB

Solution based on backtacking:



Sample Program:


public class PermutationTest
{
public static void main(String[] args)
{
String str = "ABC";
int n = str.length();
PermutationTest permutation = new PermutationTest();
permutation.permute(str, 0, n-1);
}
private void permute(String str, int l, int r)
{
if (l == r)
System.out.println(str);
else
{
for (int i = l; i <= r; i++)
{
str = swap(str,l,i);
permute(str, l+1, r);
str = swap(str,l,i);
}
}
}

public String swap(String a, int i, int j)
{
char temp;
char[] charArray = a.toCharArray();
temp = charArray[i] ;
charArray[i] = charArray[j];
charArray[j] = temp;
return String.valueOf(charArray);
}

}

Output:

ABC
ACB
BAC
BCA
CBA
CAB


Time Complexity: O(n*n!) Note that there are n! permutations and it requires O(n) time to print a a permutation.

Note : The above solution prints duplicate permutations if there are repeating characters in input string.



Thursday, November 16, 2017

Dynamic Programming | Matrix Chain Multiplication

Given a sequence of matrices, find the most efficient way to multiply these matrices together. The problem is not actually to perform the multiplications, but merely to decide in which order to perform the multiplications.

We have many options to multiply a chain of matrices because matrix multiplication is associative. In other words, no matter how we parenthesize the product, the result will be the same.

For example, if we had four matrices A, B, C, and D, we would have:

 (ABC)D = (AB)(CD) = A(BCD) = ....

 However, the order in which we parenthesize the product affects the number of simple   arithmetic operations needed to compute the product, or the efficiency.

 For example, suppose A is a 10 × 30 matrix, B is a 30 × 5 matrix, and C is a 5 × 60 matrix. Then,

 However, the order in which we parenthesize the product affects the number of simple arithmetic operations needed to compute the product, or the efficiency.

 For example, suppose A is a 10 × 30 matrix, B is a 30 × 5 matrix, and C is a 5 × 60 matrix. Then,

    (AB)C = (10×30×5) + (10×5×60) = 1500 + 3000 = 4500 operations
    A(BC) = (30×5×60) + (10×30×60) = 9000 + 18000 = 27000 operations.
   
   
 Clearly the first parenthesization requires less number of operations.

Given an array p[] which represents the chain of matrices such that the ith matrix Ai is of dimension p[i-1] x p[i]. We need to write a function MatrixChainOrder() that should return the minimum number of multiplications needed to multiply the chain.

  Input: p[] = {40, 20, 30, 10, 30}  
  Output: 26000
 
  There are 4 matrices of dimensions 40x20, 20x30, 30x10 and 10x30.
  Let the input 4 matrices be A, B, C and D.  The minimum number of
  multiplications are obtained by putting parenthesis in following way
  (A(BC))D --> 20*30*10 + 40*20*10 + 40*10*30

  Input: p[] = {10, 20, 30, 40, 30}
  Output: 30000
 
  There are 4 matrices of dimensions 10x20, 20x30, 30x40 and 40x30.
  Let the input 4 matrices be A, B, C and D.  The minimum number of
  multiplications are obtained by putting parenthesis in following way
  ((AB)C)D --> 10*20*30 + 10*30*40 + 10*40*30

  Input: p[] = {10, 20, 30}
  Output: 6000
 
  There are only two matrices of dimensions 10x20 and 20x30. So there
  is only one way to multiply the matrices, cost of which is 10*20*30
 
  So now see it how?
  
  1) Optimal Substructure:
 
A simple solution is to place parenthesis at all possible places, calculate the cost for each placement and return the minimum value. In a chain of matrices of size n, we can place the first set of parenthesis in n-1 ways. For example, if the given chain is of 4 matrices. let the chain be ABCD, then there are 3 ways to place first set of parenthesis outer side: (A)(BCD), (AB)(CD) and (ABC)(D). So when we place a set of parenthesis, we divide the problem into subproblems of smaller size. Therefore, the problem has optimal substructure property and can be easily solved using recursion.

Minimum number of multiplication needed to multiply a chain of size n = Minimum of all n-1 placements (these placements create subproblems of smaller size)

2) Overlapping Subproblems:

Following is a recursive implementation that simply follows the above optimal substructure property.

Sample Program:

class MatrixChainMultiplicationTest
{

static int MatrixChainOrder(int p[], int i, int j)
{
if (i == j)
return 0;

int min = Integer.MAX_VALUE;

for (int k=i; k<j; k++)
{
int count = MatrixChainOrder(p, i, k) +
MatrixChainOrder(p, k+1, j) +
p[i-1]*p[k]*p[j];

if (count < min)
min = count;
}

return min;
}

public static void main(String args[])
{
int arr[] = new int[] {1, 2, 3, 4, 3};
int n = arr.length;

System.out.println("Minimum number of multiplications is "+
MatrixChainOrder(arr, 1, n-1));

}
}

Output:

Minimum number of multiplications is 30

Time complexity of the above naive recursive approach is exponential.
It should be noted that the above function computes the same subproblems again and again.





Wednesday, November 15, 2017

Top Common Mistakes Done by Android Developer

Top Common Mistakes Done by Android Developer

Android. What’s not to like about this platform? It’s free, it’s customizable, it’s rapidly growing and it’s available not just on your phone or tablet, but on your smartwatch, TV and car too.

With the latest Oreo update, Android programming continues to improve. The platform has matured quite a bit since the initial AOSP release, and set the user expectations bar quite high.

There are thousands of different devices, with different screen sizes, chip architectures, hardware configurations, and software versions. Unfortunately, segmentation is the price to pay for openness, and there are thousands of ways your app can fail on different devices, even as an advanced Android programmer.

Regardless of such huge segmentation, the majority of bugs are actually introduced because of logic errors. These bugs are easily prevented, as long as we get the basics right!.

I am gone tell all those mistakes which you can avoid while development.

1) Developing for Your Android Device:

Unless you are building a kiosk/promo app for a single tablet, chances are your Android app won’t look good on every device. Here are a few Android programming tips to remember:

Density-independent pixels (dp) are different than normal pixels (px).
Resources are included multiple times to account for different densities and orientations.
9-patch drawables are stretched to fit the screen.
There are literally thousands of possible scenarios, but after a while you develop a sense for covering them all with a handful of cases.

You don’t own thousands of devices? Not a problem. The Android Emulator is super good in replicating physical devices. Even better, try out Genymotion, it’s lightning fast and comes with a lot of different popular preset devices.

Also, have you tried rotating your device? All hell can break loose…

2)Not Using Intents:

Intents are one of Android’s key components. It’s a way of passing data between different parts of the app or, even better, different apps on the system.

Let’s say you have a gallery app that can share a download link to some images via SMS. Which of the two options seems more logical?

Option 1:

Request the SEND_SMS permission.

  <uses-permission android:name="android.permission.SEND_SMS" />
 
Write your own code for sending SMS using the SmsManager.
Explain to your users why your gallery app needs access to services that can cost money, and why they have to grant this permission to use your app.

Option 2:

Start an SMS Intent and let an app designed for SMS do the work

  Intent sendIntent = new Intent(Intent.ACTION_VIEW);
  sendIntent.setData(Uri.parse("sms:" + telephoneNumber));
  sendIntent.putExtra("sms_body", x);
  startActivity(sendIntent);
 
In case that you have any doubts, best solution is option 2!

This approach can be applied to almost anything. Sharing content, taking pictures, recording video, picking contacts, adding events, opening links with native apps, etc.

Unless there is a good reason to make a custom implementation (ex., a camera that applies filters), always use Intents for these scenarios. It will save you a lot of programming time, and strip the AndroidManifest.xml of unnecessary permissions.

3)Not Using Fragments:

A while ago in Honeycomb, Android introduced the concept of fragments. Think of them as separate building blocks with their own (rather complex) life cycles that exist inside an Activity. They help a lot with optimizing for various screens, they are easily managed by their parent activity, can be reused, combined and positioned at will.

Launching a separate activity for each app screen is terribly inefficient, since the system will try to keep them in memory as long as it can. Killing one won’t free the resources used by the others.

Unless you want to dig deep into the Android core and read this article, advocating against fragment usage, you should use fragments whenever possible. It basically says that fragments and cursor loaders have good intended purpose, but poor implementation.

4)Blocking the Main Thread:

The main thread has a single purpose: keeping the user interface responsive.

Although the science behind measuring the frame rate our eyes/brain can perceive is complex and influenced by a lot of factors, a general rule is that anything below 24 fps with delay greater than 100 ms won’t be perceived as smooth.

This means that the user’s actions will have a delayed feedback, and the Android app you have programmed will stop responding. Stripping the user of his control over the app leads to frustration.

Even worse, if the main thread is blocked for a while (5 seconds for Activities, 10 for Broadcast Receivers), ANR will happen.

This was so common in Android 2.x, that on newer versions the system won’t let you make network calls in the main thread.

To avoid blocking the main thread, always use worker/background threads for:
1. network calls
2. bitmap loading
3. image processing
4. database querying
5. SD reading / writing

5)Reinventing the Wheel:

“OK, I won’t use the main thread. I’ll write my own code that communicates with my server in a background thread.”

No! Please don’t do that! Network calls, image loading, database access, JSON\xml\SOAP parsing, and social login are the most common things you do in your app. Not just yours, every app out there. There is a better way. Remember how Android has matured and grown as a platform? Here’s a quick list of examples:

Use gradle as a build system.
Use Retrofit / Volley for network calls.
Use Picasso for image loading.
Use Gson / Jackson for JSON parsing.
Use common implementations for social login.
If you need something implemented, chances are it’s already written, tested and used widely. Do some basic research and read some Android programming tutorials before writing your own code!.

6)Not Understanding Bitmaps:

Users love content! Especially when the content is well formatted and looks nice. Images, for instance, are extremely nice content, mainly due to their property of conveying a thousand words per image. They also consume a lot of memory. A lot of memory!

Before an image is displayed on the screen, it has to be loaded into the memory. Since bitmaps are the most common way to do this, we’re going to provide an Android programming guide for the whole process:

Let’s say you want to display an image on your screen that you just took with your camera. The total memory needed for this is calculated with the following formula: memory_needed_in_bytes = 4 * image_width * image_height;

Why 4? Well, the most common / recommended bitmap configuration is ARGB_8888. That means that for each pixel we draw, we need to keep 8 bits (1 byte) for the alpha, the red, the greed and the blue channel in memory, in order to properly display it. There are alternatives, like the RGB_565 configuration that requires half the memory than ARGB_8888, but loses the transparency and the color precision (while maybe adding a green tint).

Let’s assume you have a brand new device with full HD screen and 12 MP camera. The picture you just took is 4000x3000 pixels large and the total memory needed to display it is: 4 bytes * 4000 * 3000 = 48 MB

48 megabytes of your RAM just for a single image!? That’s a lot!

Now let’s take the screen resolution into consideration. You are trying to show a 4000x3000 image on a screen that has 1920x1080 pixels, in worst case scenario (displaying the image full screen) you shouldn’t allocate more than 4 * 1920 * 1080 = 8.3 MB of memory.

Always follow the Android programming tips for displaying bitmaps efficiently:

Measure the view you’re showing your images in.
Scale / crop the large image accordingly.
Show only what can be displayed.

7)Using Deep View Hierarchy:

Layouts have an XML presentation in Android. In order to draw content, the XML needs to be parsed, the screen needs to be measured, and all the elements need to be placed accordingly. It’s a resource- and time-consuming process that needs to be optimized.

This is how the ListView (and more recently the RecyclerView) works.

If a layout has been inflated once, the system reuses it. But still, inflating the layout must happen at some point.

Let’s say you want to make a 3x3 grid with images. One way of doing this is a vertical LinearLayout containing 3 LinearLayouts with equal weight, each of them containing 3 ImageViews with equal weight.

What do we get with this approach? A warning that “nested weights are bad for performance”.

There is a saying in the Android programming world, that I just made up: “With little effort all hierarchy can be flattened”.

In this case RelativeLayout or GridLayout will efficiently replace the nested LinearLayouts.

8) Not Setting the minSdkVersion to 14:

Well, this is not a mistake, but it is bad practice.

Android 2.x was a huge milestone in developing this platform, but some things should be left behind. Supporting older devices adds more complexity for code maintenance and limits the development process.

The numbers are clear, the users have moved on, the developers shouldn’t stay behind.

I’m aware that this doesn’t apply for some big markets with old devices (ex. India), and setting the minSdkVersion to 14, on the Facebook App, means leaving couple of million users without their favorite social network. But, if you are starting fresh and trying to create a beautiful experience for your users, do consider eliminating the past. Users that don’t have the resources, or feel the need to upgrade their device/OS, won’t have the incentive to try out a superior version of your Android app and ultimately spend money on it.

9) Developing App in MVC Architecture:

i have seen thousands of time that client is shouting that write unit test cases for my business logic and let me know the coverrage of it.then if your app is in MVC  then you can never say that you can write 100% unit test cases because of tight coupling between the business logic and controller and vice-versa.So instead of MVC use MVP because of its simplicity,abstractness,code maintainability,separate business logic presenter class etc.i can write 1000 of advantages over MVC which actually helps in long term project.

10) Not Giving Importance to User Experience:

Apps are made for users. so, user experience is the key factor that determines the success or failure of an app. There are several seminars, annual events and conferences help over this common topic. However, add developers often fail to place enough emphasis on this crucial factor and intuitive design.

Before finalizing an app, run usability or user acceptance testing (UAT) several times to check how it works on the mobile platform. Such testing can give you better understanding of user experience and persona, and even how people would like to interact with the app. To ensure this process works smooth and fine, wireframe the entire designing process.

11) Inefficient Resources Management in Android App Development:

Android application resources such as images, icons, layouts, text strings, etc. are vital for app performance. Due to responsive designing needs, these resources need more than one alternatives to fit in any device from tiny to large handhelds.

Therefore, an advanced architecture for resources management is essential, and we can do it by externalizing the application resources from the code. We can maintain such resources independently by creating directories and sub-directories in res/directory of your Android project.

Besides primary resources, you should place alternative resources for specific device configurations. You can group it all specifically named resources directories and sub-directories so that Android can use the appropriate resource in runtime based in its current configuration.







Tuesday, November 14, 2017

Dynamic Programming - Edit Distance


Question : Given two strings str1 and str2 and below operations that can performed on str1. Find minimum number of edits (operations) required to convert ‘str1’ into ‘str2’.

Example: 

Input:   str1 = "geek", str2 = "gesek"
Output:  1
We can convert str1 into str2 by inserting a 's'.

Input:   str1 = "cat", str2 = "cut"
Output:  1
We can convert str1 into str2 by replacing 'a' with 'u'.

Input:   str1 = "sunday", str2 = "saturday"
Output:  3
Last three and first characters are same.  We basically
need to convert "un" to "atur".  This can be done using
below three operations.
Replace 'n' with 'r', insert t, insert a


So there can be many many solution for this problem but giving you the best solution:

The idea is process all characters one by one staring from either from left or right sides of both strings.

Let we traverse from right corner, there are two possibilities for every pair of character being traversed.

m: Length of str1 (first string)
n: Length of str2 (second string)

If last characters of two strings are same, nothing much to do. Ignore last characters and get count for remaining strings. So we recur for lengths m-1 and n-1.

Else (If last characters are not same), we consider all operations on ‘str1’, consider all three operations on last character of first string, recursively compute minimum cost for all three operations and take minimum of three values.

Insert: Recur for m and n-1
Remove: Recur for m-1 and n
Replace: Recur for m-1 and n-1

Sample Program:

class EDISTTest
{
static int min(int x,int y,int z)
{
if (x<=y && x<=z) return x;
if (y<=x && y<=z) return y;
else return z;
}

static int editDist(String str1 , String str2 , int m ,int n)
{
if (m == 0) return n;

if (n == 0) return m;

if (str1.charAt(m-1) == str2.charAt(n-1))
return editDist(str1, str2, m-1, n-1);

return 1 + min ( editDist(str1, str2, m, n-1), // Insert
editDist(str1, str2, m-1, n), // Remove
editDist(str1, str2, m-1, n-1) // Replace
);
}

public static void main(String args[])
{
String str1 = "sunday";
String str2 = "saturday";

System.out.println( editDist( str1 , str2 , str1.length(), str2.length()) );
}
}

Output: 3

Time complexity:

The time complexity of above solution is exponential.
In worst case, we may end up doing O(3m) operations. The worst case happens when none of characters of two strings match.