Find the repeated elements in a list You are given an array of n+2 elements. All elements of the array are in range 1 to n. All elements occur once except two numbers, which occur twice. Your task is to find the two repeating numbers.


My solution is:

t=int(input()) #number of test cases
for _ in range(t):
    n=int(input()) # no. of array elements
    l=[int(x) for x in input().split()]  #array elements
    for i in range(1,n-1):
        if l.count(i)==2:  # using count function to count the elements
            print(i,end=' ')
    print()


How can I improve it?  Currently, it shows time limit exceeded on hackerrank.
Minor


Consider using the unittest module instead of using input to test
Use a if __name__ == "__main__" guard
Make it a function
Don't print but return variables


Timing improvements


  l.count(i) == 2


It will search the entire list from the start. 

Let's take a sample input (worst case) of [2, 3, 4, 5, 6, 7, 8, 1, 1, 2, 2], it will search the entire list 10 times!

This can be done in \$ O(n) \$ (worst case), because we know


  All elements of the array are in range 1 to n



You can create a list temp with length n filling it with None or 0
For every number in the array, check if the value in temp[i] is empty (0 or None)


If it is empty put the value on that position
If the number is the same as the value of the temp list, we have seen it before



Revised Code

def find_repeating(lst):
    counts = [None] * len(lst)
    for i in lst:
        if counts[i] is None:
            counts[i] = i
        elif i == counts[i]:
            yield i


Note

This has the disadvantage of continuing to loop after the numbers are found, to avoid this you could add the elements to another array and return when the length of the array is 2.

It will not make the most "beautiful" code, but it will be faster than @Peilonrayz's answer for anything but worst case, since that requires to loop through the entire array.

def find_repeating(lst, count=2):
    ret = []
    counts = [None] * len(lst)
    for i in lst:
        if counts[i] is None:
            counts[i] = i
        elif i == counts[i]:
            ret += [i]
            if len(ret) == count:
                return ret


Timing all solutions