Wednesday, 17 April 2024
Extracting information from URL
Thursday, 11 April 2024
Code demonstrating multiple inheritence in JAVA VIA INTERFACE
interface A {
void methodA();
}
interface B {
void methodB();
}
// Class C implements both interfaces A and B
class C implements A, B {
public void methodA() {
System.out.println("Method A implementation");
}
public void methodB() {
System.out.println("Method B implementation");
}
}
public class Main {
public static void main(String[] args) {
C obj = new C();
obj.methodA(); // Output: Method A implementation
obj.methodB(); // Output: Method B implementation
}
}
Static vs Non-static access
class Car{
Returning object using this keyword in Java
Merge two sorted arrays
import java.util.*;
Monday, 8 April 2024
Abstract class in JAVA
abstract class Shape {
abstract double area(); // Abstract method to calculate area
abstract double perimeter(); // Abstract method to calculate perimeter
void display() {
System.out.println("This is a shape.");
}
}
class Circle extends Shape {
double radius;
Circle(double radius) {
this.radius = radius;
}
@Override
double area() {
return Math.PI * radius * radius;
}
@Override
double perimeter() {
return 2 * Math.PI * radius;
}
}
class Rectangle extends Shape {
double length;
double width;
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
double area() {
return length * width;
}
@Override
double perimeter() {
return 2 * (length + width);
}
}
public class AbstractClassExample {
public static void main(String[] args) {
Circle circle = new Circle(5);
System.out.println("Area of circle: " + circle.area());
System.out.println("Perimeter of circle: " + circle.perimeter());
Rectangle rectangle = new Rectangle(4, 6);
System.out.println("Area of rectangle: " + rectangle.area());
System.out.println("Perimeter of rectangle: " + rectangle.perimeter());
circle.display();
rectangle.display();
}
}
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;
}
}
Monday, 8 January 2024
Next Permutation by O(n)
import java.util.*;
public class Solution {
public static List< Integer > nextGreaterPermutation(List< Integer > A) {
// Write your code here
int n= A.size();
int dip_idx = -1;
for(int i=n-2; i>=0; i--)
{
if(A.get(i)<A.get(i+1))
{
dip_idx = i;
break;
}
}
if(dip_idx== -1)
{
Collections.reverse(A);
}
for(int i=n-1;i>=dip_idx;i--)
{
if(A.get(i)>A.get(dip_idx))
{
int temp=A.get(dip_idx);
A.set(dip_idx,A.get(i));
A.set(i,temp);
break;
}
}
Collections.reverse(A.subList(dip_idx+1, n));
return A;
}
}
Sunday, 7 January 2024
longest Subarray with maximum sum as k
import java.util.*;
public class MyFirstClass {
public static void main(String[] args) {
int[] a = {2, 3, 1, 1, 2, 4, 2, 9};
long k = 10;
int len = getLongestSubarray(a, k);
System.out.println("The length of the longest subarray is: " + len);
}
public static int getLongestSubarray(int []a, long k) {
int n = a.length; // size of the array.
Map<Long, Integer> preSumMap = new HashMap<>();
long sum = 0;
int maxLen = 0;
for (int i = 0; i < n; i++) {
//calculate the prefix sum till index i:
sum += a[i];
// if the sum = k, update the maxLen:
if (sum == k) {
maxLen = Math.max(maxLen, i + 1);
}
// calculate the sum of remaining part i.e. x-k:
long rem = sum - k;
//Calculate the length and update maxLen:
if (preSumMap.containsKey(rem)) {
int len = i - preSumMap.get(rem);
maxLen = Math.max(maxLen, len);
}
//Finally, update the map checking the conditions:
if (!preSumMap.containsKey(sum)) {
preSumMap.put(sum, i);
}
}
return maxLen;
}
}
Intersection of two sorted arrays code in java
import java.util.*;
public class MyFirstClass {
public static void main(String[] args) {
int arr1[] = {1,1,2,3,4,4,5};
int arr2[] = {2,3,4,4,5,10,20,100};
int n1 = arr1.length; int n2=arr2.length;
int leng = n1+n2;
int i=0;int j=0;
ArrayList<Integer> Intersection = new ArrayList<>();
while(i<n1 && j<n2)
{
if(arr1[i]<arr2[j])
{
i++;
}
else if(arr2[j] < arr1[i])
{
j++;
}
else
{
Intersection.add(arr1[i]);
i++;
j++;
}
}
System.out.println(Intersection);
}
}
Union of two sorted arrays code in java
import java.util.*;
public class MyFirstClass {
public static void main(String[] args) {
int arr1[] = {1,1,2,3,4,5};
int arr2[] = {2,3,4,4,5,10,20,100};
int n1 = arr1.length; int n2=arr2.length;
int leng = n1+n2;
int i=0;int j=0;
ArrayList<Integer> Union = new ArrayList<>();
while(i<n1 && j<n2)
{
if (arr1[i] <= arr2[j]) // Case 1 and 2
{
if (Union.size() == 0 || Union.get(Union.size()-1) != arr1[i])
Union.add(arr1[i]);
i++;
} else // case 3
{
if (Union.size() == 0 || Union.get(Union.size()-1) != arr2[j])
Union.add(arr2[j]);
j++;
}
}
while(j<n2)
{
if (Union.size() == 0 || Union.get(Union.size()-1) != arr2[j])
Union.add(arr2[j]);
j++;
}
while(i<n1)
{
if (Union.size() == 0 || Union.get(Union.size()-1) != arr1[i])
Union.add(arr1[i]);
i++;
}
System.out.println(Union);
}
}
Wednesday, 20 December 2023
Highest / Lowest Frequency Elements
import java.util.HashMap;
import java.util.Map;
import java.util.Arrays;
import java.util.Scanner;
public class MyFirstClass {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int v[] = {11,13,3,14,17,3,7,9,1,11,9,15,5,2,2,3,11,2};
int r[] = getFrequencies(v);
for (int i : r) {
System.out.print(i+" ");
}
}
public static int[] getFrequencies(int []v) {
// Write Your Code Here
HashMap<Integer,Integer> mp = new HashMap<>();
int n = v.length;
//int result[] = new int[n];
for(int i=0; i<v.length; i++)
{
int freq = 0;
if(mp.containsKey(v[i]))
{
freq = mp.get(v[i]);
}
freq += 1;
mp.put(v[i],freq);
}
int maxele=0;int minele=0;
int minfreq=n;
int maxfreq = 0;
for(HashMap.Entry<Integer,Integer> entry : mp.entrySet())
{
int element = entry.getKey();
int count = entry.getValue();
if(count>=maxfreq)
{
if(count==maxfreq) maxele = Math.min(maxele, element);
else maxele = element;
maxfreq = count;
}
if(count<=minfreq)
{
//minele = Math.min(element,minele);
if(count==minfreq) minele = Math.min(minele, element);
else minele = element;
minfreq = count;
}
}
int result[] = new int[2];
result[0] = maxele;
result[1] = minele;
return result;
}
}
Count Frequency in a range
import java.util.HashMap;
public class Solution {
public static int[] countFrequency(int n, int x, int []nums){
HashMap<Integer,Integer> mp = new HashMap<>();
int result[] = new int[n];
for(int i=0; i<nums.length; i++)
{
int freq = 0;
if(mp.containsKey(nums[i]))
{
freq = mp.get(nums[i]);
}
freq += 1;
mp.put(nums[i],freq);
}
for (int i = 0; i < n+1; i++) {
mp.putIfAbsent(i, 0);
}
for(int i=0; i<n; i++)
{
result[i] = mp.get(i+1);
}
return result;
}
}
HashMap and Entry Interface code in JAVA
import java.util.HashMap;
import java.util.Map;
import java.util.Arrays;
import java.util.Scanner;
public class MyFirstClass {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
HashMap<Integer,String> m = new HashMap<>();
System.out.println(m);
m.put(101,"John");
m.put(102,"Aman");
m.put(103,"Satyam");
m.put(104,"Aryaman");
System.out.println(m);
System.out.println("=======");
System.out.println(m.entrySet());
System.out.println(m.keySet().size());
for(int i: m.keySet())
{
System.out.println(i);
}
for(String i: m.values())
{
System.out.println(i);
}
for(int i: m.keySet())
{
System.out.println(i+" "+m.get(i));
}
}
}
Tuesday, 19 December 2023
Question: Find the highest/lowest frequency element.If there are multiple elements that have the highest frequency or lowest frequency then pick the smallest element.
Coding Ninjas Problem link
import java.util.HashMap;
import java.util.Map;
import java.util.TreeSet;
public class Solution {
public static int[] getFrequencies(int[] v) {
int n = v.length;
return frequency(v, n);
}
public static int[] frequency(int[] arr, int n) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
map.put(arr[i], map.getOrDefault(arr[i], 0) + 1);
}
TreeSet<Integer> maxFreqElements = new TreeSet<>();
TreeSet<Integer> minFreqElements = new TreeSet<>();
int maxFreq = 0, minFreq = n;
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
int count = entry.getValue();
int element = entry.getKey();
if (count > maxFreq) {
maxFreqElements.clear();
maxFreqElements.add(element);
maxFreq = count;
} else if (count == maxFreq) {
maxFreqElements.add(element);
}
if (count < minFreq) {
minFreqElements.clear();
minFreqElements.add(element);
minFreq = count;
} else if (count == minFreq) {
minFreqElements.add(element);
}
}
int[] res = new int[2];
res[1] = minFreqElements.first(); // Smallest element with minimum frequency
if (maxFreqElements.size() > 1) {
res[0] = maxFreqElements.first(); // Smallest element with maximum frequency
} else {
res[0] = maxFreqElements.pollFirst();
}
return res;
}
}
Saturday, 16 December 2023
L
L L L
L L L L L
L L L L L L L
L L L L L L L L L
import java.util.*;
public class MyFirstClass {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int i = 1 ; i<=n ; i++)
{
for(int j = i+1; j<=n; j++)
{
System.out.print(" ");
}
for(int j = 1; j<=i; j++)
{
System.out.print("L");
}
for(int j = 1; j<i; j++)
{
System.out.print("L");
}
System.out.println();
}
}
}
Friday, 15 December 2023
Pass by value vs Pass by reference in JAVA
Theory:
Java is strictly pass-by-value. In Java, you can't directly pass variables by reference as you would in languages like C/C++. However, you can achieve a similar effect by passing an array or an object reference.
Code:
import java.util.*;
public class MyFirstClass {
public static void main(String[] args) {
//Pass by value example in JAVA
System.out.println("PASS by value example in JAVA");
int n = 1;
passByValue(n);
System.out.println(n); // You can see O/P of n is unmodified by passByValue func
System.out.println("PASS by reference example in JAVA");
// Pass by reference example in JAVA
int num[] = new int[1];
num[0] = 10;
doSomething(num); // Passing the array reference
System.out.println(num[0]); // Print the modified value
}
// Pass by value example in JAVA
public static void passByValue(int num)
{
num = num + 10;
System.out.println(num);
}
// Pass by reference example in JAVA
public static void doSomething(int num[]) {
num[0] = num[0] + 10;
System.out.println(num[0]);
}
}
Friday, 17 November 2023
// Grid Unique Paths-->2-D dp concept(space optimised)
// tc = O(mxn)
// sc = O(n) --> array
import java.util.*;
class dp {
public static int f(int m, int n)
{
int prev[] = new int[n];
for(int i=0;i<m;i++)
{
int temp[] = new int[n];
for(int j=0;j<n;j++)
{
if(i==0&&j==0) {temp[j] = 1;continue;}
else
{
int up=0;int left=0;
if(i>0)
up = prev[j];
if(j>0)
left = temp[j - 1];
temp[j] = up + left;
}
}
prev = temp;
}
return prev[n - 1];
}
public static void main(String args[]) {
int m = 3;
int n = 2;
System.out.println(f(m,n));
}
}
// Grid Unique Paths-->2-D dp concept(Tabulation)
// tc = O(mxn)
// sc = O(mxn) --> extra dp array
import java.util.*;
class dp {
public static int f(int dp[][], int m, int n)
{
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(i==0&&j==0) {dp[0][0]=1;continue;}
else
{
int up=0;int left=0;
if(i>0)
up = dp[i-1][j];
if(j>0)
left = dp[i][j-1];
dp[i][j] = up+left;
}
}
}
return dp[m-1][n-1];
}
public static void main(String args[]) {
int m = 3;
int n = 2;
int dp[][] = new int[m][n];
// Initialize the DP array with -1 to indicate uncomputed values
for (int[] row : dp)
Arrays.fill(row, -1);
System.out.println(f(dp,m,n));
}
}
// 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)+(m-1)) + O(mxn) --> stack space + extra dp array
import java.util.*;
class dp {
public static int f(int i , int j, int dp[][])
{
if(i==0&&j==0) return 1;
if(i<0||j<0) return 0;
if(dp[i][j]!=-1) return dp[i][j];
int up = f(i-1,j,dp);
int left = f(i,j-1,dp);
return dp[i][j]=up+left;
}
public static void main(String args[]) {
int m = 3;
int n = 2;
int dp[][] = new int[m][n];
// Initialize the DP array with -1 to indicate uncomputed values
for (int[] row : dp)
Arrays.fill(row, -1);
System.out.println(f(m-1,n-1,dp));
}
}
// Ninja's Training-->2-D dp concept(Memoization)
// tc = O(nx4x3)
// sc = O(n) + O(nx4) --> stack space + extra dp array
import java.util.*;
class dp {
// Recursive function to calculate the maximum points for the ninja training
static int f(int day, int last, int[][] points, int[][] dp) {
// If the result is already calculated, return it
if (dp[day][last] != -1) return dp[day][last];
// Base case: When it's the first day (day == 0)
if (day == 0) {
int maxi = 0;
for (int i = 0; i <= 2; i++) {
if (i != last)
maxi = Math.max(maxi, points[0][i]);
}
return dp[day][last] = maxi; // Store and return the result
}
int maxi = 0;
// Loop through the three activities on the current day
for (int i = 0; i <= 2; i++) {
if (i != last) {
// Calculate the points for the current activity and recursively
// calculate the maximum points for the previous day
int activity = points[day][i] + f(day - 1, i, points, dp);
maxi = Math.max(maxi, activity); // Update the maximum points
}
}
return dp[day][last] = maxi; // Store and return the result
}
// Function to find the maximum points for ninja training
static int ninjaTraining(int n, int[][] points) {
// Initialize a memoization table with -1 values
int dp[][] = new int[n][4];
for (int[] row : dp)
Arrays.fill(row, -1);
// Start the recursive calculation from the last day (n - 1) with the last activity (3)
return f(n - 1, 3, points, dp);
}
public static void main(String args[]) {
// Define the points for each activity on each day
int[][] points = {{10, 40, 70},
{20, 50, 80},
{30, 60, 90}};
int n = points.length; // Get the number of days
System.out.println(ninjaTraining(n, points)); // Calculate and print the maximum points
}
}
Monday, 13 November 2023
// Maximum Sum of Non-Adjacent Elements(Memoization)
// tc = O(n)
// sc = O(n) + O(n) --> stack space + extra dp array
import java.util.*;
public class dp {
public static int func(int index, int arr[],int dp[])
{
if(index==0) return arr[index];
if(index<0) return 0;
if(dp[index] !=-1) return dp[index];
int pick = func(index-2, arr,dp) + arr[index];
int notpick = func(index-1, arr, dp) + 0;
return dp[index] = Math.max(pick,notpick);
}
public static void main(String[] args) {
int arr[] = {2,1,4,9};
int n = 3; // or, n=arr.length
int dp[] = new int[n+1]; // then n
Arrays.fill(dp,-1);
System.out.println(func(n,arr,dp));
}
}
// Frog Jump via Bottom-up(Tabulation)
// tc = O(n)
// sc = O(n) --> extra dp array
import java.util.*;
public class dp {
public static void main(String[] args) {
int height[]={30,10,60,10,60,50};
int n = 5; // or when --> n = height.length
int dp[] = new int[n+1];
Arrays.fill(dp,-1);
dp[0] = 0;
for(int i = 1;i<n+1;i++)
{
int left_jmpOne = dp[i-1] + Math.abs(height[i] - height[i-1]);
int right_jmpTwo = Integer.MAX_VALUE;
if(i>1){
right_jmpTwo = dp[i-2] + Math.abs(height[i] - height[i-2]);
}
dp[i] = Math.min(left_jmpOne,right_jmpTwo);
}
System.out.println(dp[n]); // then n-1
}
}
// Frog Jump via Memoization
// tc = O(n)
// sc = O(n) + O(n) --> stack space + extra dp array
import java.util.*;
public class dp {
public static int func(int index, int height[], int dp[]) {
if(index==0) return 0;
if(dp[index] != -1) return dp[index];
int left_jmpOne = func(index-1,height,dp) + Math.abs(height[index] - height[index-1]);
int right_jmpTwo = Integer.MAX_VALUE;
if(index>1)
{
right_jmpTwo = func(index-2,height,dp) + Math.abs(height[index] - height[index-2]);
}
return dp[index] = Math.min(left_jmpOne,right_jmpTwo);
}
public static void main(String[] args) {
int height[]={30,10,60,10,60,50};
int n = 5; // n = height.length
int dp[] = new int[n+1];
Arrays.fill(dp,-1);
System.out.println(func(n,height,dp)); // then n-1 here
}
}
// Climbing Stairs | How to Write 1D Recurrence Relations
// tc = O(n)
// sc = O(n) --> stack space
import java.util.*;
public class dp {
public static int func(int index) {
if (index == 0) return 1;
if (index == 1) return 1;
int left = func(index - 1);
int right = func(index - 2);
return left + right;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of stairs: ");
int n = scanner.nextInt();
int ways = func(n);
System.out.println("Number of ways to climb " + n + " stairs: " + ways);
}
}
// Program to convert recursive fibonacci into dp by tabulation method(bottom-up)
// tc= O(n)
// sc= O(1) = extra array space is also removed
import java.util.*;
public class dp {
public static void main(String[] args) {
int n = 5;
//int dp[] = new int[n+1];
int prev2 = 0;
int prev = 1;
System.out.println(prev2);
System.out.println(prev);
for(int i = 2; i<n+1;i++)
{
int curr = prev + prev2;
System.out.println(curr);
prev2 = prev;
prev = curr;
}
//System.out.println(prev);
}
}
// Program to convert recursive fibonacci into dp
// tc= O(n)
// sc= O(n) + O(n) = stack space + extra array space respectively
import java.util.*;
public class dp {
public static int func(int n, int[] dp)
{
if(n<=1) return n; //base case
if(dp[n] != -1) return dp[n]; //memoization
return dp[n]= func(n-1,dp) + func(n-2,dp); //compute
}
public static void main(String[] args) {
int n = 5;
int dp[] = new int[n+1];
Arrays.fill(dp,-1); // initialise all with -1
for (int i : dp) {
System.out.print(i+" "); // output is -1,-1,-1,-1,-1,-1
}
System.out.println();
System.out.println("----");
System.out.println(func(n,dp)); // output is 5
System.out.println("----");
for (int i : dp) {
System.out.print(i+" "); // output is: -1,-1,1,2,3,5
}
}
}
// Program to convert recursive fibonacci into dp by tabulation method(bottom-up)
// tc= O(n)
// sc= O(n) = extra array space respectively (stack space is removed)
import java.util.*;
public class dp {
public static void main(String[] args) {
int n = 5;
int dp[] = new int[n+1];
dp[0] = 0;
dp[1] = 1;
for(int i = 2; i<n+1;i++)
{
dp[i] = dp[i-2] + dp[i-1];
}
for (int i : dp) {
System.out.print(i+" ");
}
}
}
Tuesday, 3 October 2023
Shortest Path in undirected Graph with unit weights (code in JAVA)
import java.util.*;
import java.lang.*;
import java.io.*;
class dist{
public static void main(String[] args) throws IOException{
int n=9, m=10;
int[][] edge = {{0,1},{0,3},{3,4},{4,5},{5,6},{1,2},{2,6},{6,7},{7,8},{6,8}};
Solution obj = new Solution();
int res[] = obj.shortestPath(edge,n,m,0);
for(int i=0;i<n;i++){
System.out.print(res[i]+" ");
}
System.out.println();
}
}
class Solution {
public int[] shortestPath(int[][] edges,int n,int m ,int src) {
//Create an adjacency list of size N for storing the undirected graph.
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
for(int i = 0;i<n;i++) {
adj.add(new ArrayList<>());
}
for(int i = 0;i<m;i++) {
adj.get(edges[i][0]).add(edges[i][1]);
adj.get(edges[i][1]).add(edges[i][0]);
}
//A dist array of size N initialised with a large number to
//indicate that initially all the nodes are untraversed.
int dist[] = new int[n];
for(int i = 0;i<n;i++) dist[i] = (int)1e9;
dist[src] = 0;
// BFS Implementation
Queue<Integer> q = new LinkedList<>();
q.add(src);
while(!q.isEmpty()) {
int node = q.peek();
q.remove();
for(int it : adj.get(node)) {
if(dist[node] + 1 < dist[it]) {
dist[it] = 1 + dist[node];
q.add(it);
}
}
}
// Updated shortest distances are stored in the resultant array ‘ans’.
// Unreachable nodes are marked as -1.
for(int i = 0;i<n;i++) {
if(dist[i] == 1e9) {
dist[i] = -1;
}
}
return dist;
}
}
Shortest Path in directed acyclic graph via topological sort. Remember this method of topological sort to find the shortest distance do not work for graph containing cycle and in that case we use Dijkstra's Algorithm. (code in JAVA)
import java.util.*;
import java.lang.*;
import java.io.*;
class dist {
public static void main(String[] args) throws IOException {
int n = 6, m = 7;
int[][] edge = {{0,1,2},{0,4,1},{4,5,4},{4,2,2},{1,2,3},{2,3,6},{5,3,1}};
Solution obj = new Solution();
int res[] = obj.shortestPath(n, m, edge);
for (int i = 0; i < n; i++) {
System.out.print(res[i] + " ");
}
System.out.println();
}
}
class Pair {
int first, second;
Pair(int _first, int _second) {
this.first = _first;
this.second = _second;
}
}
//User function Template for Java
class Solution {
private void topoSort(int node, ArrayList < ArrayList < Pair >> adj,
int vis[], Stack < Integer > st) {
//This is the function to implement Topological sort.
vis[node] = 1;
for (int i = 0; i < adj.get(node).size(); i++) {
int v = adj.get(node).get(i).first;
if (vis[v] == 0) {
topoSort(v, adj, vis, st);
}
}
st.add(node);
}
public int[] shortestPath(int N, int M, int[][] edges) {
ArrayList < ArrayList < Pair >> adj = new ArrayList < > ();
for (int i = 0; i < N; i++) {
ArrayList < Pair > temp = new ArrayList < Pair > ();
adj.add(temp);
}
//We create a graph first in the form of an adjacency list.
for (int i = 0; i < M; i++) {
int u = edges[i][0];
int v = edges[i][1];
int wt = edges[i][2];
adj.get(u).add(new Pair(v, wt));
}
int vis[] = new int[N];
//Now, we perform topo sort using DFS technique
//and store the result in the stack st.
Stack < Integer > st = new Stack < > ();
for (int i = 0; i < N; i++) {
if (vis[i] == 0) {
topoSort(i, adj, vis, st);
}
}
//Further, we declare a vector ‘dist’ in which we update the value of the nodes’
//distance from the source vertex after relaxation of a particular node.
int dist[] = new int[N];
for (int i = 0; i < N; i++) {
dist[i] = (int)(1e9);
}
dist[0] = 0;
while (!st.isEmpty()) {
int node = st.peek();
st.pop();
for (int i = 0; i < adj.get(node).size(); i++) {
int v = adj.get(node).get(i).first;
int wt = adj.get(node).get(i).second;
if (dist[node] + wt < dist[v]) {
dist[v] = wt + dist[node];
}
}
}
for (int i = 0; i < N; i++) {
if (dist[i] == 1e9) dist[i] = -1;
}
return dist;
}
}
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...
-
Intersection of two sorted arrays code in java import java.util.*; public class MyFirstClass { public static void main(String[] args) {...
-
longest Subarray with maximum sum as k import java.util.*; public class MyFirstClass { public static void main(String[] args) { ...
-
BigInteger class is not in java.util.* Hence you have to import it import java.math.BigInteger; public class MyFirstClass { public stati...