Monday, 11 March 2024
GRAPH REPRESENTATION VIA ADJACENCY LIST IN JAVA & ADD EDGES
Friday, 8 March 2024
Thursday, 7 March 2024
To print the longest increasing subsequence
Solution:
import java.util.ArrayList;
import java.util.Arrays;
class Dsa {
public static int lengthOfLIS() {
int arr[]={5,4,11,1,16,8};
int n=arr.length;
int dp[]=new int[n];int hash[]=new int[n];
Arrays.fill(dp,1);
for(int i=1;i<n;i++)
{
hash[i]=i;
for(int j=0;j<i;j++)
{
if(arr[i]>arr[j])
{
if(dp[j]+1>dp[i])
{
dp[i]=dp[j]+1;
hash[i]=j;
}
}
}
}
int maxIdx=0;int lastIndex=-1;
for(int i=0;i<n;i++)
{
if(dp[i]>dp[maxIdx])
{
maxIdx=i;
//maxIdx=i;
lastIndex=i;
}
}
ArrayList<Integer> temp=new ArrayList<>();
temp.add(arr[lastIndex]);
while(hash[lastIndex] != lastIndex){ // till not reach the initialization value
lastIndex = hash[lastIndex];
temp.add(arr[lastIndex]);
}
// reverse the array
System.out.print("The subsequence elements are ");
for(int i=temp.size()-1; i>=0; i--){
System.out.print(temp.get(i)+" ");
}
System.out.println();
return dp[maxIdx];
}
public static void main(String[] args) {
lengthOfLIS();
}
}
Collections.binarySearch in JAVA
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class BinarySearchExample {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6, 7, 8, 9));
int key = 5;
int index = Collections.binarySearch(list, key);
if (index >= 0) {
System.out.println("Element found at index: " + index);
} else {
System.out.println("Element not found. Insertion point: " + (-index - 1));
}
}
}
// If you are working with arrays, you would use Arrays.binarySearch.
Tuesday, 5 March 2024
Problem statement: https://leetcode.com/problems/product-of-array-except-self/description/
Solution:
in O(1) space , if ans array is not considered as extra space
class Solution {
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] ans = new int[n];
ans[0] = 1;
for (int i = 1; i < n; i++) {
ans[i] = ans[i - 1] * nums[i - 1];
}
int right = 1;
for (int i = n - 1; i >= 0; i--) {
ans[i] *= right;
right *= nums[i];
}
return ans;
}
}
Good thoughtful question on Binary search on answers
Problem link: https://leetcode.com/problems/maximize-score-of-numbers-in-ranges/description/ Solution: //import java.util.Arrays; class So...
-
// Grid Unique Paths-->2-D dp concept(space optimised) // tc = O(mxn) // sc = O(n) --> array import java.util.*; class dp { pub...
-
// Grid Unique Paths-->2-D dp concept(Tabulation) // tc = O(mxn) // sc = O(mxn) --> extra dp array import java.util.*; class dp { ...
-
// Count Grid Unique Paths-->2-D dp concept(Memoization) // tc = O(mxn) -->at max there will be n*m calls of recursion // sc = O((n-1...