You are given a read only array of n integers from 1 to n.
Each integer appears exactly once except A which appears twice and B which is missing.
Return A and B.
Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Note that in your output A should precede B.
Example:
Input:[3 1 2 5 3]
Output:[3, 4]
A = 3, B = 4
my code :
import functools
class Solution:
def repeatedNumber(self, A):
s=functools.reduce(lambda x,y:x+y,A,0) #to find the sum of given elements of tuple
r=functools.reduce(lambda x,y: x+y,set(A),0)# to find the sum of given elements after removing the repeated element ,set is used for the purpose
return [s-r,((len(A)*(len(A)+1))//2)-r]here A is a tuple .
though i solved the question but i am feeling confident about the correctness of the ans .
what is space complexity?
set(A) doesn't allocate space?
what could be other approach ?
edit:
another O(n) time and O(1) space using xor.
class Solution:
def repeatedNumber(self, A):
xor=0
x=0
y=0
for index in range(len(A)):
xor=xor^A[index]^(index+1)
set_bit_val=xor& ~(xor-1)
for index in range(len(A)):
if(A[index]&set_bit_val):
x=x^A[index]
else:
y=y^A[index]
if(index+1 & set_bit_val):
x=x^(index+1)
else:
y=y^(index+1)
return [x,y] if x in A else [y,x]