Duplicate in Array - LeetCode Solution with HashSet

Contains Duplicate – LeetCode Solution 📌 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. 🔗 Problem Link: https://lnkd.in/gY2dtJ9m ⸻ 💡 Approach To solve this problem efficiently, we use a HashSet. Why HashSet? • A HashSet does not allow duplicate elements. • It provides O(1) average time complexity for add() and contains() operations. Algorithm Steps: 1. Create an empty HashSet. 2. Traverse through each element in the array. 3. For every number: • If it already exists in the set → return true. • Otherwise, add it to the set. 4. If no duplicates are found after the loop → return false. ⸻ 🧠 Time & Space Complexity • Time Complexity: O(n) (We traverse the array once) • Space Complexity: O(n) (In worst case, all elements are stored in the HashSet) #java #dsa #javaprogram

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories