DEV Community

Tammy Vo
Tammy Vo

Posted on • Edited on

1 1

Contains Duplicate

Objective:

Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.


Pattern: Arrays and Hashing


Approach:

  1. Use a Set because Set does not allow duplicates.
  2. Go through the array nums and add values to the set, check if the Set contains the value.
  3. If set contains value then return true, else return false.

Big-O Notation:

Time Complexity: O(n)
We have a for loop that goes through the array n times.

Space Complexity: O(n)
We have a Set that stores the n elements.


Code:

class Solution {
    public boolean containsDuplicate(int[] nums) {
        // Set -> doesn't allow duplicates 
        Set <Integer> hashSet = new HashSet<>();

        // example: [2,5,8,5]
        // set: 2, 5, 8, 5
        for(int i = 0; i < nums.length; i++){
            if(hashSet.contains(nums[i])){
                return true;
            }
            hashSet.add(nums[i]);
        }
        return false; 
    }
}
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay