Posts

Showing posts from August, 2021

Minimum Sum Partition Geeks For Geeks

 class Solution { public int minDifference(int arr[], int n)  {   int sum=0;     ArrayList<Integer>aa=new ArrayList<Integer>();     for(int i=0;i<n;i++){         sum=sum+arr[i];     }         boolean t[][]=new boolean[n+1][sum+1];     for(int i=0;i<n+1;i++){         for(int j=0;j<sum+1;j++){             if(i==0){                 t[i][j]=false;             }             if(j==0){                 t[i][j]=true;             }         }     }          for(int i=1;i<n+1;i++){         for(int j=1;j<sum+1;j++){             if(arr[i-1]>j){                 t[i][j]=t[i-1][j];             }             else{                 t[i][j]=(t[i-1][j] || t[i-1][j-arr[i-1]]);             }         }     }         for(int j=0;j<(sum)/2 + 1 ;j++){          if(t[n][j]==true){               aa.add(j);          }     }         int min=Math.abs(sum-2*aa.get(0));     for(int i=1;i<aa.size();i++){    

Perfect Sum Problem Geeks for Geeks

 class Solution{ public int perfectSum(int arr[],int n, int sum)  {      int t[][]=new int[n+1][sum+1];     for(int i=0;i<n+1;i++){         for(int j=0;j<sum+1;j++){             if(i==0){                 t[i][j]=0;             }             if(j==0){                 t[i][j]=1;             }         }     }     int count=0;     for(int i=1;i<n+1;i++){         for(int j=1;j<sum+1;j++){             if(arr[i-1]>j){                 t[i][j]=t[i-1][j] % 1000000007;             }             else{                 t[i][j]=((t[i-1][j-arr[i-1]]) + (t[i-1][j])) %1000000007;                             }         }     }               return (t[n][sum])%1000000007; }  } Problem Statement: Here we have to count the pairs which have sums equal to a given value. Approach: Here we will initialize the int array with 0 and 1 for two cases. 1.It is not possible that given array is empty and sum is finite(except 0) so for all i==0 t[i]

Partition Equal Subset Sum Geeks For Geeks and LeetCode

 class Solution{     static int equalPartition(int n, int arr[])     {         int sum=0;         for(int i=0;i<n;i++){             sum=sum+arr[i];         }         if(sum%2!=0){             return 0;         }         else{             int t[][]=new int[n+1][sum+1];             sum=sum/2;             for(int i=0;i<n+1;i++){                 for(int j=0;j<sum+1;j++){                     if(i==0){                         t[i][j]=0;                     }                     if(j==0){                         t[i][j]=1;                     }                                      }             }             for(int i=1;i<n+1;i++){                 for(int j=1;j<sum+1;j++){                     if(arr[i-1]>j){                         t[i][j]=t[i-1][j];                     }                     else{                         t[i][j]=Integer.max((t[i-1][j-arr[i-1]]),(t[i-1][j]));                     }                 }             }             return t[n][sum];         }     } }

Subset Sum Problem Geeks For Geeks

 class Solution{     static boolean isSubsetSum(int n, int arr[], int sum){         boolean [][] t=new boolean[n+1][sum+1];         for(int i=0;i<n+1;i++){             for(int j=0;j<sum+1;j++){                 if(i==0){                     t[i][j]=false;                 }                 if(j==0){                     t[i][j]=true;                 }             }         }                  for(int i=1;i<n+1;i++){             for(int j=1;j<sum+1;j++){                 if(arr[i-1]>j){                     t[i][j]=t[i-1][j];                 }                 else{                     t[i][j]=(t[i-1][j-arr[i-1]]) || (t[i-1][j]);                 }             }         }         return t[n][sum];     } } APPROACH: Dynamic Programming Here we will first initialize boolean matrix t of size n+1 and sum+1 with true or false. If the sum is 0 then the size of the array does not matter and hence true will be stored. If the sum is non zero but the size of an array is non zero then it is

Minimum Distances HackerRank

  class  Result {      /*      * Complete the 'minimumDistances' function below.      *      * The function is expected to return an INTEGER.      * The function accepts INTEGER_ARRAY a as parameter.      */      public   static   int  minimumDistances(List<Integer> a) {         HashMap<Integer,Integer> map= new  HashMap<Integer,Integer>();         ArrayList<Integer>aa= new  ArrayList<Integer>();          for ( int  i= 0 ;i<a.size();i++){              if (!map.containsKey(a.get(i))){                 map.put(a.get(i),i);             }              else {                  int  b=map.get(a.get(i));                 aa.add(i-b);             }         }          if (aa.size()== 0 ){              return  - 1 ;         }          else            return  Collections.min(aa);     } } Approach: Here we will use a HashMap and an ArrayList. In HashMap we will store unique elements as keys and with their value as their incoming index in the given ArrayList a.

Remove Duplicate Element from sorted Linked List Geeks For Geeks

 class GfG {     //Function to remove duplicates from sorted linked list.     Node removeDuplicates(Node head)     {     Node temp=head;     Node newNode;/*created in manner it wil help in reference adjustments*/     while(temp.next!=null){         int a=temp.data;         int b=temp.next.data;         if(a==b){            newNode=temp.next.next;            temp.next.next=null;            temp.next=newNode;                      }         else{             temp=temp.next;         }     }     return head;     } } Approach:  Here we will take a node named temp which will point to the node head. This temp node will traverse till it reaches the last node at which temp.next==null. If we found duplicates then the reference of the middle node will be null and the previous node will point to the next node reference. In such a manner all duplicate nodes will be removed. If no duplicates then iterations will be there in the forwarding direction. TIME:O(N)[Geeks For

01Knapsack by Top Down Approach

 import java.util.Scanner; import java.util.*; class KnapsackImplementation{ int[][] t; int opt; int n; int k; public KnapsackImplementation(int k,int n){ this.n=n; this.k=k; opt=0; this.t=new int[n+1][k+1]; }    public int knapsack(int w[],int val[], int k,int n){ for(int i=0;i<n+1;i++){ for(int j=0;j<k+1;j++){ if(i==0||j==0){ t[i][j]=0; } } }  for(int i=1;i<n+1;i++){ for(int j=1;j<k+1;j++){ if(w[i-1]>j){ t[i][j]=t[i-1][j]; } else{ t[i][j]=Integer.max((val[i-1]+t[i-1][j-w[i-1]]),t[i-1][j]); } } } return t[n][k]; } } class O1KnapsackbyTopDown{ public static void main(String arg[]){ Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int w[]=new int[n]; int val[]=new int[n]; System.out.println("enter elements of weight array."); for(int i=0;i<n;i++){ w[i]=sc.nextInt(); } System.out.printl

01 Knapsack Problem by Memiozation

 import java.util.Scanner; import java.util.*; class KnapsackImplementation{ static int[][] t; int opt; int n; int k; public KnapsackImplementation(int k,int n){ this.n=n; this.k=k; opt=0; this.t=new int[n+1][k+1];   for(int i = 0; i < n + 1; i++){  for(int j = 0; j < k + 1; j++)   t[i][j] = -1;      } } public int knapsack(int w[],int val[], int k,int n){   if(n==0 || k==0){ opt=0; return 0; } if(t[n][k]!=-1){ opt=t[n][k]; System.out.println("Element existing  is: "+t[n][k]); return t[n][k]; } else { if(w[n-1]<=k){ System.out.println("Weight is less."); System.out.println("NOw we have choice wither to include or not."); t[n][k]=Integer.max((val[n-1]+knapsack(w,val,k-w[n-1],n-1)),(knapsack(w,val,k,n-1))); System.out.println("Element max is: "+t[n][k]); return t[n][k]; } else{ System.out.printl

Kadane Algorithm Geeks For Geeks

  class Solution{     // arr: input array     // n: size of array     //Function to find the sum of contiguous subarray with maximum sum.     int maxSubarraySum(int arr[], int n){         int count=0;         int max1=arr[0];          int max=0;         for(int i=0;i<n;i++){             if(arr[i]<0){                 count++;             }         }         if(count==n){                          for(int i=1;i<n;i++){                 if(arr[i]>max1){                     max1=arr[i];                 }             }             return max1;         }         else{             int sum=0;                         max=arr[0];             for(int i=0;i<n;i++){                 sum=sum+arr[i];                 if(sum<0){                     sum=0;                 }                 if(sum>max){                     max=sum;                 }             }         }         return max;              }      } Approach: Here we will traverse the array and we will see whether all ele

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++;             }         }         aa.add(arr.size());         return Collections.max(aa); APPROACH: Here we will add the elements of string one by one in ArrayDeque and will increase the value of count simultaneously. If an element exists prior in the deque then we will store the value of count up to that element in ArrayList and empty or clear the array deque. Now our iteration starts from the next element which means now we will start from the second element.  Iteration starts f

Repeated String HackerRank

  public   static   long  repeatedString(String s,  long  t) {                            long  n=s.length();                  long  count= 0l ;          for ( int  i= 0 ;i<n;i++){              if (s.charAt(i)== 'a' ){                 count++;             }         }                  long  q=t/n;         count=q*count;          long  r=t%n;                   for ( int  i= 0 ;i<( int )r;i++){              if (s.charAt(i)== 'a' ){                 count++;             }         }                 return  count;     } Approach: Here first for the input string we will calculate the number of a's (store in long l). Then we will see how many times the same string will be covered in the input length (long c=dividing input length by l) and we will get the number of a's till now by multiplying c with l (m=c*l). Now by applying modulus operation (long r=input length% l). Later traversing up to r we will see if the character is a then m value will increase. Hence we wi

Valid Palindrome LeetCode

 Approach 1: Using Inbuilt reverse() Function on StringBuffer Object.           s=s.replaceAll("[^a-zA-Z0-9]", "");//replace all non alphanumeric characters with empty string.         s=s.toLowerCase();                 StringBuffer sb=new StringBuffer();         sb.append(s);         String s2=sb.reverse().toString();         if(s.equals(s2)){             return true;         }         else{             return false;         } Time: O(N) [As do swapping of characters by iterating up to half of the length of  given string length.][LeetCode Time: 23 ms beats 30.26% ] Space: O(Length of String)[LeetCode Memory: 40MB beats 32.77%] ========================================================================= Approach 2: Using Two Pointers           s=s.replaceAll("[^a-zA-Z0-9]", "");         s=s.toLowerCase();                  int start=0;         int count=0;         int end=s.length()-1;         if(start==end || s.length()==0){             return true;

Winner Of An Election Geeks For Geeks

 class Solution {     //Function to return the name of candidate that received maximum votes.     public static String[] winner(String arr[], int n)     {         TreeMap<String,Integer> map=new TreeMap<String,Integer>();         for(int i=0;i<arr.length;i++){             if(map.containsKey(arr[i])){                 map.put(arr[i],map.get(arr[i])+1);             }             else                 map.put(arr[i],1);         } PriorityQueue<Integer> pq=new PriorityQueue<Integer>(); int a=0; for (Map.Entry<String, Integer> entry : map.entrySet()) { a=entry.getValue(); if(pq.isEmpty()){ pq.add(a); } else{ if(pq.peek()<a){ pq.remove(); pq.add(a); } } } String arr2[]=new String[2]; for (Map.Entry<String, Integer> entry1 : map.entrySet()) { int a1=entry1.getValue(); if(a1==pq.peek()){ arr2[0]=entry1.getKey(); arr2[1]=String.valueOf(a1); break

Java Collection | Set 3 (HashMap) Part-1 Geeks For Geeks

 class Solution{     static int map(int n, String keys[], int arr[], String s)     {         HashMap<String,Integer> map1=new HashMap<String,Integer>();                  for(int i=0;i<keys.length;i++){             map1.put(keys[i],arr[i]);         }         int val=0;         if(map1.containsKey(s)){            val=map1.get(s);         }         else{             val=-1;         }         return val;                } } Time: O(Length of string array or key array) [GFG Time: 0.2/2.2] Space: O(n) Thanks for Reading.😇

Remove Consecutive Characters Geeks For Geeks

 class Solution{     public String removeConsecutiveCharacter(String s){         Stack<Character> stack=new Stack<Character>(); int count=0; for(int i=0;i<s.length();i++){ if(stack.isEmpty()==true){ stack.push(s.charAt(i)); } else if(String.valueOf(stack.peek()).equals(String.valueOf(s.charAt(i)))){ count++; } else stack.push(s.charAt(i)); } //System.out.println(stack); StringBuffer sb=new StringBuffer(); while(!stack.isEmpty()){     sb.append(stack.pop()); } sb.reverse(); return sb.toString();     } } APPROACH: Here we will use a stack. We will add the elements of string in the stack in such a manner that if an element is equal to the peek of the stack it won't get added to the stack otherwise it will be added in the stack. I have used a counter variable also which will count the number of times different duplicate elements were traversed. After that, we will add elements of the stack into Stri

Median Of Two Sorted Arrays LeetCode And Geeks For Geeks

 class Solution {     public double findMedianSortedArrays(int[] nums1, int[] nums2) {         int x=0;         int y=0;         int n=nums1.length;         int m=nums2.length;         PriorityQueue<Integer> pq=new PriorityQueue<Integer>();         while(x<nums1.length && y<nums2.length){             if(nums1[x]<nums2[y]){                 pq.add(nums1[x]);                 x++;             }             else if(nums1[x]>nums2[y]){                 pq.add(nums2[y]);                 y++;             }             else{                 pq.add(nums1[x]);                 pq.add(nums2[y]);                 x++;                 y++;             }         }             for(;x<n;x++){                 pq.add(nums1[x]);             }             for(;y<m;y++){                 pq.add(nums2[y]);             }             ArrayList<Integer>aa=new ArrayList<Integer>();             aa.addAll(pq);             int a=aa.size();             double median=0.0;

Reverse A String Using Stack Geeks For Geeks

 class Solution {          public String reverse(String s){         Stack<Character> stack=new Stack<Character>(); for(int i=0;i<s.length();i++){ stack.push(s.charAt(i)); } StringBuffer sb=new StringBuffer(); while(!stack.isEmpty()){ sb.append(stack.pop()); } String s1=sb.toString(); return s1;     } } Approach: We will add all the elements of the given string into the stack. After that, we will apply a while loop which will run till the stack becomes empty and the object of StringBuffer will append those characters. In the end, we will convert the string buffer object to a string.  TIME: O(N) [here N is the length of given string][GFG time: 0.2/1.5] SPACE: O(1) [here we are simply appending the characters in the last and later converting object of StringBuffer into a string.] Thanks for Reading 😇.

Merge Without Using Extra Space Geeks For Geeks

class Solution {     public void merge(int arr1[], int arr2[], int n, int m) {                          PriorityQueue<Integer> pq=new PriorityQueue<Integer>(); int x=0; int y=0; while(x<n && y<m){ if(arr1[x]<arr2[y]){ pq.add(arr1[x]); x++; } else if(arr1[x]==arr2[y]){ pq.add(arr1[x]); pq.add(arr2[y]); x++; y++; } else{ pq.add(arr2[y]); y++; } } for(;x<n;x++){ pq.add(arr1[x]); } for(;y<m;y++){ pq.add(arr2[y]); } int index=0; while(index<n){ arr1[index++]=pq.remove(); } index=0; while(index<m){ arr2[index++]=pq.remove(); }     } } Approach: Here we will traverse both the list together and see for smaller element in both lists and simultaneously add it to the priority queue. Value for the pointer will be increased for the list whose elements get add up in the queue. If the same value elements are there then th

Array Formation HackerEarth

  import java . util .*; import java . util . LinkedList ; import java . util . Queue ;   class PrimeChecker { Queue < Integer > q ; Stack < Integer > stack ; Stack < Integer > stack1 ; public PrimeChecker (){ q = new LinkedList < Integer >(); stack = new Stack < Integer >(); } public void isPrime ( int num ){ boolean b = true ; for ( int i = 2 ; i <= num / 2 ; i ++) { int temp = num % i ; if ( temp == 0 ) { b = false ; break ; } } if ( b ){ //System.out.println(num + " is a Prime Number"); q . add ( num ); } else { //System.out.println(num + " is not a Prime Number"); stack . push ( num ); } } // This is checked so that we can skip // middle five numbers in below loop public void toPrint (){ //System.out.println(/*"Queue is: "+*/ q); //System.out.println(/*&quo