Javatpoint Logo
Javatpoint Logo

Python Program to Find Difference between Two Strings

In this tutorial, we will write a Python program to find the difference between the two given strings. This problem can be asked in the interview. Let's understand the problem statement and then we will approach to the solution.

Problem Statement -

There are two strings given s and t. String t is generated by random shuffling string s and then added one more character at any random position. We need to write a Python program that returns the letter added to t.

Example -

Example -


The following constraints should be followed -

  • 0 <= s.length <= 1000
  • t.length == s.length + 1
  • s and t consist of lowercase English letters.

Python Program

Let's understand the following Python program.

Example -



Explanation -

In the above code, we defined the findThedifference() function that takes two strings as arguments. We used the list comprehension to convert the strings into list. Now, we iterate ls_s list, pick single element and remove that element to the second list ls_t. If all element removed from the second element, it means both given strings are same, otherwise return the first element of the second list.

Solution - 2

Let's see another solution of the problem.



Explanation -

In this tutorial, we used the sorted() method, which converts the string into a list of characters in a sorted manner. We created the two lists of strings and added an extra element as 0 to make the length equal; else, we will get the list index out of bounds. Now we iterated the t_list and checked if the s_list element is not equal to t_list; if the condition is matched, it returns that element.

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA