Contains Duplicate
Contains Duplicate
Section titled “Contains Duplicate”
Easy
Day 1 • Striver Blind 75
📌 Problem Overview
Section titled “📌 Problem Overview”Given an integer array nums, return true if any value appears at least twice in the array.
Examples & Constraints
Section titled “Examples & Constraints”Example 1:
- Input:
nums = [1,2,3,1] - Output:
true
Example 2:
- Input:
nums = [1,2,3,4] - Output:
false
Example 3:
- Input:
nums = [1,1,1,3,3,4,3,2,4,2] - Output:
true
Constraints:
1 ≤ nums.length ≤ 10⁵-10⁹ ≤ nums[i] ≤ 10⁹
💡 Approach & Intuition
Section titled “💡 Approach & Intuition”Tests your ability to detect duplicates efficiently.
🎯 Pattern Recognition
Section titled “🎯 Pattern Recognition”Pattern: Set for Duplicates
Use a Set to track seen elements. If an element is already in the Set, you’ve found a duplicate.
📊 Step-by-Step Execution (Mermaid Diagram)
Section titled “📊 Step-by-Step Execution (Mermaid Diagram)”graph TD Start["Input Data"] --> Process["Process Element by Element"] Process --> Lookup{"Hash Map / Set Lookup"} Lookup -- "Match Found" --> Return["Return Indices / Result"] Lookup -- "No Match" --> Store["Store in Map / Set"] Store --> Process🐢 Brute Force Solution
Section titled “🐢 Brute Force Solution”function containsDuplicate(nums) { for (let i = 0; i < nums.length; i++) { for (let j = i + 1; j < nums.length; j++) { if (nums[i] === nums[j]) return true; } } return false;}- Time Complexity:
O(n²) - Space Complexity:
O(1) - Explanation: Compare every pair.
⚡ Optimized Solution
Section titled “⚡ Optimized Solution”function containsDuplicate(nums) { const seen = new Set(); for (const num of nums) { if (seen.has(num)) return true; seen.add(num); } return false;}- Time Complexity:
O(n) - Space Complexity:
O(n) - Explanation: Use a Set for O(1) lookups.
🐾 Step-by-Step Walkthrough
Section titled “🐾 Step-by-Step Walkthrough”- Initialize State: Setup necessary pointers, dynamic programming arrays, or hash maps.
- Iterate & Evaluate: Process the input according to the boundary conditions.
- Update & Return: Compute the optimal answer and return early or at termination.
🎙️ FAANG Interview Pitch
Section titled “🎙️ FAANG Interview Pitch”- Brute force O(n²)
- Use a Set for O(n) time
- Trade O(n) space for O(n) time
- Early exit optimization
💡 Progressive Hints
Section titled “💡 Progressive Hints”- Use a Set to track seen numbers.
- If a number is already in the Set, you have a duplicate.
- Return true as soon as you find a duplicate.