Posts

Showing posts from July, 2021

ELECTRONICS SHOP HACKERRANK

APPROACH 1: TIME: O(N^2) SPACE:O(NLOG(K) ie NLOG(1) as k=1)[ArrayList and Priority Queue] static   int  getMoneySpent( int [] arr1,  int [] arr2,  int  a) {          int  b=arr1.length;          int  c=arr2.length;                  int  start= 0 ;          int  sum= 0 ;          int  end=b- 1 ;         ArrayList<Integer> aa= new  ArrayList<Integer>();          while (start<=end){              for ( int  i= 0 ;i<c;i++){                 sum=arr1[start]+arr2[i];                 aa.add(sum);                 sum= 0 ;             }             start++;                      }          //System.out.print(aa+" ");                  PriorityQueue<Integer> q= new  PriorityQueue<Integer>();         q.add(- 1 );          //System.out.println(q+" ");          for ( int  i= 0 ;i<aa.size();i++){              //System.out.println("Peek is: "+q.peek());              //System.out.println("Element is: "+aa.get(i));              if ((q

Implement strStr() LeetCode

APPROACH  TIME: O(N) [indexOf will check whole string(haystack) for getting indexof string needle. Along with that contains function will check whether the string needle is present in the string haystack or not. So it may also traverse the whole string also.] SPACE: O(1)[directly return index] WAY 1 : if(haystack.length()==0 && needle.length()==0){             return 0;         }         else if(haystack.length()==0 && needle.length()!=0){             return -1;         }         else{             if(!haystack.contains(needle)){                 return -1;             }             else{                 return haystack.indexOf(needle);             }         } LeetCode Time: 649 ms faster than 23.3% LeetCode Space: 38.8MB less than 56.96% ====================================================================== WAY 2: if(needle.length()==0){             return 0;         }         else{             if(haystack.length()==0){                 return -1;             }          

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.😇"

Sum Of Unique Elements LeetCode

Approach Explained:  Here first we will add all the numbers in the ArrayList 1 . After that we will traverse the ArrayList1 and then add all the duplicates in the ArrayList 2 . We are doing sum simultaneously for both ArrayList. Then, we will have sum of the original ArrayList (the input array) and duplicate elements sum2. We will then subtract sum2 from sum1 which is ultimately the sum of all unique elements.  First Way: TIME O(N) [LeetCode Time 3 ms] SPACE O(N) [Using of Two ArrayLists][LeetCode Memory Uasge : 36.8MB less than 34.90%]  class Solution {     public int sumOfUnique(int[] nums) {         int sum=0; int sum2=0;         ArrayList<Integer> aa=new ArrayList<Integer>(); ArrayList<Integer> ab=new ArrayList<Integer>(); for(int i=0;i<nums.length;i++){ aa.add(nums[i]); sum=sum+aa.get(i); } for(int i=0;i<aa.size();i++){ if(Collections.frequency(aa,aa.get(i))>1){ ab.add(nums[i]); sum2=sum2+nums[i]; } }

K Largest Element LeetCode

 Approach 1: Using ArrayList and Sorting    TIME : O(NLOGN) [LeetCode Time: 5 ms] SPACE: O(N)                [LeetCode Space 39.2MB] class Solution {     public int findKthLargest(int[] arr, int k) {         ArrayList<Integer> aa=new ArrayList<Integer>();         for(int i=0;i<arr.length;i++){             aa.add(arr[i]);         }         Collections.sort(aa);         return (aa.get(aa.size()-k));     } } ========================================================================= Approach 2: Using Priority Queue and getting the peak element TIME: O(NLOGK) [LeetCode Time: 2ms] SPACE: O(K)              [LeetCode Space: 39.8MB] class Solution {     public int findKthLargest(int[] arr, int k) {         PriorityQueue<Integer> q=new PriorityQueue<Integer>(); for(int i=0;i<k;i++){ q.add(arr[i]); } for(int i=k;i<arr.length;i++){ if(q.peek()<arr[i]){ q.remove(); q.add(arr[i]); } }         return q.peek();     } } Thanks for

K largest Elements Geeks For Geeks

 class Solution {     //Function to return k largest elements from an array.     public static ArrayList<Integer> kLargest(int arr[], int n, int k)     {         PriorityQueue <Integer> p=new PriorityQueue<Integer>(); for(int i=0;i<k;i++){ p.add(arr[i]); } for(int i=k;i<n;i++){ if(p.peek()<arr[i]){ p.remove(); p.add(arr[i]); } } ArrayList<Integer> aa=new ArrayList<Integer>(); aa.addAll(p); Collections.sort(aa,Collections.reverseOrder()); return aa;     } } Using Priority Queue Time: O(NLOGK) [Sorting of K elements list] [GFG Time : 3.6/6.8] Space: O(K) [Using ArrayList additionally of size k] {Here we will be adding the first k elements in the priority queue. Then for the next (n-k) elements, we will compare with the peek element of the queue. If the peek element is small then we will remove it from the queue and add the element from an array, and if the peek element is large or equal we will do n

ARRAYDEQUE IMPLEMENTATION IN JAVA WITH GENERICS WITHOUT USING INBUILT FUNCTIONS

USING DOUBLY LINKED LIST  class NodeImplementation<E>{ Node<E> head; Node<E> tail; static class Node<E>{ E data; Node<E> next; Node<E> prev; Node(E data){ this.data=data; this.next=null; this.prev=null; } } public void toAddHead(E data){ Node<E> newNode=new Node(data); if(head==null && tail==null){ System.out.println("Deque is empty"); head=newNode; tail=newNode; } else{ Node temp=head; newNode.prev=temp; temp.next=newNode; newNode.next=null; head=newNode; } } public void toAddTail(E data){ Node<E> newNode=new Node(data); if(head==null && tail==null){ System.out.println("List is Empty."); head=newNode; tail=newNode; } else{ Node temp=tail; newNode.next=temp; temp.prev=newNode; tail=newNode; newNode.prev=null; } } public void toRemoveTail(

Find Digits HackerRank

  class  Result {      /*      * Complete the 'findDigits' function below.      *      * The function is expected to return an INTEGER.      * The function accepts INTEGER n as parameter.      */      public   static   int  findDigits( int  n) {          int  count= 0 ;          int  a= 0 ;         String s=null;         s=String.valueOf(n);          for ( int  i= 0 ;i<s.length();i++){                          a=Integer.valueOf(String.valueOf(s.charAt(i)));              if (a!= 0 ){                  //System.out.println(a);                  if ((n/a)*a==n){ //You can also use modulus operator here n%a                     count++;                 }             }                                                }         System.out.println(count);          return  count;      // Write your code here     } } Thanks for Reading.

Remove Duplicates From Sorted Array LeetCode

TIME : O(N) [leetcode time : 7 ms] SPACE: O(N) [Memory Usage : 40.2 MB] import java.util.*; import java.io.*; import java.util.Set; import java.util.HashSet; class Solution {     public int removeDuplicates(int[] nums) {         int index=0;         int count=0;         int p=nums.length;         Set<Integer> aa=new TreeSet<Integer>();         int n=nums.length;         for(int i=0;i<n;i++){            if(aa.contains(nums[i])){                count++;            }             else                 aa.add(nums[i]);         }         /*for(int b:aa){ System.out.println(b+" "); }*/ Iterator<Integer> it = aa.iterator(); while(it.hasNext()){ nums[index]=it.next(); index++; } p=p-count; /*for(int i=0;i<p;i++){ System.out.println(nums[i]); }*/         return p;              } }

Common Elements Geeks For Geeks

TIME O(NLOGN)  [GFG TIME : 3.2/7.2] SPACE O(N)  class Solution{         public static ArrayList<Integer> common_element(ArrayList<Integer>arr1, ArrayList<Integer>arr2)     {                   int x=0; int y=0; int n=arr1.size(); int m=arr2.size(); Collections.sort(arr1); Collections.sort(arr2); ArrayList<Integer> set=new ArrayList<Integer>(); while(x<n && y<m){ if(arr1.get(x)>arr2.get(y)){ y++; } else if(arr1.get(x)<arr2.get(y)){ x++; } else{ set.add(arr1.get(x)); x++; y++; } } Collections.sort(set); //System.out.println(set); return set;     } } Thanks For Reading.

Count Squares Geeks For Geeks

TIME O(sqrt(N)) [GFG time 0.4/1.4] SPACE O(1) Here we will be traversing till the square root of number and see weather i*i is more than or equal to n.  class Solution {     static int countSquares(int n) {          int a=0; int count=0; for(int i=1;i<Math.sqrt(n);i++){ a=i*i; if(a<n){ count++; } }        //System.out.println(count);         return count;                  // code here     } }; Thanks for Reading.

Value equal to index value Geeks For Geeks

TIME O(N)   [GFG TIME : 2.6/4.4]  SPACE O(N) [Due To Use Of ArrayList ] class Solution {     ArrayList<Integer> valueEqualToIndex(int arr[], int n) {                      ArrayList<Integer> aa=new ArrayList<Integer>(); if(n==1){ if(arr[0]==1){ aa.add(1); return aa; } else{ aa.add(0); return aa; } } else { for(int i=0;i<n;i++){ if(i==arr[i]-1){ aa.add(i+1); } } } return aa;             } } Thanks for reading.

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.println("set3: "); for (Integer i : set3){             System.out.println(i); }*/ ArrayList<Inte

Angry Professor HackerRank Algorithms Implementation

TIME O(N) [ArrayList Traversal] SPACE O(1) [Only Constants Are Used]    public   static  String angryProfessor( int  k, List<Integer> aa) {          int  count= 0 ;          for ( int  i= 0 ;i<aa.size();i++){              if (aa.get(i)<= 0 ){                 count++;             }         }          if (count>=k){             // System.out.println("YES");              return   "NO" ;         }          else {             // System.out.println("NO");              return   "YES" ;         }     } Thanks for reading.

Mini-Max Sum HackerRank Algorithms

TIME O(NLOGN) SPACE  O(1) public   static   void  miniMaxSum(List<Integer> arr) {             Collections.sort(arr);              long  sum2= 0 ;             sum2=Long.valueOf(arr.get( 0 ))+Long.valueOf(arr.get( 1 ))+Long.valueOf(arr.get( 2 ))+Long.valueOf(arr.get( 3 ));             System.out.print(sum2+ " " );                       long  sum1= 0 ;             sum1=Long.valueOf(arr.get( 4 ))+Long.valueOf(arr.get( 1 ))+Long.valueOf(arr.get( 2 ))+Long.valueOf(arr.get( 3 ));             System.out.println(sum1);                           // Write your code here     } } Thanks for Reading.

StairCase HackerRank Algorithms Practice

TIME O(N^2)  SPACE O(1)   public   static   void  staircase( int  n) {          for ( int  i= 0 ;i<n;i++){              for ( int  j= 0 ;j<n;j++){                  if (j<n- 1 -i){                     System.out.print( " " );                 }                  else                     System.out.print( "#" );             }             System.out.println();         }     } Thanks for Reading.

Breaking The Records HackerRank Algorithms

Time O(N) [traversing array] Space O(N) [due to use of arraylist]  import  java.io.*; import  java.math.*; import  java.security.*; import  java.text.*; import  java.util.*; import  java.util.concurrent.*; import  java.util.function.*; import  java.util.regex.*; import  java.util.stream.*; import   static  java.util.stream.Collectors.joining; import   static  java.util.stream.Collectors.toList; class  Result {      /*      * Complete the 'breakingRecords' function below.      *      * The function is expected to return an INTEGER_ARRAY.      * The function accepts INTEGER_ARRAY scores as parameter.      */      public   static  List<Integer> breakingRecords(List<Integer> scores) {         System.out.println(scores);         ArrayList<Integer> aa= new  ArrayList<Integer>();          int  max=scores.get( 0 );          int  count1= 0 ;          int  count2= 0 ;          for ( int  i= 1 ;i<scores.size();i++){              int  a=scores.get(i);            

Java Map Hackkerank

  //Complete this code or write your own from scratch import  java.util.*; import  java.io.*; import  java.util.HashMap; import  java.util.Map.Entry; class  Solution{      public   static   void  main(String arg[])  throws  Exception{                       InputStreamReader r= new  InputStreamReader(System.in);             BufferedReader br= new  BufferedReader(r);            int  n=Integer.valueOf(br.readLine());          if ( 1 <=n && n<= 100000 ){             HashMap<String,String> aa= new  HashMap<String,String>();              for ( int  i= 0 ;i<n;i++){                                  String name=br.readLine();                     String phone=br.readLine();                  if (phone.length()== 8  && phone.charAt( 0 )!= '0' ){                     aa.put(name,phone);                 }             }                           while (n --> 0 ){                 String q;                  while ((q=br.readLine())!=null){                 

Palindrome String Geeks For Geeks (2 Different Approaches)

First Approach  Using StringBuffer Reverse method Time : 0.3 sec / 11.1 sec   class Solution {     int isPlaindrome(String s) {          StringBuffer sb=new StringBuffer(); sb.append(s); String a=(sb.reverse()).toString(); if(a.equals(s)){ //System.out.println("True"); return 1; } else{ //System.out.println("False"); return 0; }                                             // code here     } }; ################################################################################## Another Approach  Comparing each character Time : 0.3 sec / 11.1 sec class Solution {     int isPlaindrome(String s) {                 int start=0; int count=0; int end=s.length()-1; if(s.length()>1){ while(start<end){ char a=s.charAt(start); char b=s.charAt(end); if(a==b){ start++; end--; count++; } else { count=0; break; } } if(count!=0){ //System.out.println

Valid Parenthesis LeetCode

 class Solution {     public boolean isValid(String str) {                         Stack<Character> stack=new Stack<Character>(); for(int i=0;i<str.length();i++){ if(stack.isEmpty()){ stack.push(str.charAt(i)); } else if(stack.peek()=='{' && str.charAt(i)=='}'){ stack.pop(); } else if(stack.peek()=='[' && str.charAt(i)==']'){ stack.pop(); } else if(stack.peek()=='(' && str.charAt(i)==')'){ stack.pop(); } else{ stack.push(str.charAt(i)); } } if(stack.isEmpty()){ return true; } else{ return false; }     } }

Reverse String LeetCode JAVA 2 Different Solutions

 public static void main(String arg[]){ Scanner sc=new Scanner(System.in); System.out.println("Enter total number of characters in string"); int n=sc.nextInt(); char arr[]=new char[n]; for(int i=0;i<n;i++){ arr[i]=sc.next().charAt(0); ; } for(int i=0;i<n;i++){ System.out.print(arr[i]+" "); } /* Approach 1 : Swapping elements till half. Leetcode stats: Runtime 112 seconds, Memory 42.4 MB.  int start=0; int end=arr.length-1; while(start<end){ char temp; temp=arr[start]; arr[start]=arr[end]; arr[end]=temp; start++; end--; } for(int i=0;i<n;i++){ System.out.print(arr[i]+" "); } */ //============================================================ /* Approach 2 : Using the StringBuffer reverse method. Leetcode stats: Runtime 114 seconds, Memory 41.8 MB.  String str = new String(arr); StringBuffer sb=new StringBu

Parenthesis Checker Geeks For Geeks Total Time Complexity O(String length) Space O(1) constant

Solution 1: Brute Force (Accuracy: 100% , Time 0.5/1.6 )  static boolean ispar(String str)     {                   int c1=0; int c2=0; int c3=0; int c4=0; int c5=0; int c6=0; int c7=0; if((str.length()/2)*2==str.length()){//Checking weather string length is even or not //System.out.println("Confirmation that this string length is even.............."); for(int i=0;i<str.length();i++){ if(str.charAt(i)=='{'){ c1++; } else if(str.charAt(i)=='}'){ c2++; } else if(str.charAt(i)=='['){ c3++; } else if(str.charAt(i)==']'){ c4++; } else if(str.charAt(i)=='('){ c5++; } else if(str.charAt(i)==')'){ c6++; } else{ c7++; break; } } if((c1==c2) && (c3==c4) && (c5==c6)){ //System.out.println("Confirmed that for each charater there is a close brackett. ")

Check If N and its Double Exist LeetCode

 class Solution {     public boolean checkIfExist(int[] arr) {         int n=arr.length;         int count1=0; int count2=0; ArrayList<Integer>set=new ArrayList<Integer>(); for(int i=0;i<n;i++){ set.add(arr[i]); } for(int i=0;i<n;i++){ if(set.contains(2*arr[i])){ if(arr[i]==0){ count1++; } else{ count2++; break; } } } if(count2!=0 && count1==0){ //System.out.println("true");             return true; } else if(count2!=0 && count1!=0){ //System.out.println("true");             return true; } else if(count2==0 && count1!=0){ if(Collections.frequency(set,0)>1){ //System.out.println("true");                 return true;             }              else{ //System.out.println("false");                 return false;             } } else{ //System.out.println("false");             retu