1. Contains Duplicate

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,1]

Output: true

Explanation: The element 1 occurs at the indices 0 and 3.

Example 2:

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

Output: false

Explanation: All elements are distinct.

Example 3:

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

Output: true

Code

class Solution {
    public boolean containsDuplicate(int[] nums) {
        HashMap<Integer, Integer> duplicateHashmap = new HashMap<Integer, Integer>();
        for (int index = 0; index < nums.length; index++) {
            if (duplicateHashmap.containsKey(nums[index])) {
                return true;
            } else {
                duplicateHashmap.put(nums[index], 1);
            }
        }
        return false;
    }
}

The overall function of this code is to efficiently determine whether any number appears more than once in the given array. Please find the explanation below:

  • A HashMap named duplicateHashmap is created. This map will store the integers from the nums array as keys. Each key in the HashMap represents a unique number from the array.

  • A for loop iterates through each element in the nums array. Inside the loop, the code checks if the current number (nums[index]) is already a key in duplicateHashmap:

    • If it is, this means the number is a duplicate, so the method immediately returns true.

    • If it isn't, the number is added to the duplicateHashmap with a value of 1.

  • When adding a number to the HashMap, the code sets the value to 1 with duplicateHashmap.put(nums[index], 1);. This value doesn’t serve any specific purpose in this context because:

    • We’re only interested in whether the key exists (indicating the number has already been seen).

    • The value (1 in this case) does not provide any additional information or functionality.

  • If the loop completes without finding any duplicates, the method returns false, indicating that all elements in the array are unique.

This might not be the optimal solution, but it’s a starting point for my work. As I progress, I hope to enhance my coding style along the way.

Last updated