Posts

Showing posts from January, 2022

Reverse Words In A Given String Geeks For Geeks

 Problem Link: Its also Problem Of Day 29 January https://practice.geeksforgeeks.org/problems/reverse-words-in-a-given-string5459/1 Solution: class Solution  {     //Function to reverse words in a given string.     String reverseWords(String s)     {                     StringBuilder sb=new StringBuilder();        Stack<String>stack=new Stack<String>();         for(int i=0;i<s.length();i++){             if(s.charAt(i)=='.'){                 stack.add(sb.toString());                 sb.setLength(0);             }             else{                 sb.append(s.charAt(i));             }         }         stack.add(sb.toString());         sb.setLength(0);                  while(!stack.isEmpty()){             sb.append(stack.pop());             sb.append('.');         }         sb.setLength(sb.length()-1);         return sb.toString();                      } } Time Complexity: O(String Length)[GFG Time:0.7/1.8] Space Complexity: O(1)[Only A String is used. Not

Set Mismatch LeetCode

Problem Link: https://leetcode.com/problems/set-mismatch/   Solution 1: int sum=0;         int sum1=0;         HashSet<Integer>set=new HashSet<Integer>();         for(int i=0;i<nums.length;i++){            set.add(nums[i]);             sum1=sum1+nums[i];         }                               for(int a:set){             sum=sum+a;         }                  int arr[]=new int[2];         arr[0]=sum1-sum;         int sum2=(nums.length*(nums.length+1))/2;         arr[01]=sum2-sum;                  return arr; ---------------------------------------------------------------------------------------------------------------------------- Solution 2: Arrays.sort(nums);         Stack<Integer>stack=new Stack<Integer>();         int a=0;         int sum=0;                 for(int i=0;i<nums.length;i++){             if(stack.isEmpty()){                 stack.push(nums[i]);             }             else{                 if(stack.peek()==nums[i]){                     a=

Counting Bits LeetCode

 Problem Link: https://leetcode.com/problems/counting-bits/ Solution 1 : public int cal(int n){          int count=0;          while(n>0){              n=n&(n-1);              ++count;          }          return count;      }               public int[] countBits(int n) {         int arr[]=new int[n+1];         for(int i=0;i<=n;i++){             arr[i]=cal(i);         }         return arr;     } Time Complexity:O(N*number of set bits in number)[LeetCode Time: 2ms faster than 68.42%] Space Complexity:O(1)[No array or any other data structure is used.] Auxillary Space:O(N) [An additional array is used which will be returned later.] LeetCode Memory:43MB less than 84.07%. Total Test Cases:15 Approach : Here we will send every element to the cal function as a parameter and later using the Brian-Kerningam algorithm we will calculate the number of set bits in a number. The count of set bits will be then stored in an array against that particular index and that array will be returned

Print 1 To N Without Using Loops Geeks For Geeks

 Problem Link: https://practice.geeksforgeeks.org/problems/print-1-to-n-without-using-loops3621/1 Solution: class Solution{     static void printTillN(int n){         if(n==0){             return ;         }         else{             printTillN(n-1);             System.out.print(n+" ");         }         // code here     } } Time Complexity: O(N)[GFG Time: 0.5/2.0] Space Complexity:O(1) Auxillary Space:O(N)[Recusive Stack of max N+1 functional calls][Non-Tail Recursive] Total Test Cases: 200 Approach: We, Will, apply for Recursion. Here base condition will be when n==0 else we will make a recursive call and print number later. "Thanks For Reading.😇" "Share Further To Increase Knowledge Treasure.😊" 

Rearrange A String Geeks For Geeks

 Problem Link: https://practice.geeksforgeeks.org/problems/rearrange-a-string4100/1 Solution: class Solution {     public String arrangeString(String s)         {            PriorityQueue<Character>set=new PriorityQueue<Character>();             int res=0;            for(int i=0;i<s.length();i++){                if(Character.isDigit(s.charAt(i))){                     res=res+Character.getNumericValue(s.charAt(i));                  }                else{                    set.add(s.charAt(i));                }            }            StringBuilder sb=new StringBuilder();           while(!set.isEmpty()){                sb.append(set.remove());            }            sb.append(res);            return sb.toString();                     } } Time Complexity:O(N)[N=length of string][GFG Time:1.0/13.1] Space Complexity:O(1) Auxillary Space:O(N)[PriorityQueue of characters present in the string. The worst-case string will consist of all characters, not digits. But on average ca

