Ticker

6/recent/ticker-posts

Contains Duplicate - LeetCode Solution and Approach

 


 217. Contains Duplicate - LeetCode - Easy

Problem Description:

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.

Example 1:

Input: nums = [1,2,3,1]
Output: true

Example 2:

Input: nums = [1,2,3,4]
Output: false

Example 3:

Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true

Constraints:

1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9

Approach:


The problem becomes easy if you use Set Data Structure. Set has inbuilt methods for checking if set already contains given value or not. In JAVA we have contains method which returns true if given number is present in Set. We also have the add method to add given number to Set. The add method returns true if given number is added, and false if given number is already present in Set.

  • We will initialize a Set. We will iterate through given array and add current number to the Set. If Set already contains given number, the add method returns false, so we will return true. And we will keep iterating.
  • If we completed iterating all the numbers, means the set doesn't contains duplicates, so we will return false.

JAVA:

Time Complexity : 0(n)
Space Complexity: 0(n)

class Solution {
    public boolean containsDuplicate(int[] nums) {
        Set<Integer> set=new HashSet<>();
        for(int n:nums)
        if(!set.add(n)) return true;
        return false;
    }
}





Keep Learning and Practicing with Programming Chaska !!!

Post a Comment

0 Comments