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++){       ...

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;             }             el...

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;                     }           ...

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

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 (!ma...

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 h...

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.o...

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.o...

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];                 }      ...

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++;             }         }       ...

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;     ...

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: ...

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.ad...

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

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{ ...

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

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(/*...