Finding Duplicates in an array -BruteForce [O(n^2)]

Finding duplicates in an array is a common interview question. The problem statement can be defined as follows. Given an array of n numbers, give an algorithm for checking whether, there are any duplicates in the array or not? For such questions obvious answer is Brute force  or Naive solution.

Solution: Exhaustively search for duplicates in the array. For-each input element, check whether there is any element with the same value. This can be solved with just by using two for loops.

Finding duplicates in an array – Brute Force

In the above solution, we are making an extra comparison, element with it self. We can decrease no.of comparisons by avoiding comparison of element with self.

Finding duplicates in an array -Brute Force with improvement over no.of comparisons

A sample Test client for above programs


Leave a Comment