Task
Two arrays are called similar if one can be obtained from another by swapping at most one pair of elements in one of the arrays.
Given two arrays a and b, check whether they are similar.
Example
-
For
a = [1, 2, 3]andb = [1, 2, 3], the output should be
areSimilar(a, b) = true.
The arrays are equal, no need to swap any elements. -
For
a = [1, 2, 3]andb = [2, 1, 3], the output should be
areSimilar(a, b) = true.
We can obtainbfromaby swapping2and1inb.
Fora = [1, 2, 2]andb = [2, 1, 1], the output should be
areSimilar(a, b) = false.
Any swap of any two elements either inaor inbwon’t makeaandbequal.
Input/Output
-
[execution time limit]
4 seconds (py3) -
[input] array.integer a
Array of integers.
Guaranteed constraints:3 ≤ a.length ≤ 105,1 ≤ a[i] ≤ 1000. -
[input] array.integer b
Array of integers of the same length asa.
Guaranteed constraints:b.length = a.length,1 ≤ b[i] ≤ 1000. -
[output] boolean
trueifaandbare similar,falseotherwise.
My Solution
def areSimilar(a, b):
i = 0
fstIndx = -1
sndIndx = -1
while i < len(a):
if a[i] != b[i]:
fstIndx = i
i += 1
break
i += 1
while i < len(a):
if a[i] != b[i]:
sndIndx = i
i += 1
break
i += 1
while i < len(a):
if a[i] != b[i]:
return False
i += 1
if (fstIndx < 0 or sndIndx < 0):
return True
return (a[fstIndx] == b[sndIndx] and a[sndIndx] == b[fstIndx])