easy Problem 2 Contains Duplicate
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.
Examples
Example 1:
Input: nums= [1, 2, 3, 4]
Output: false
Explanation: There are no duplicates in the given array.
Example 2:
Input: nums= [1, 2, 3, 1]
Output: true
Explanation: '1' is repeating.
Example 3:
Input: nums= [3, 2, 6, -1, 2, 1]
Output: true
Explanation: '2' is repeating.
Constraints:
- 1 <= nums.length <=
<= nums[i] <=
Try it yourself
Try solving this question here:
For a detailed solution, see the next chapter.
✅ Solution Contains Duplicate
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.
Examples
Example 1:
Input: nums= [1, 2, 3, 4]
Output: false
Explanation: There are no duplicates in the given array.
Example 2:
Input: nums= [1, 2, 3, 1]
Output: true
Explanation: '1' is repeating.
Example 3:
Input: nums= [3, 2, 6, -1, 2, 1]
Output: true
Explanation: '2' is repeating.
Constraints:
- 1 <= nums.length <=
<= nums[i] <=
Solution
Approach 1: Brute Force
We can use a brute force approach and compare each element with all other elements in the array. If any two elements are the same, we'll return true. If we've gone through the entire array and haven't found any duplicates, we'll return false.
Code
Here is the code for this algorithm:
class Solution {
public boolean containsDuplicate(int[] nums) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] == nums[j]) {
// if any two elements are the same, return true
return true;
}
}
}
return false; // if no duplicates are found, return false
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] nums1 = { 1, 2, 3, 4 };
System.out.println(solution.containsDuplicate(nums1)); // Expected output: false
int[] nums2 = { 1, 2, 3, 1 };
System.out.println(solution.containsDuplicate(nums2)); // Expected output: true
int[] nums3 = {};
System.out.println(solution.containsDuplicate(nums3)); // Expected output: false
int[] nums4 = { 3, 2, 6, -1, 2, 1 };
System.out.println(solution.containsDuplicate(nums4)); // Expected output: true
}
}
Complexity Analysis
Time Complexity
- Outer loop: The outer loop runs
Ntimes, whereNis the length of the input array. This gives the outer loop a time complexity of. - Inner loop (nested): For each iteration of the outer loop, the inner loop runs
N - i - 1times, which decreases asiincreases. In the worst case, the inner loop will run approximatelytimes for the first element, times for the second element, and so on. This results in a total time complexity for the inner loop of .
Overall time complexity:
Space Complexity
- The algorithm only uses a few variables (
i,j, and boolean result), all of which require constant space. - No additional data structures are used that depend on the input size.
Overall space complexity:
Approach 2: Using Hash Set
We can use the set data structure to check for duplicates in an array.
Since a set can only hold unique elements, we can check if the elements in the given array are present more than once by adding them to a set. This way, we can determine if there are any duplicates in the array.
This approach works as follows:
-
A set named
unique_setis created to store unique elements. -
The algorithm then iterates through the input array
nums. -
For each element "x" in the array, the algorithm checks if "x" is already in the
unique_set.-
If "x" is in the
unique_set, then the algorithm returns True, indicating that a duplicate has been found. -
If "x" is not in the
unique_set, then the algorithm adds "x" to theunique_set.
-
-
The iteration continues until all elements in the array have been processed.
-
If no duplicates are found, the algorithm returns False.
This approach utilizes the property of sets to store only unique elements, making it an efficient solution for finding duplicates in an array.
Here is the algorithm Walkthrough:
Code
Here is the code for this algorithm:
import java.util.HashSet;
import java.util.Set;
public class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> unique_set = new HashSet<>(); // Use HashSet to store unique elements
for (int x : nums) {
if (
!unique_set.add(x) // If the set already contains the current element, return true
) return true;
}
return false; // Return false if no duplicates found
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] nums1 = { 1, 2, 3, 4 };
System.out.println(solution.containsDuplicate(nums1)); // Expected output: false
int[] nums2 = { 1, 2, 3, 1 };
System.out.println(solution.containsDuplicate(nums2)); // Expected output: true
int[] nums3 = {};
System.out.println(solution.containsDuplicate(nums3)); // Expected output: false
int[] nums4 = { 3, 2, 6, -1, 2, 1 };
System.out.println(solution.containsDuplicate(nums4)); // Expected output: true
}
}
Complexity Analysis
Time Complexity
- Loop through the array: The algorithm iterates over the array
numsonce. This gives a time complexity of, where Nis the number of elements in the array. - HashSet operations: For each element, the algorithm performs a
HashSet.add()operation. On average, adding or checking elements in aHashSethas a time complexity ofdue to its underlying hash table structure.
Overall time complexity: N is the number of elements in the array.
Space Complexity
- HashSet storage: The algorithm uses a
HashSetto store unique elements. In the worst case, when all elements are unique, theHashSetwill containNelements. - This results in a space complexity of
, where Nis the number of unique elements in the array.
Overall space complexity:
Approach 3: Sorting
Another approach is to sort the array first and then check for duplicates.
We'll sort the array and then iterate through it, comparing each element with the next one.
If any two elements are the same, we'll return true. If we've gone through the entire array and haven't found any duplicates, we'll return false.
Code
Here is the code for this algorithm:
import java.util.Arrays;
class Solution {
public boolean containsDuplicate(int[] nums) {
Arrays.sort(nums); // sort the array
// use a loop to compare each element with its next element
for (int i = 0; i < nums.length - 1; i++) {
// if any two elements are the same, return true
if (nums[i] == nums[i + 1]) {
return true;
}
}
return false; // if no duplicates are found, return false
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] nums1 = { 1, 2, 3, 4 };
System.out.println(solution.containsDuplicate(nums1)); // Expected output: false
int[] nums2 = { 1, 2, 3, 1 };
System.out.println(solution.containsDuplicate(nums2)); // Expected output: true
int[] nums3 = {};
System.out.println(solution.containsDuplicate(nums3)); // Expected output: false
int[] nums4 = { 3, 2, 6, -1, 2, 1 };
System.out.println(solution.containsDuplicate(nums4)); // Expected output: true
}
}
Complexity Analysis
Time Complexity
- The algorithm first sorts the array using
Arrays.sort(), which has a time complexity of, where Nis the number of elements in the array. - After sorting, the algorithm performs a single pass through the array to compare adjacent elements. This step takes
time. - Therefore, the overall time complexity is dominated by the sorting operation, making it
.
Space Complexity
- The space complexity of the sorting algorithm depends on the implementation of
Arrays.sort(). In the case of primitive types likeint[], it uses a variant of the quicksort algorithm, which has a space complexity ofdue to the recursion stack for in-place sorting. - The algorithm itself only uses a constant amount of extra space for the index variable and the loop, which does not depend on the size of the input.
Thus, the overall complexity is:
- Time Complexity:
- Space Complexity:
🤖 Don't fully get this? Learn it with Claude
Stuck on Problem 2 Contains Duplicate? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Problem 2 Contains Duplicate** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Problem 2 Contains Duplicate** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Problem 2 Contains Duplicate**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Problem 2 Contains Duplicate**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.