- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to check whether one string swap can make strings equal or not using Python
Suppose we have two strings s and t of same length. Consider an operation where we choose two indices in a string (not necessarily different) and swap the characters at the selected indices. We have to check whether it is possible to make both strings same by performing at most one string swap on exactly one of the strings or not.
So, if the input is like s = "hello" t = "hlelo", then the output will be True because we need to swap 'e' and 'l' at either s or t to make them equal.
To solve this, we will follow these steps −
st := a new set
st2 := a new set
for i in range 0 to size of s, do
if s[i] is not same as t[i], then
diffs := diffs + 1
if s[i] not present in st, then
insert s[i] into st
if t[i] not present in st2, then
insert t[i] into st2
if diffs > max_diffs, then
return true if (diffs is same as 0 or diffs is same as 2) and size of st is same as size of st2 and st is same as st2, otherwise false
Let us see the following implementation to get better understanding −
def solve(s, t): max_diffs=2 diffs=0 st = set() st2 = set() for i in range(len(s)): if s[i] != t[i]: diffs+=1 if s[i] not in st: st.add(s[i]) if t[i] not in st2: st2.add(t[i]) if diffs > max_diffs: return False return (diffs == 0 or diffs == 2) and len(st) == len(st2) and st == st2 s = "hello" t = "hlelo" print(solve(s, t))
- Program to check whether final string can be formed using other two strings or not in Python
- Program to check whether we can make group of two partitions with equal sum or not in Python?
- Program to check whether we can make k palindromes from given string characters or not in Python?
- Program to check whether we can convert string in K moves or not using Python
- Program to check two strings can be equal by swapping characters or not in Python
- Program to check whether one point can be converted to another or not in Python
- Python Program to Check Whether a String is a Palindrome or not Using Recursion
- Python program to check whether we can pile up cubes or not
- Python program to check whether a given string is Heterogram or not
- C++ program to check we can make two strings equal by swapping from third string
- How to Check Whether a String is Palindrome or Not using Python?
- Java Program to check whether two Strings are an anagram or not.
- Program to check whether one value is present in BST or not in Python
- Program to check whether one tree is subtree of other or not in Python
- Program to check whether the sentence is pangram or not using Python