Sort Integers By The Number Of 1 Bits LeetCode

 Problem Link: https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/ Solution: public int cal(int n){         int count=0;         while(n>0){             n=n&(n-1);             ++count;         }         return count;     }               public int[] sortByBits(int[] arr) {         TreeMap<Integer,PriorityQueue<Integer>>map=new TreeMap<Integer,PriorityQueue<Integer>>();                  for(int i=0;i<arr.length;i++){            if(map.containsKey(cal(arr[i]))){               PriorityQueue<Integer>pq=map.get(cal(arr[i]));                pq.add(arr[i]);                map.put(cal(arr[i]),pq);                           }             else{                 PriorityQueue<Integer>pq=new PriorityQueue<Integer>();                 pq.add(arr[i]);                 map.put(cal(arr[i]),pq);                             }         }         //System.out.println(map);         int arr1[]=new int[arr.length];         int index=0;        f

Power Set Geeks For Geeks

 Problem Link https://practice.geeksforgeeks.org/problems/power-set4302/1/ Solution:  ArrayList<String>aa=new ArrayList<String>();         StringBuilder sb=new StringBuilder();         for(int i=01;i<(int)Math.pow(2,s.length());i++){             for(int j=0;j<s.length();j++){                 if((i&(1<<j))!=0){                     sb.append(s.charAt(j));                 }                              }             aa.add(sb.toString());             sb.setLength(0);         }                 Collections.sort(aa);                  return aa; TIME COMPLEXITY:O(N^2)[GFG Time:1.9/3.9] SPACE COMPLEXITY: O(1) AUXILLARY SPACE: O(2*N) TOTAL TEST CASES:90 APPROACH: 1.Here we will use binary representation to store characters of the string. Imagine it as  for string abc for index 0 it is c for 1 it is b and for 2 it is a. In map form: 0->a  1->b 2->c 2. Now we know that the maximum powerset can be 2^n. So for the 2^n powerset, there will be different 2^n  combi

Flipping Bits HackerRank

Problem Link: https://www.hackerrank.com/challenges/flipping-bits/problem Solution:   class  Result {      public   static   long  flippingBits( long  n) {                  long  n1=~n;         String s=Long.toBinaryString(n1);          //System.out.println(s);          double  res= 0.0 ;          for ( int  i= 0 ;i< 32 ;i++){              if (s.charAt( 63 -i)== '1' ){                 res=res+Math.pow( 2 ,i);             }         }                   return  ( long )res;     } } Time Complexity:O(logn) ie more than O(1) and about O(log(2^31-1))(max value as n can be 2^31-1). Actually when we call this function then it will find out its binary and at the instant of time maximum recursive calls will be logn. So that's why its time complexity will be O(logn). Space Complexity:O(1) Auxillary Space:O(1) Approach: 1. First we will find out the negation of number. 2. Here First we will convert the negated number to binary value using the Long.toBinaryString() function. 3. Then

Maximizing XOR Hacker Rank

 Problem Link: https://www.hackerrank.com/challenges/maximizing-xor/problem Solution: class  Result {      /*      * Complete the 'maximizingXor' function below.      *      * The function is expected to return an INTEGER.      * The function accepts the following parameters:      *  1. INTEGER l      *  2. INTEGER r      */      public   static   int  maximizingXor( int  l,  int  r) {         PriorityQueue<Integer>pq= new  PriorityQueue<Integer>(Collections.reverseOrder());                   for ( int  i=l;i<r;i++){              for ( int  j=l+ 1 ;j<=r;j++){                 pq.add(i^j);             }         }          return  pq.peek();     } } TIME COMPLEXITY:O(N^2)[N=r-l] SPACE COMPLEXITY:O(1) AUXILLARY SPACE:O(N)[Using Priority Queue of N size] APPROACH: Here we will traverse the whole array and simultaneously store values in the priority queue. Later we remove the peek value of pq. Peek value of queue will be maximum because in declaration we have said t

Two Numbers With Odd Occurrences Geeks For Geeks

 Problem Link: https://practice.geeksforgeeks.org/problems/two-numbers-with-odd-occurrences5846/1/ Solution 1: Using XOR Operator class Solution {     public int[] twoOddNum(int arr[], int n)     {         int xor=0;       for(int i=0;i<arr.length;i++){           xor=xor^arr[i];       }       int sn=(xor&(~(xor-1)));       int sum1=0;       int sum2=0;       for(int i=0;i<arr.length;i++){           if((arr[i]&sn)!=0){               sum1=sum1^arr[i];           }           else{               sum2=sum2^arr[i];           }       }       int arr1[]=new int[2];       arr1[0]=Math.max(sum1,sum2);       arr1[1]=Math.min(sum2,sum1);       return arr1;     } } TIME:O(N)[GFG Time:0.9/7.1] SPACE:O(N)[Array of size n is in usage] AUXILLARY SPACE: More than O(1) and less than O(N) (Precisely: O(2+1) ie O(3))[Array of fixed size 2 is in usage (O(2)) and constants are used O(1)]. TOTAL TEST CASES:10035  APPROACH: 1. Here In question, it is given two numbers will be distinct while all ot

Number of 1 bits GFG Practice

Problem Link: https://practice.geeksforgeeks.org/problems/set-bits0143/1 Solution: int count=0;         int a=0;         while(n!=0){             a=n%2;             if(a==1){                 ++count;             }             n=n/2;               //n=n>>1 (you can use this statement also in place of n=n/2 as every time n is divided by 2)         }         return count; TIME:O(Total bits in given number)[GFG Time:0.2/1.3] SPACE:O(1) AUXILLARY SPACE:O(1) Total Test Cases:150 Approach : Here we will convert the number into binary and check for each digit from last. If the digit is 1 then increment the counter variable count else value of the count variable remains the same. Return count; -------------------------------------------------------------------------------------------------------------------------- int count=0;         int a=0;         while(n!=0){                          if((n&1)==1){                 ++count;             }             //n=n/2;             n=n>>

Count Digits in A Factorial Geeks For Geeks

 Problem Link: https://practice.geeksforgeeks.org/problems/count-digits-in-a-factorial3957/1# Solution: class Solution{     static int facDigits(int n){         double a=0.0;         for(int i=2;i<=n;i++){             a=a+Math.log10(i);         }        a=a+1;         return (int)a;     } } TIME:O(N)[Here we are traversing the whole array once starting from 2 and taking the sum of all log values of numbers.][GFG Time:0.1/1.2] SPACE:O(1)[No array or any memory consuming data structure is used] AUXILLARY SPACE:O(1)[No extra space required] Total Test Cases:290 APPROACH: 1.We know that log(a*b)=log(a)+log(b) and for factorial, we can write, factorial of number n = 1*2*3*4*.......................*n and log(1*2*3*4*.......................*n)=log(1)+log(2)+log(3)+log(4)+......................................+log(n) Using this approach instead of multiplying every number we will directly calculate the sum of log values of every number coming between 2 to n. if we see log values are in deci

Absolute Value Geeks For Geeks

 Problem Link: Absolute Value | Practice | GeeksforGeeks Solution: class Solution {     public int absolute(int I) {         return Math.abs(I);     } } Time:O(1) Space:O(1) Auxillary Space:O(1)

LCM and GCD Geeks For Geeks

 Problem Link: https://practice.geeksforgeeks.org/problems/lcm-and-gcd4516/1/ Solution:  class Solution {     static Long fun(Long a, Long b){         if(b==0){             return a;         }         else{             return fun(b,a%b);         }     }      static Long[] lcmAndGcd(Long a , Long b) {             Long c=fun(a,b);         Long arr[]=new Long[2];         Long d=(a*b)/c;             arr[0]=d;             arr[1]=c;         // System.out.println(arr[0]+" "+arr[1]);         return arr;      } }; TIME:O(log(min(a,b)))[GFG Time:0.1/1.5] SPACE:O(1)[Array arr of size 2 is created.] AUXILLARY SPACE:O(Logn)[Log n calls are made till the parameter b becomes 0 and at any moment maximum logn calls can be stored in a stack.] Total Test Cases:102 Approach: For HCF: Here we will use recursion. Every time we will pass two parameters a and b (given numbers) but the concept use will be modular division, ie a%b as the second parameter. This will reduce the value of second parameter

Factorial Number Geeks For Geeks

Problem Link: https://practice.geeksforgeeks.org/problems/factorial-number2446/1 Solution : class Solution{     static int isFactorial(int n) {         //code here         int val=1;         int index=1;                 while(val<n){                        val=val*index;            index++;        }        if(val==n){            return 1;        }        else{            return 0;        }              } } TIME:O(Log n)[Every Time multiplication with 2][GFG Time:0.2/1.4] SPACE:O(1) AUXILLARY SPACE:O(1)[Only Constants] Total Test Cases:11555 Approach:  We will apply the while loop and see whether the value(val) is less than a given number.(n) The loop will break only when the value(val) is more or equal which we will check later. If the value(val) is equal then yes the number is factorial and returns 1 else returns 0. Thanks For Reading.😇 "Share Further To Increase Knowledge Treasure".😊

Count Digits Geeks For Geeks

 Problem Link: https://practice.geeksforgeeks.org/problems/count-digits5716/1 Solution: class Solution{     static int evenlyDivides(int n){                int num=n;         int count=0;         int a=0;         while(n!=0){             a=n%10;             if(a!=0){                 if(num%a==0){                     ++count;                 }             }             n=n/10;         }        // System.out.println(count);         return count;     } } TIME:O(logn)[GFG Time :0.1/1.2] SPACE:O(1)[No Storage only constants] AUXILLARY SPACE:O(1)[No Additional Space is Used] TOTAL TEST CASES:285 APPROACH: Here we will see every digit by taking number%10 whether it's dividing the number or not. If yes we add count else no increase in the value of the count. Here we have applied the condition of a!=0 inside loop to make sure that division does not occur by 0. ex if the number is 1002 then the first digit is 2 since it divides 1002 so the count value increases to 1. Now next digit is 0 whic

Even Odd GeeksForGeeks

 Problem Link: https://practice.geeksforgeeks.org/problems/even-odd/1# Solution: class Solution{     public void evenOdd(int a, int b){         int a1=a&1;         if(a1==1){             System.out.println(b);             System.out.println(a);         }         else{              System.out.println(a);             System.out.println(b);         }     } } TIME:O(1)[Geeks For Geeks Time: 0.1/1.3] SPACE:O(1) Approach: Since in question only they have asked to print even number before than odd number, so it is a guarantee that among two numbers they provide one will be even one will be odd.  So if we check for one number only the other number will be reverse of that. That's why here we checked for number a and if it is even then b will be odd and vice versa. For a to be even, it should return output to 0 once masked with 1. (Masking approach: Actually, this masking approach deals with the bits. We can do masking through and, or, xor operation.  example:  if the number is 5 then bi

Find Unique Element Geeks For Geeks

Problem Link: https://practice.geeksforgeeks.org/problems/find-unique-element2632/1  Solution :  HashMap<Integer,Integer>map=new HashMap<Integer,Integer>();         for(int i=0;i<n;i++){             if(map.containsKey(a[i])){                 map.put(a[i],map.get(a[i])+1);             }             else{                 map.put(a[i],1);             }         }         int c=0;         for(int a1:map.keySet()){             int b=map.get(a1);             if(b%k!=0){                 c=a1;                 break;             }         }         return c; Time:O(N)[Traversal of given array][GFG Time:1/10.3] Space:O(N)[Storing all entries in hashmap but the size of the map will be less than n.] Approach: 1. Traverse the given array and store the elements in the map with their frequency. 2. Apply for each loop on the key set of map and see whether the frequency of the element is divisible by k or not. If not then break the loop and print the key ie element. 3. Return element. &qu

Substring Of Size Three with Distinct Characters LeetCode

 Problem Link: https://leetcode.com/problems/substrings-of-size-three-with-distinct-characters/ Solution: class Solution {     public int countGoodSubstrings(String s) {             ArrayDeque<Character>aa=new ArrayDeque<Character>();             if(s.length()<3){                 return 0;             }         else{             int count=0;             aa.addLast(s.charAt(0));              aa.addLast(s.charAt(01));              aa.addLast(s.charAt(02));             if(s.charAt(0)!=s.charAt(1) && s.charAt(1)!=s.charAt(2) && s.charAt(0)!=s.charAt(2)){                 count++;             }             //System.out.println(aa);             boolean flag=false;             for(int i=3;i<s.length();i++){                 aa.removeFirst();                 //System.out.println(aa);                 aa.addLast(s.charAt(i));                 char a=aa.removeLast();                 char b=aa.removeLast();                 char c=aa.removeLast();                  if(