Find duplicates in an array using Python DSA


Can anyone help me out with this question. I did it in the right way but it is showing me an error. I dont know whats the issue.

Find duplicates in an array
Given an array a[] of size N which contains elements from 0 to N-1, you need to find all the elements occurring more than once in the given array.

Error while compiling

Here is my code

def duplicates(self, arr, n): 
        result = []
        a = []
        for i in arr:
            if i not in a:
                if i not in result:
        if len(a) == n:
        return result
Asked By: David Roy



I think the error the error is due to the worst time and space complexity. You have used the brute force method to program the code which is not the right way. Make your code more efficient for a good time and space complexity. Here is my code.

def duplicates(self, arr, n): 
        # Make an array of n size with a default value of 0
        result = [0] * n
        ans = []
        #Update the index with value in an array

        for i in range(n):
            result[arr[i]] +=1

        # Iterate through each element in an array to find the element which has a value of more than 1. return the I value and break.

        for i in range(len(result)):
            if result[i] >1:
        if not ans:
        return ans
Answered By: Pratul Pant
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.