Grokking Data Structures & Algorithms for Coding Interviews
Vote

0% completed

Problem 2: Contains Duplicate (easy)

Problem Statement

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.

Examples

Example 1:

Input: nums= [1, 2, 3, 4]
Output: false  
Explanation: There are no duplicates in the given array.

Example 2:

Input: nums= [1, 2, 3, 1]
Output: true  
Explanation: '1' is repeating.

Example 3:

Input: nums= [3, 2, 6, -1, 2, 1]
Output: true  
Explanation: '2' is repeating.

Constraints:

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

.....

.....

.....

Like the course? Get enrolled and start learning!
P

pratiksh.patel91

· 2 years ago

Computing plan 

Brute Force: Compare each element with every other element in the array. If any two elements are equal, return true. Time complexity: O(n^2), space complexity: O(1).

Sorting: Sort the array and check if adjacent elements are equal. Time complexity: O(n log n) due to sorting, space complexity: O(1).

Hash Set: Use a HashSet to store unique elements. If adding an element fails (because it’s already in the set), return true. Otherwise, return false. Time complexity: O(n) for the loop, space complexity: O(n) for the HashSet.

S

Shane

· 3 years ago

rust support soon?

Show 1 reply
Gokul Rama

Gokul Rama

· 3 years ago

public boolean containsDuplicate(int[] nums) {     if (nums == null || nums.length == 0) {       return false;     }     // O(N*logN) - sorting     Arrays.sort(nums);     // O(N) - iteration     for (int i=1; i<nums.length; i++) {       if (nums[i-1] == nums[i]) {         return true;       }     }     return false;   }
Show 1 reply
Shraddha

Shraddha

· 2 years ago

package main

import "fmt"

// containsDuplicate checks for duplicates in a slice of integers

func containsDuplicate(nums []int) bool {

if len(nums) == 0 || nums == nil {

    return false

}

for i := 0; i< len(nums) - 1; i++ {

     for j := i+1 ; j < len(nums) ; j++ {

        if nums[i] == nums[j] {

           return true 

        }

     }

}

// ToDo: Write Your Code Here.

return false 

}

func main() {

arr := [][]int{

    {1,2,3,4},

    {1,2,3,1},

}



for _, input := range arr {

    isDuplicate := containsDuplicate(input)

    fmt.Println(isDuplicate)

}

}

Show 1 reply