titan2400

Contains Duplicate - LeetCode

Oct 27th, 2025
1,353
0
Never
13
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.30 KB | Source Code | 0 0
  1. // Contains Duplicate - https://leetcode.com/problems/contains-duplicate/
  2.  
  3. class Solution {
  4.     // Brute force
  5.     // Time Complexity: O(n^2)
  6.     // Space Complexity: O(1)
  7.     // Below solution leads to time limit exceeded on LeetCode
  8.     // public boolean containsDuplicate(int[] nums) {
  9.     //     for(int i = 0; i < nums.length; i++) {
  10.     //         for(int j = i + 1; j < nums.length; j++) {
  11.     //             if(nums[i] == nums[j]) {
  12.     //                 return true;
  13.     //             }
  14.     //         }
  15.     //     }
  16.  
  17.     //     return false;
  18.     // }
  19.  
  20.     // Using HashSet
  21.     // Time Complexity: O(n)
  22.     // Space Complexity: O(n)
  23.     // public boolean containsDuplicate(int[] nums) {
  24.     //     Set<Integer> set = new HashSet<>();
  25.  
  26.     //     for(int i = 0; i < nums.length; i++) {
  27.     //         set.add(nums[i]);
  28.     //     }
  29.  
  30.     //     return set.size() != nums.length;
  31.     // }
  32.  
  33.     // Using HashSet (Optimized)
  34.     // Time Complexity: O(n)
  35.     // Space Complexity: O(n)
  36.     public boolean containsDuplicate(int[] nums) {
  37.         Set<Integer> set = new HashSet<>();
  38.  
  39.         for(int i = 0; i < nums.length; i++) {
  40.             if(set.contains(nums[i])) {
  41.                 return true;
  42.             }
  43.  
  44.             set.add(nums[i]);
  45.         }
  46.  
  47.         return false;
  48.     }
  49. }
Advertisement
Comments
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
Add Comment
Please, Sign In to add comment