Coding
How would you ascertain if two strings could be identical after zero or one character swaps?
Data ScientistMachine Learning Engineer
Shopify
TikTok
FactSet
NerdWallet
GitHub
Answers
Anonymous
6 months ago
def can_be_equal_with_one_swap(s1, s2):
# Step 1: Check if lengths are the same
if len(s1) != len(s2):
return False
# Step 2: If strings are already identical
if s1 == s2:
return True
# Step 3: Find mismatching positions
mismatches = []
for i in range(len(s1)):
if s1[i] != s2[i]:
mismatches.append(i)
# Step 4: Check the mismatch condition
if len(mismatches) == 2:
i, j = mismatches
# Check if swapping the mismatched characters makes the strings identical
return s1[i] == s2[j] and s1[j] == s2[i]
# If there are not exactly two mismatches, return False
return False
Try Our AI Interviewer
Prepare for success with realistic, role-specific interview simulations.
Try AI Interview NowInterview question asked to Machine Learning Engineers and Data Scientists interviewing at ServiceNow, Nubank, Quantcast and others: How would you ascertain if two strings could be identical after zero or one character swaps?.