Solving Leetcode Question 859, Buddy Strings, Using Python

The Prompt

Given two input strings, (a) and (b), return (true) if two letters in (a) can be swapped so that the result is equal to (b), otherwise return (false).

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:

The Code

We’re given the following template to start with.

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!