Problem Statement:
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.
Example
Input:[3 1 2 5 3] Output:[3, 4] A = 3, B = 4
I wrote the following code:
def repeated_number(number_array):
pair_A_B = []
n = len(number_array)
for i in number_array:
if(number_array.count(i)==2):
pair_A_B.append(i)
break
sample = range(1,n+1)
diff = list(set(sample)-set(number_array))
pair_A_B.append(diff[0])
return pair_A_B
sample_input = [3,1,2,3,5]
print(repeated_number(sample_input))
The code works fine for this problem on my laptop but when I try to submit it on a coding forum it says my code is not efficient. How can I make it efficient in terms of time?
number_array
. Initialize the elements to false with a list comprehension. Now, iterate throughnumber_array
. For each number found, check the value in the bool list at that index - 1. If it's true, add that number to the output list. If it's false, set it to true. Then iterate through the list of bools. Once you find an element that is false, add the index of that element + 1 to the... \$\endgroup\$