Notes
Notes
1)Reverse an array
1. Objects of String are immutable.
2. String class in Java does not have reverse() method, however StringBuilder class
has built in reverse() method.
3. StringBuilder class do not have toCharArray() method, while String class does
have toCharArray() method.
StringBuilder ans=new StringBuilder();
ans.append(str);
ans.reverse();
return ans.toString();
4. char temp1=str.charAt(start);
char temp2=str.charAt(end);
string.setCharAt(end, temp1);
string.setCharAt(start,temp2);
===================================================================================
===============================================
2)Maximum and minimum of an array using minimum number of comparisons
To get the minimum or maximum value from the array we can use the Collections.
min() and Collections. max() methods
===================================================================================
====================================================
3)to find kth min in array
Arrays.sort(arr, 1, 5);(nlogn)
other aolutions is:Quick select O(n)average case and O(n2) worst case
min heap or max heap in java (n+klogn)
===================================================================================
=================================================
4)Sort an array of 0s, 1s and 2s
check segregate 0 and 1s also
swap in single line:
1. y = (x+y) - (x=y);
2.x = x ^ y ^ (y = x);
without temporoary variable
3.
first = first - second;
second = first + second;
first = second - first;
dutch flag algorith to sort color of 3 flags using single loop
public static void sort012(int a[], int n)
{
// code here
//three pointers
int l=0,m=0,h=n-1;
while(m<=h)
{
if(a[m]==0)
{
a[m]=(a[m]+a[l])-(a[l]=a[m]);
l++;
m++;
}
else if(m<=h && a[m]==1)
{
m++;
}
else if(m<=h && a[m]==2)
{
a[h]=(a[m]+a[h])-(a[m]=a[h]);
h--;
}
}
}
===================================================================================
================================================
5)sort negative and positive elements
need to do without changing the order of elements
===================================================================================
=================================================
6)Union of two arrays
using hashmap O(m+n)
public static int doUnion(int a[], int n, int b[], int m)
{
//Your code here
HashMap<Integer,Integer> hash=new HashMap<>();
for(int i=0;i<n;i++)
{
if(hash.containsKey(a[i]))
{
continue;
}
else
{
hash.put(a[i],1);
}
}
for(int i=0;i<m;i++)
{
if(hash.containsKey(b[i]))
{
continue;
}
else
{
hash.put(b[i],1);
}
}
int count=0;
for(Map.Entry<Integer,Integer> entry:hash.entrySet())
{
count++;
}
return count;
}
//other method
class Solution{
public static int doUnion(int a[], int n, int b[], int m)
{
//Your code here
int count=0;
Set<Integer> hs = new HashSet<>();
for(int i=0;i<a.length;i++)
{
hs.add(a[i]);
}
for(int i=0;i<b.length;i++)
{
hs.add(b[i]);
}
for(int x:hs)
{
count++;
}
return count;
}
}
===================================================================================
====================================
6)(Intersection of two arrays):
public static int NumberofElementsInIntersection(int a[],int b[],int n,int m)
{
//Your code here
int count=0;
Set<Integer> hs = new HashSet<>();
Set<Integer> h = new HashSet<>();
for(int i=0;i<a.length;i++)
{
hs.add(a[i]);
}
for(int i=0;i<b.length;i++)
{
h.add(b[i]);
}
for (int s : hs)
{
if(h.contains(s))
{
count++;
}
}
return count;
}
===================================================================================
=============================================
plus one problem geeks for geeks
static ArrayList<Integer> increment(ArrayList<Integer> arr , int N) {
// code here
int carry=1;
for(int i=N-1;i>=0;i--)
{
int temp1=arr.get(i);
int temp2=temp1+carry;
if(temp2>9)
{
arr.set(i,temp2%10);
carry=(temp2)/10;
//System.out.println("carry"+carry);
}
else
{
arr.set(i,temp2%10);
carry=0;
}
}
if(carry==1)
{
arr.add(0,1);
}
return arr;
}
===================================================================================
=================================================
pleasent pairs 728 b problem
FastReader input=new FastReader();
PrintWriter out=new PrintWriter(System.out);
from now on use this
===================================================================================
===================================================
7)Largest sum contigious subarray
int maxSubarraySum(int arr[], int n){
}
//case:{3, 9, 12, 16, 20}
ans;11 k=3
===================================================================================
============================================
9)
===================================================================================
=====================================
10)find duplulicate within incl7usive
public int findDuplicate(int[] nums) {
Arrays.sort(nums);
int z=0;
int ans[]=new int[nums.length];
for(int i=0;i<nums.length;i++)
{
ans[nums[i]]+=1;
}
for(int i=0;i<ans.length;i++)
{
System.out.println(ans[i]);
if(ans[i]>1)
{
System.out.println("d"+i);
z=i;
}
}
return z;
}
-
===================================================================================
================================================
Anagram problems:
to check if it is a anagram
public static boolean isAnagram(String a,String b)
{
}
//number of required to delete to make a anagram
public int remAnagrams(String s,String s1)
{
//add code here.
int count1[]=new int[26];
// int count2[]=new int[26];
for(int i=0;i<s.length();i++)
{
count1[s.charAt(i)-'a']+=1;
}
for(int i=0;i<s1.length();i++)
{
count1[s1.charAt(i)-'a']-=1;
}
int count=0;
for(int i=0;i<count1.length;i++)
{
count+=Math.abs(count1[i]);
}
return count;
}
//ispossible of anagram palindrome
int isPossible (String S)
{
// your code here
int count=0;
int ans[]=new int[26];
for(int i=0;i<S.length();i++)
{
ans[S.charAt(i)-'a']++;
}
for(int i=0;i<ans.length;i++){
if(ans[i]%2!=0)
{
count++;
}
}
if(count<=1) return 1;
else return 0;
}
//same as palindreome
//important
//public List<List<String>> Anagrams(String[] str) {
int n=str.length;
HashMap<String,List<String>> hm=new HashMap<>();
for(int i=0;i<n;i++){
String word=str[i];
char letters[]=word.toCharArray();
Arrays.sort(letters);
String newword=new String(letters);
if(hm.containsKey(newword))
hm.get(newword).add(word);
else{
List<String> words=new ArrayList<>();
words.add(word);
hm.put(newword,words);
}
}
List<List<String>> res=new ArrayList<>();
for(Map.Entry<String,List<String>> me:hm.entrySet())
res.add(me.getValue());
return res;
}
///////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
geeks for geeks(04-07-2021)
daily challange
circular sum contigious subarray
static int kadane(int a[],int n)
{
int meh=0,msf=Integer.MIN_VALUE;
for(int i=0;i<n;i++)
{
meh=meh+a[i];
if(a[i]>meh)
{
meh=a[i];
}
if(meh>msf)
{
msf=meh;
}
}
// System.out.println(meh);
return msf;
}
static int reverseKadane(int a[],int n)
{
int total = 0;
int k = kadane(a,n);
}
static int circularSubarraySum(int a[], int n) {
===================================================================================
========================================================
Strngs babaeer 1)spiral traversal of a matrix
//Function to return a list of integers denoting spiral traversal of matrix.
static ArrayList<Integer> spirallyTraverse(int matrix[][], int r, int c)
{
// code here
ArrayList<Integer> ans=new ArrayList<>();
int k=0,l=0;
while(k<r && l<c)
{
for(int i=l;i<c;i++)
{
ans.add(matrix[k][i]);
}k++;
for(int i=k;i<r;i++)
{
ans.add(matrix[i][c-1]);
}c--;
if(k<r)
{
for(int i=c-1;i>=l;i--)
{
ans.add(matrix[r-1][i]);
}
r--;
}
if(l<c)
{
for(int i=r-1;i>=k;i--)
{
ans.add(matrix[i][l]);
}
l++;
}
}
return ans;
}
===================================================================================
================================================
BigInteger in java can handle a lot higher number
public String multiplyStrings(String s1,String s2)
{
//code here.
BigInteger b1 = new BigInteger(s1);
BigInteger b2 = new BigInteger(s2);
b1 = b1.multiply(b2);
return ""+b1;
}
#check normal multiplication without using biginteger
===================================================================================
=========================================
reverse words in a string
String reverseWords(String s)
{
// code here
String a="";
List<String> ans=new ArrayList<>();
String temp="";
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)!='.')
{
temp=temp+s.charAt(i);
}
else
{
ans.add(temp);
temp="";
}
}
ans.add(temp);
for(int i=ans.size()-1;i>=0;i--)
{
if(i!=0)
{
a=a+ans.get(i)+".";
}
else
{
a=a+ans.get(i);
}
}
return a;
}
===================================================================================
==============================================
first non reparating character in java
static char nonrepeatingCharacter(String S)
{
}
#ponder ho to do in a single loop
===================================================================================
=============================
knapsack classification problems
using memorisation as of now(recursion +memory)
static int knapSackMemory(int W,int wt[],int val[],int n,int dp[][])
{
if(n==0 || W==0)
{
return 0;
}
if(dp[n][W]!=0)
{
return dp[n][W];
}
if(wt[n-1]>W)
{
return dp[n][W]=knapSackMemory(W,wt,val,n-1,dp);
}
else
{
return dp[n][W]=Math.max(knapSackMemory(W,wt,val,n-1,dp),val[n-
1]+knapSackMemory(W-wt[n-1],wt,val,n-1,dp));
}
}
//Function to return max value that can be put in knapsack of capacity W.
static int knapSack(int W, int wt[], int val[], int n)
{
// your code here
int dp[][]=new int [n+1][W+1];
for (int row = 0; row < dp.length; row++)
{
for (int col = 0; col < dp[row].length; col++)
{
dp[row][col] = 0;
}
}
return knapSackMemory(W,wt,val,n,dp);
}
===================================================================================
===============================================
subset sum
need to learn bootom up approach
Given a set of non-negative integers, and a value sum, determine if there is a
subset of the given set with sum equal to given sum.
knapsack variation
static Boolean isSubsetSum(int N, int arr[], int sum){
// code here
for(int i=0;i<=N;++i){
t[i][0]=true;
}
if(N==0&&sum!=0)
return false;
if(sum==0)
return true;
if(arr[N-1]>sum)
return t[N][sum]=isSubsetSum(N-1,arr,sum);
else
return t[N][sum]=isSubsetSum(N-1,arr,sum-arr[N-1])||isSubsetSum(N-
1,arr,sum);
// 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];
===================================================================================
==============================================
System.out.println(dp[dp.length - 1][tar]);
}
===================================================================================
================================================
partition equal sum subset
static Boolean isSubsetSum(int N, int arr[], int sum){
// code here
for(int i=0;i<=N;++i){
t[i][0]=true;
}
// if(N==0&&sum!=0)
// return false;
// if(sum==0)
// return true;
// if(arr[N-1]>sum)
// return t[N][sum]=isSubsetSum(N-1,arr,sum);
// else
// return t[N][sum]=isSubsetSum(N-1,arr,sum-arr[N-1])||isSubsetSum(N-
1,arr,sum);
for(int i=1;i<=N ;++i){
for(int j=1;j<=sum;++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];
}
static int equalPartition(int N, int arr[])
{
int sum=0;
for(int i=0;i<N;i++)
{
sum+=arr[i];
}
// System.out.println(sum);
if(sum%2!=0)
{
return 0;
}
else
{
boolean x=isSubsetSum(N,arr,sum/2);
if(x==true) return 1;
else return 0;
}
}
===================================================================================
=======================================================================
count of subsets with given sum
public int perfectSum(int a[],int n, int sum)
{
int tab[][] = new int[n + 1][sum + 1];
tab[0][0] = 1;
for(int i = 1; i <= sum; i++)
tab[0][i] = 0;
for(int i = 1; i <= n; i++)
tab[i][0] = 1;
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= sum; j++)
{
if (a[i - 1] > j)
tab[i][j] = tab[i - 1][j];
else
{
tab[i][j] = (tab[i - 1][j] +
tab[i - 1][j - a[i - 1]])%1000000007;
}
}
}
return tab[n][sum];
}
===================================================================================
=======================================================================
minimum sum difference
find subset for half a sum value and iterate in the last row of the subset sum
static boolean [][] isSubsetSum(int N, int arr[], int sum){
// code here
for(int i=0;i<=N;++i){
t[i][0]=true;
}
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;
}
int finalsum=sum/2;
boolean a[][]=isSubsetSum(n,arr,sum/2);
int l=0;
// System.out.println(a.length+" "+a[0].length);
// System.out.println(n+" "+finalsum);
// System.out.println(a[n][finalsum]);
// for(int i=0;i<a.length;i++)
// {
// for(int j=0;j<a[0].length;j++)
// {
// System.out.print(a[i][j]+" ");
// }
// System.out.println();
// }
for(int i=a[0].length-1;i>=0;i--)
{
if(a[n][i]==true)
{
l=i;
break;
}
}
return sum-2*l;
}
===================================================================================
======================================
count of number of subsets with the given difference
s1=(diff+sum)/2
find the count of number of s1 in array
===================================================================================
========================
should check leetcode target sum problem +-
===================================================================================
========================
Maximum profit of buying and selling a stock with single transactio(leetcode121)
public int maxProfit(int[] prices) {
int ans=0;
int lsf=Integer.MAX_VALUE;
for(int i=0;i<prices.length;i++)
{
if(prices[i]<=lsf)
{
lsf=prices[i];
}
else
{
int temp=prices[i]-lsf;
if(temp>ans)
{
ans=temp;
}
}
}
return ans;
}
===================================================================================
==========================================
Maximum profit of buying and selling a stock with infinite transactions are allowed
class Solution {
public int maxProfit(int[] prices) {
int profit=0;
int bd=0;int sd=0;
for(int i=1;i<prices.length;i++)
{
if(prices[i]>prices[i-1])
{
sd++;
}
else
{
profit=profit+prices[sd]-prices[bd];
sd=bd=i;
}
}
profit=profit+prices[sd]-prices[bd];
return profit;
}
}
===================================================================================
=========================================
Best Time to Buy and Sell Stocks with Transaction Fee and Infinite Transactions
string to integer handles both negative and positve case without Integer.parseInt
class Solution
{
int atoi(String str)
{
// Your code here
// char x='0';
// char y='9';
// System.out.println(x);
// System.out.println(((int) x)+" "+((int) y));
boolean flag=true;
if(str.startsWith("-"))
{
str=str.substring(1);
flag=false;
}
for(int i=0;i<str.length();i++)
{
int temp=(int)str.charAt(i);
// System.out.println(temp);
if(temp>47 && temp<=57) continue;
else return -1;
}
int ans=0;
int z=0;
for(int i=str.length()-1;i>=0;i--)
{
int temp=Integer.parseInt(""+str.charAt(i));
ans=ans+temp*(int)Math.pow(10,z);
z++;
}
if(flag==false)
{
return -ans;
}
return ans;
}
}
===================================================================================
==================================
palindrome string check done before or not
class Solution {
int isPlaindrome(String S) {
// code here
int i=0,j=S.length()-1;
while(i<j)
{
if(S.charAt(i)==S.charAt(j))
{
i++;j--;
}
else
{
return 0;
}
}
return 1;
}
};
===================================================================================
===================
return first letter of each word
class Solution {
String firstAlphabet(String S) {
// code here
String ans="";
ans+=S.charAt(0);
for(int i=1;i<S.length();i++)
{
if(S.charAt(i)==' ')
{
ans+=S.charAt(i+1);
}
}
return ans;
}
};
===================================================================================
===========================
minimum number following a string (dddIII) d donates decreasing i for increading
class Solution{
static String printMinNumberForPattern(String str){
Stack<Integer> st = new Stack<>();
String ans="";
int num = 1;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch == 'D') {
st.push(num);
num++;
} else {
st.push(num);
num++;
st.push(num);
while (st.size() > 0) {
// System.out.print(st.pop());
ans+=st.pop();
}
return ans;
}
}
this is O(n) time complexity
O(n) space complexity
=>now let us know about O(n) time complexity and O(1) space complexity
===================================================================================
=============================
get subsequence storing in an arraylist
import java.io.*;
import java.util.*;
char ch = str.charAt(0);
String ros = str.substring(1);
char ch = ques.charAt(0);
String roq = ques.substring(1);
printSS(roq, ans + ch);
printSS(roq, ans + "");
}
}
===================================================================================
===============================================
print stair paths
import java.io.*;
import java.util.*;
return;
}
import java.io.*;
import java.util.*;
if(n == 0){
bres.add("");
}
return bres;
}
return mres;
}
}
===================================================================================
============================
get maze paths
import java.io.*;
import java.util.*;
public static void printMazePaths(int sr, int sc, int dr, int dc, String psf) {
if(sr > dr || sc > dc){
return;
}
import java.io.*;
import java.util.*;
public class Main {
public static ArrayList<String> getMazePaths(int sr, int sc, int dr, int dc) {
if(sr > dr || sc > dc){
return new ArrayList<>();
}
return paths;
}
}
===================================================================================
=============================================================
printmazepaths with jumps