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
Duplicate in Array - LeetCode Solution with HashSet
More Relevant Posts
-
3Sum Problem: Recently solved the classic 3Sum problem by implementing it in three progressively optimized ways: 🔹 Brute Force – Checked all triplets (O(n³)) 🔹 Better Approach (Hashing) – Reduced one loop using a set (O(n²)) 🔹 Optimal Approach (Sorting + Two Pointers) – Efficient duplicate handling with O(n²) time and O(1) extra space Key takeaways: ✔️ Writing the brute-force solution first builds clarity ✔️ Sorting often unlocks powerful optimizations ✔️ Two-pointer technique is essential for array problems ✔️ Handling edge cases and duplicates carefully matters This exercise reinforced how structured thinking leads to better optimization — step by step. #DSA #Java #ProblemSolving #CodingPractice #LeetCode #SoftwareEngineering
To view or add a comment, sign in
-
-
Day: 57/365 📌 LeetCode POTD: Special Positions in a Binary Matrix Easy Key takeaways/Learnings from this problem: 1. This one shows how precomputing row and column counts makes checking each cell super easy. 2. Instead of re-scanning the whole row and column every time, count once and reuse smartly. 3. Good reminder that brute force can often be optimized with a tiny bit of preprocessing. 4. Clean implementation and careful condition checking matter more than complex algorithms here. #POTD #365DaysOfCode #DSA #Java #ProblemSolving #LearningInPublic #Consistency 🥷
To view or add a comment, sign in
-
-
Day 84/100 – LeetCode Challenge ✅ Problem: #47 Permutations II Difficulty: Medium Language: Java Approach: Backtracking with HashSet Deduplication Time Complexity: O(n × n!) Space Complexity: O(n × n!) for storing unique permutations Key Insight: When array contains duplicates, swapping can generate duplicate permutations. Use HashSet to store seen permutations and filter duplicates. Solution Brief: Modified standard permutation backtracking: Swap elements to generate permutations After generating full permutation, check if already in HashSet Add to result only if unique Backtrack by swapping back #LeetCode #Day84 #100DaysOfCode #Backtracking #Java #Algorithm #CodingChallenge #ProblemSolving #PermutationsII #MediumProblem #HashSet #Deduplication #DSA
To view or add a comment, sign in
-
-
Day 13/100 – LeetCode Challenge Problem: Linked List Cycle Today’s problem was about detecting whether a cycle exists in a linked list. Approach: Used Floyd’s Cycle Detection Algorithm (Tortoise and Hare). slow pointer moves one step fast pointer moves two steps If a cycle exists, both pointers will eventually meet If fast reaches null, the list has no cycle Complexity: Time: O(n) Space: O(1) Concepts Practiced: Linked List traversal Two-pointer technique Cycle detection algorithm #100DaysOfCode #LeetCode #DSA #Java #LinkedList #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
Day 26 - Single Element in a Sorted Array Technique Used: Parity-Based Binary Search Key Idea: Since every element appears twice except one, used index parity (even/odd positions) to determine which half violates the pairing rule. If pairing is correct on the left side, move right. Otherwise, move left. Time Complexity: O(log n) #Day26 #LeetCode #Java #BinarySearch #DSA #Algorithms
To view or add a comment, sign in
-
-
Day 38/75 — Permutations II Today’s problem was about generating all unique permutations of an array that may contain duplicates. Approach: • Use backtracking • Sort the array to handle duplicates • Use a boolean used[] array • Skip duplicates using condition: if (i > 0 && nums[i] == nums[i-1] && !used[i-1]) continue Key logic: if (used[i]) continue; if (i > 0 && nums[i] == nums[i-1] && !used[i-1]) continue; Time Complexity: O(n! × n) Space Complexity: O(n) recursion stack Key Insight: The main challenge is avoiding duplicate permutations. Sorting + controlled skipping ensures we only generate unique results. 38/75 🚀 #Day38 #DSA #Backtracking #Java #Algorithms #LeetCode Thank You Pratyush Narain .
To view or add a comment, sign in
-
-
🚀 Day 29 of #75daysofLeetCode 2095 – Delete the Middle Node of a Linked List Just solved an interesting linked list problem that perfectly demonstrates the power of the two-pointer technique (slow & fast pointers). 🔍 Problem Insight: Given a linked list, delete its middle node where the middle is defined as ⌊n/2⌋ (0-based indexing). 💡 Key Idea: Instead of calculating the length, we can efficiently find the middle using: 🐢 Slow pointer (1 step) ⚡ Fast pointer (2 steps) When the fast pointer reaches the end, the slow pointer will be at the middle node! 🛠 Approach: ✔ Handle edge case (single node → return null) ✔ Traverse using slow & fast pointers ✔ Keep track of previous node ✔ Remove the middle node in one pass ⏱ Time Complexity: O(n) 💾 Space Complexity: O(1) 🔥 Why this matters? This pattern is widely used in: Finding middle of linked list Detecting cycles Splitting lists Mastering this unlocks many problems! #LeetCode #DSA #LinkedList #Java #CodingInterview #ProblemSolving #TechLearning
To view or add a comment, sign in
-
-
🚀 Day 51 of #100DaysOfCode 🌱 Topic: Arrays / HashSet ✅ Problem Solved: LeetCode 1346 – Check If N and Its Double Exist 🛠 Approach: Used a HashSet for efficient lookups. Traversed the array once. For each element num: Checked if 2 * num already exists in the set. Checked if num is even and num / 2 exists in the set. If either condition is true → return true. Otherwise, added the current number to the set. #100DaysOfCode #Day51 #DSA #Arrays #HashSet #LeetCode #Java #ProblemSolving #CodingJourney #Consistency
To view or add a comment, sign in
-
-
Day 83/100 – LeetCode Challenge ✅ Problem: #46 Permutations Difficulty: Medium Language: Java Approach: Backtracking with Swapping Time Complexity: O(n × n!) Space Complexity: O(n) for recursion stack Key Insight: Generate all permutations by fixing each element at current position and recursively permuting remaining elements. Use swapping to avoid extra space for visited tracking. Solution Brief: Base case: When index i reaches end, add current array as permutation. Recursive case: For each position j from i to end: Swap elements at i and j Recurse on i + 1 Swap back (backtrack) to restore original order #LeetCode #Day83 #100DaysOfCode #Backtracking #Java #Algorithm #CodingChallenge #ProblemSolving #Permutations #MediumProblem #Recursion #Swapping #DSA
To view or add a comment, sign in
-
-
Day 7/100 – LeetCode Challenge Problem: Palindrome Number Today’s problem focused on number manipulation without converting the integer into a string. Approach: If number is negative → return false Reverse the digits using modulo (% 10) and division (/ 10) Compare reversed number with original number Logic Used: Extract last digit: rem = x % 10 Build reversed number: rev = rev * 10 + rem Remove last digit: x = x / 10 Complexity: Time: O(log₁₀ n) Space: O(1) Key takeaway: Problems involving digits can often be solved mathematically without string conversion. #100DaysOfCode #LeetCode #DSA #Java #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development