1. Contains Duplicate

1. Contains Duplicate

Ques:(https://leetcode.com/problems/contains-duplicate/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

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

Constraints:

  • 1 <= nums.length <= 10<sup>5</sup>

  • -10<sup>9</sup> <= nums[i] <= 10<sup>9</sup>

Steps to aproach leetcode problem to solve effectively and ace the oa and inteviews:

  1. Understand the Problem Statement

  2. Examine the Examples for Clarity

  3. Analyze the Constraints

  4. Plan the Solution

  5. Write and Test Your Code

Step 1 Understand the Problem Statement : Look for duplicates in the array. If you find any duplicate, return true. If there are no duplicates, return false.

Step 2 Examine the Examples for Clarity:

Examples:

  1. Example 1:

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

    • Output: true

    • Explanation: The number 1 appears twice (at indices 0 and 3), so the output is true.

  2. Example 2:

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

    • Output: false

    • Explanation: All numbers are distinct, so the output is false.

Step 3 Analyze the Constraints : we have to see the constraint of the problem like in this 1 <= nums.length <= 10<sup>5</sup>

This means the length of the array nums can range from 1 to 100,000.A solution with O(n^2) time complexity (e.g., nested loops) will be too slow for large arrays (like when nums.length = 100,000).You should aim for a solution with O(n) or O(n log n) complexity.

-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup> Each integer in the array can range from -1 billion to 1 billion.The array elements can be both negative and positive, so your algorithm should not assume only positive integers.

  • If you're storing these numbers in a data structure (e.g., a HashSet or Map), ensure the data structure can handle this range. Fortunately, Java's HashSet and HashMap can handle integers of this size.If you use an array as a counter (like a frequency array), it would require too much memory (2 * 10^9 elements), which is impractical. So avoid this approach

now we clear with the constraint and now we are going with optimal solution becaue if we solve in O(n^2) then there would be time limit exceed. we have to solve with optimal.

there are two terms -

brute force solution - checking all the possible case after runing loop basic way.

optimal solution - best way to solve.

Step 4 Plan the Solution:

Brute force solution first - The brute-force solution uses two nested loops to compare every pair of elements in the array. If we find any two elements that are the same, we immediately return true. If no duplicates are found after checking all pairs, we return false.

Steps for Brute-Force Solution

Time & Space Complexity

  • Time complexity: O(n2)

  • Space complexity: O(1)

//brute force solution

class Solution {
    public boolean containsDuplicate(int[] nums) { 
        // The method takes an array of integers 'nums' as input
        // and returns true if there are any duplicate values in the array.
        // Otherwise, it returns false.

        // Outer loop: Iterate through each element of the array
        for (int i = 0 ; i < nums.length ; i++) { 
            // 'i' represents the current index of the element we are comparing
            // Start with the first element and go up to the second last element.

            // Inner loop: Compare nums[i] with all subsequent elements in the array
            for (int j = i + 1 ; j < nums.length ; j++) { 
                // 'j' starts from the index just after 'i' to avoid comparing the same element
                // Compare the current element nums[i] with nums[j].
                if (nums[i] == nums[j]) {
                    // If nums[i] and nums[j] are equal, that means a duplicate is found.
                    return true; // Return true immediately as we only need one duplicate.
                }
            }
        }

        // If the loops complete without finding any duplicates,
        // it means all elements in the array are distinct.
        return false; 
    }
}
  1. Outer Loop:

    • Iterate through the array from the first element to the second last element.
  2. Inner Loop:

    • For each element in the outer loop, iterate through all subsequent elements using the inner loop.

    • Compare the current element from the outer loop with the current element from the inner loop.

      to know about outer and inner loop click here

  3. Check for Equality:

    • If any two elements are equal, return true.
  4. Complete the Iteration:

    • If no duplicates are found after all comparisons, return false.

Steps for Optimal Solution

Here’s the line-by-line explanation of the code with comments added:

public class Solution {
    public boolean hasDuplicate(int[] nums) {
        // This method takes an array of integers 'nums' as input.
        // It returns true if any duplicate values exist in the array.
        // Otherwise, it returns false.

        Set<Integer> seen = new HashSet<>();
        // Create a HashSet to store unique numbers encountered in the array.
        // HashSet is used because it provides O(1) average time complexity for add and contains operations.

        for (int num : nums) {
            // Iterate through each element in the array 'nums'.

            if (seen.contains(num)) {
                // Check if the current number 'num' is already in the HashSet 'seen'.
                // If it is, that means a duplicate has been found.
                return true; // Return true immediately as we only need one duplicate to confirm.
            }

            seen.add(num);
            // If the current number 'num' is not in the HashSet, add it to the HashSet.
            // This ensures that we keep track of all numbers encountered so far.
        }

        return false;
        // If the loop completes without finding any duplicates, return false,
        // indicating that all elements in the array are distinct.
    }
}

Time & Space Complexity

  • Time complexity: O(n)

  • Space complexity: O(n)

Summary of the Code Flow

  1. Initialization:

    • A HashSet called seen is created to store numbers as we iterate through the array. This helps us efficiently check for duplicates.
  2. Iteration:

    • The for loop iterates through each number in the array nums.

    • For each number, we check:

      • If the number is already in the HashSet:

        • Return true because a duplicate is found.
      • If the number is not in the HashSet:

        • Add the number to the HashSet.
  3. Final Return Statement:

    • If the loop completes without finding a duplicate, return false.

Advantages of This Approach

  1. Efficiency:

    • The HashSet operations (add and contains) are O(1)O(1)O(1) on average.

    • The total time complexity is O(n)O(n)O(n), where nnn is the size of the input array.

  2. Simplicity:

    • The code is concise and avoids nested loops, making it much faster than a brute-force solution.
  3. Space Usage:

    • The space complexity is O(n)O(n)O(n), as we store up to nnn elements in the HashSet.

How the Code Works with Example

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

  1. seen = {} (initially empty).

  2. First Iteration:

    • num = 1.

    • 1 is not in seen → Add 1 to seen.

    • seen = {1}.

  3. Second Iteration:

    • num = 2.

    • 2 is not in seen → Add 2 to seen.

    • seen = {1, 2}.

  4. Third Iteration:

    • num = 3.

    • 3 is not in seen → Add 3 to seen.

    • seen = {1, 2, 3}.

  5. Fourth Iteration:

    • num = 1.

    • 1 is already in seen → Return true immediately.