Solving Leetcode Question 859, Buddy Strings, Using Python

The Prompt

Note: swapping letters is defined as taking two indices (i) and (j), where (i) is not equal to (j), and swapping the elements at those indices.

Here’s an example:

Leetcode #859

The Code

So first off, we should create variables to represent the length of the strings, and for this we can use the Counter() function.

Since there are two inputs, we’ll create two variables. Now, if the lengths aren’t equal, we can return false, since the swapping won’t allow the strings to be equal, as they are different lengths.

The code will look like the following:

Next, we need to count how many positions between the inputs (a) and (b) are different.

If the code hasn’t returned false already, then we know the two inputs have the same length. Now, we need to check if the first elements in each input are the same or not.

The diff variable should be either 2 or 0, and depending on which value it becomes we return True or False. We can handle these cases using an if/elif/else statement. The code will look like the example below:

And that’s it! Run tests and it should give a pass for all the test cases.

Thank you for reading through this short tutorial. I hope it helped, and if it did, show that clap button some love!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store