Check if array contains duplicates

Program for checking duplicate in an array – Duplicate Integer Problem

Given an integer array nums, return true if any value appears more than once in the array, otherwise return false.

Contains Duplicate in an Array

Program for checking duplicate in an array - Duplicate Integer Solution

Recommendation – You should aim for a solution as good or better than O(n) time and O(n) space, where n is the size of the input array.

There are mainly 4 approach to solve this problem – 

  1. Brute Force Method
  2. Sorting Method
  3. Hash Set
  4. Hash Set Length

Hints for solving problems

1. Brute Force Method

This method iterate through each element and check it against every other element to find duplicates or fulfill specific conditions. This is usually the simplest but least efficient method.

  • Time complexity: O(n^2)
  • Space complexity: O(1)

Code

2. Sorting Method

This method sort the elements first, then compare adjacent elements. This reduces the problem to a more manageable sequence comparison.

  • Time complexity: O(nlogn)
  • Space complexity: O(1) or O(n) depending on the sorting algorithm.

Code

3. Hash Set Method

This method use a hash set to store elements as you iterate. This allows you to check for duplicates or existence in constant time.

  • Time complexity: O(n)
  • Space complexity: O(n)

Code

4. Hash Set Length Method

This method add elements to a hash set, then check the set’s length against the list length. If the lengths differ, duplicates exist.

  • Time complexity: O(n)
  • Space complexity: O(n)

Code

More Articles