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:

Leetcode #859

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!




Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Southies Stories: How a musician-turned- programmer built his career on a love of learning

More Than a Brand Name and a Tech Stack

WebGL needs a Home: Flash Bit Rot

How I made this real time clock with Raspberry Pi Pico

Commonly used Linux Commands you should know 2

EmojiDAO is hiring 🔍

5 SAAS Platforms Critical To My E-Commerce Tech Stack

The Red-Blue Simulation on Battleground | TriathonNow!

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
Karan S. Chauhan

Karan S. Chauhan

More from Medium

Finding a duplicate number in an array in Python and C comparison

Implementing a Heap in Python

LeetCode Patterns Adventure 8 — Range Sum Query — Immutable

Leetcode 534 Game Play Analysis III without sum window function