DSA Array | Contains duplicate

Problem Statement

You are given an array of integers, nums. Your task is to determine if the array contains any duplicate values. Return:

  • true if any value appears more than once in the array.

  • false if all values in the array are unique.

Examples

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

Explanation: The value 1 appears twice in the array.

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

Explanation: All values in the array are unique.


Code:


class Solution {
    public boolean hasDuplicate(int[] nums) {
        int n = nums.length;
        Set set = new HashSet<>();
        boolean containsDuplicate = false;
        for(int i =0; i<n; i++){
            containsDuplicate = !set.add(nums[i]);
            if(containsDuplicate){
                return containsDuplicate;
            }
        }
        return containsDuplicate; 
    }
}

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

Comments

Popular posts from this blog

Spring-Boot externalize logback configuration file (logback-spring.xml)

Create Height Balanced BST from Sorted Linkedlist

Reverse LinkedList in K nodes group - Data Structure Linked List

Spring Cloud - Configuration Server with Git Integration

Finding Height Of A Binary Tree