Solving LeetCode problem 217 Contains Duplicate in 4 ways.

2 min read
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.
Example 1:
Input: nums = [1,2,3,1]
Output: true
Explanation:
The element 1 occurs at the indices 0 and 3.
Constraints:
1 <= nums.length <= 10^5
-10^9<= nums[i] <= 10^9
Solutions-
public static void main(String[] args) {
int[] arr = {1,2,4,1,5,6};
System.out.println(containsduplicate1(arr));
System.out.println(containsduplicate2(arr));
System.out.println(containsduplicate3(arr));
System.out.println(containsduplicate4(arr));
}
public static boolean containsduplicate1(int[] arr) {
//BruteForcing our way with looping in an array for each element
//Time complexity - O(n^2)
int len = arr.length;
for(int i=0 ; i<len-1 ; i++ )
for(int j = i+1 ; j< len ; j++) {
if(arr[i] == arr[j])
return true;
}
return false;
}
public static boolean containsduplicate2(int[] arr) {
//Using Set we add every element in a set which has the property to only store unique
//numbers and have a method to directly check if set contains the number.
//Time Complexity - O(1) for set method and O(n) for looping once --> O(n)
Set<Integer> set1 = new HashSet<>();
for(int x: arr) {
if(set1.contains(x))
return true;
else
set1.add(x);
}
return false;
}
public static boolean containsduplicate3(int[] arr ) {
// using Java 8 Stream API , One line solution to showcase API stream knowledge
//Time Complexity - O(n)
return Arrays.stream(arr).distinct().count() < arr.length;
}
public static boolean containsduplicate4(int[] arr) {
//using sort
//Time Complexity - O(nlogn)
Arrays.sort(arr); // Time - 0(nlogn) ( Dual-Pivot Quicksort )
for(int i =1 ; i< arr.length ;i++)
if(arr[i] == arr[i-1])
return true;
return false;
}
0
Subscribe to my newsletter
Read articles from CodeStorm directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
