Posts

Showing posts with the label HashSet

Longest SubString Without Repeating Characters LeetCode

         Way 1 : Using ArrayDeque and ArrayList           int count=0;         int index=0;         ArrayList<Integer>aa=new ArrayList<Integer>();         ArrayDeque<Character> arr=new ArrayDeque<Character>();         for(int i=0;i<s.length();i++){             if(arr.contains(s.charAt(i))){                 aa.add(count); count=0;                 arr.clear(); i=index++;                              }             else{                 arr.addLast(s.charAt(i)); count++;             }         }       ...

Distribute Candies LeetCode

TIME: O(N) [Traversing Array][LeetCode Time : 31ms faster than 86.25%] SPACE: O(N) [Using HashSet] [LeetCode Memory: 40.5 MB less than 95.93%] Approach: Using HashSet HashSet will keep just one occurrence of the element due to which we will clearly get the number of different types of candies available. Then we will compare with the number of chocolates recommended by the doctor. If options available are less than the doctor's recommendation then we will return options else we will return recommend chocolates by a doctor. class Solution {     public int distributeCandies(int[] arr) {         HashSet<Integer> set=new HashSet<Integer>(); for(int i=0;i<arr.length;i++){ set.add(arr[i]); } int a=set.size();//options int b=arr.length/2;//doctor if(b>a){ return a;         } else{ return b;         }     } } Thanks for Reading. "Knowledge grows by sharing not by saving...

Common ELements Geeks For Geeks

 class Solution {     ArrayList<Integer> commonElements(int arr1[], int arr2[], int arr3[], int n1, int n2, int n3)      {                   HashSet<Integer> set1=new HashSet<Integer>(); HashSet<Integer> set2=new HashSet<Integer>(); HashSet<Integer> set3=new HashSet<Integer>(); for(int i=0;i<n1;i++){ set1.add(arr1[i]); } for(int i=0;i<n2;i++){ if(set1.contains(arr2[i])){ set2.add(arr2[i]); } } for(int i=0;i<n3;i++){ if(set2.contains(arr3[i])){ set3.add(arr3[i]); } } /*System.out.println("set1: "); for (Integer i : set1){             System.out.println(i); } System.out.println("set2: "); for (Integer i : set2){             System.out.println(i); }*/ Set<Integer> set4 = new TreeSet<Integer>(set3); /*System.out...