Saturday 7 September 2024

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 Solution {
    public int maxPossibleScore(int[] start, int d) {
        Arrays.sort(start); // Ensure the start array is sorted

        long head = 0, tail = (long) 2e9;
        while (head < tail) {
            long mid = (head + tail + 1) / 2; // Try the middle gap value
            if (check(mid, start, d)) {
                head = mid; // Gap is valid, try for a larger gap
            } else {
                tail = mid - 1; // Gap is not valid, reduce the gap
            }
        }
        return (int) head; // Maximum minimum gap found
    }

    // Function to check if a given gap 'lim' is valid
    public static boolean check(long lim, int[] start, int d) {
        long now = start[0];  // Start with the first number

        // for each mid you are checking whether it is within the range of each
        // interval and if it is then you are checking with greater gap that is
        // mid value otherwise if not then you are reducing by mid-1
        for (int i = 1; i < start.length; i++) {
            now = Math.max(now + lim, start[i]);  // Pick the maximum valid number
            if (now > start[i] + d) return false; // If exceeds the range, return false
        }
        return true; // Gap is valid for all picks
    }
}

Thursday 8 August 2024

Detect cycle via BFS

import java.util.*;
class Pair{
    int first;int second;
    Pair(int f, int s)
    {
        this.first=f; this.second=s;
    }
}

public class DetectCycleViaBfs {
    // Function to detect cycle in an undirected graph.
    public boolean isCycle(int maxIntegerVertex, ArrayList<ArrayList<Integer>> adj) {
        // Code here
        Queue<Pair> q =  new ArrayDeque<>();
        int V=maxIntegerVertex;
        boolean vis[] = new boolean[V];
        Arrays.fill(vis,false);
   
    // code to find detect cycle in connected component
        for(int i=0;i<V;i++)
       {
            if(!vis[i])
                if(checkForCycle(adj, i,vis,q))
                    return true;
       }
   
        return false; //NO CYCLE
    }
   
    //check for cycle using bfs
    public static boolean checkForCycle(ArrayList<ArrayList<Integer>> adj, int s,

            boolean vis[], Queue<Pair> q)

    {
       q.add(new Pair(s, -1)); //FOR STARTING NODE
       vis[s] =true;

       // until the queue is empty
       while(!q.isEmpty())
       {
           // source node and its parent node
           int node = q.peek().first;
           int par = q.peek().second; //PARENT
           q.remove();
           // go to all the adjacent nodes

           for(Integer it: adj.get(node))

           {
               if(!vis[it])  

               {

                   q.add(new Pair(it, node));

                   vis[it] = true;

               }

       

                // if adjacent node is visited and is not its own parent node

               else if(par != it) return true; //cycle detection

           }

       }

       
       return false;

    }
}

Tuesday 16 July 2024

Two pointer approach in sliding window using hashmap

Problem statement: https://leetcode.com/problems/find-all-anagrams-in-a-string/description/

Solution:

Time complexity: in O(n)

import java.util.*;

public class Solution {
    public List<Integer> findAnagrams(String s, String p) {
        List<Integer> result = new LinkedList<>();
        int n=s.length();
        HashMap<Character,Integer> s_mp=new HashMap<>();
        HashMap<Character,Integer> p_mp=new HashMap<>();
        for(int i=0;i<p.length();i++)
        {
            char c=p.charAt(i);
            p_mp.put(c,p_mp.getOrDefault(c,0)+1);
        }
        int i=0; int j=0;
        while(j<n)
        {
            char cs=s.charAt(j);
            s_mp.put(cs,s_mp.getOrDefault(cs,0)+1);
            if(j-i+1==p.length())
            {
                if(s_mp.equals(p_mp))
                {
                    result.add(i);
                }
            // Remove the character that's left behind as the window slides
            char leftChar = s.charAt(i);
            if (s_mp.get(leftChar) == 1) s_mp.remove(leftChar);
            else s_mp.put(leftChar, s_mp.get(leftChar) - 1);
                i+=1;
            }
            j+=1;
        }
        return result;
    }
}

Monday 3 June 2024

Priority queue medium variant leetcode question

Problem statement link: https://leetcode.com/problems/largest-values-from-labels/

Solution:

import java.util.*;


class Pair{

    int value;int type;

    public Pair(int value,int type)

    {

        this.value=value;this.type=type;

    }

}


class Solution {

    public int largestValsFromLabels(int[] values, int[] labels, int numWanted, int useLimit) {

        PriorityQueue<Pair> pq=new PriorityQueue<Pair>((a,b)->(b.value-a.value));

        for(int i=0;i<values.length;i++)

        {

            pq.add(new Pair(values[i],labels[i]));

        }

        Map<Integer,Integer> mp=new HashMap<>();

        int result=0;int i=0;

        while(i<numWanted && !pq.isEmpty())

        {

            Pair p= pq.poll();

            if(mp.get(p.type)==null)

            {

                mp.put(p.type,1);

                result+=p.value;

                i+=1;

            }

            else if(mp.get(p.type)!=null && mp.get(p.type)<useLimit)

            {

                result+=p.value;

                mp.put(p.type,mp.get(p.type)+1);

                i+=1;

            }

        }

        return result;

    }

}

Saturday 20 April 2024

Detect a cycle in an undirected graph using dfs

import java.util.*;

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello World");
        int V = 5;  // Adjust the number of vertices appropriately
        HashMap<Integer, ArrayList<Integer>> adj = makeAdjList(V);
        addEdge(0, 2, adj);
        addEdge(0, 1, adj);
        addEdge(0, 3, adj);
        addEdge(2, 4, adj);
        addEdge(4, 1, adj);
       
        System.out.println(adj);
        System.out.println("The graph has cycle: " + isCycle(V, adj));
    }

    public static boolean dfs(int node, int parent, HashMap<Integer,
ArrayList<Integer>> adj, boolean[] vis) {
        vis[node] = true;
        for (int it : adj.get(node)) {
            if (!vis[it]) {
                if (dfs(it, node, adj, vis)) {
                    return true;
                }
            } else if (it != parent) {
                return true;
            }
        }
        return false;
    }

    public static boolean isCycle(int V, HashMap<Integer,
ArrayList<Integer>> adj) {
        boolean[] vis = new boolean[V];
        for (int i = 0; i < V; i++) {
            if (!vis[i]) {
                if (dfs(i, -1, adj, vis)) {
                    return true;
                }
            }
        }
        return false;
    }

    public static HashMap<Integer, ArrayList<Integer>>
makeAdjList(int V) {
        HashMap<Integer, ArrayList<Integer>> adj = new HashMap<>();
        for (int i = 0; i < V; i++) {
            adj.put(i, new ArrayList<Integer>());
        }
        return adj;
    }

    public static void addEdge(int src, int dest,
HashMap<Integer, ArrayList<Integer>> adjList) {
        adjList.get(src).add(dest);
        adjList.get(dest).add(src);
    }
}

 

Friday 19 April 2024

Simplified dfs traversal in a graph

import java.util.*;

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello World");
        int V = 9;  // Total number of vertices (0 to 8)
        HashMap<Integer, ArrayList<Integer>> adj = makeAdjList(V);
        addEdge(0, 2, adj);
        addEdge(0, 1, adj);
        addEdge(2, 0, adj);
        addEdge(2, 4, adj);
        addEdge(1, 0, adj);
        addEdge(3, 0, adj);
        addEdge(4, 2, adj);
        addEdge(0, 3, adj);
        System.out.println(adj);
        boolean[] vis = new boolean[V];
        List<Integer> ans = new ArrayList<>();
        dfs(0, adj, vis, ans);
        System.out.println("The dfs traversal of the graph is:");
        System.out.println(ans);
    }

    // DFS of graph
    public static void dfs(int src, HashMap<Integer, ArrayList<Integer>> adj, boolean[] vis, List<Integer> ans) {
        vis[src] = true;
        ans.add(src);
        for (int it : adj.get(src)) {
            if (!vis[it]) {
                dfs(it, adj, vis, ans);
            }
        }
    }

    // Make adjList
    public static HashMap<Integer, ArrayList<Integer>> makeAdjList(int V) {
        HashMap<Integer, ArrayList<Integer>> adj = new HashMap<>();
        for (int i = 0; i < V; i++) {
            adj.put(i, new ArrayList<Integer>());
        }
        return adj;
    }

    // Add Edge
    public static void addEdge(int src, int dest, HashMap<Integer, ArrayList<Integer>> adjList) {
        adjList.get(src).add(dest);
        adjList.get(dest).add(src);
    }
}

 

Shortest path in undirected graph with unit weight starting from start node via bfs

import java.util.*;
class Pair<Key, Value>{
    public Key first;
    public Value second;
    public Pair(Key first, Value second)
    {
        this.first=first;
        this.second=second;
    }
}
public class Main
{
    public static void main(String[] args) {
        System.out.println("Hello World");
        ArrayList<Integer> arr = new ArrayList<>();
        HashMap<Integer, ArrayList<Integer>> adj = makeAdjList(8,arr);
        addEdge(0,1,adj);
        addEdge(0,3,adj);
        addEdge(1,3,adj);
        addEdge(1,2,adj);
        addEdge(3,4,adj);
        addEdge(4,5,adj);
        addEdge(5,6,adj);
        addEdge(2,6,adj);
        addEdge(6,7,adj);
        addEdge(6,8,adj);
        addEdge(7,8,adj);
       
        System.out.println(adj);
        bfs(0,adj);
    }
   
    // Make adjList
    public static HashMap<Integer, ArrayList<Integer>> makeAdjList(int V, ArrayList<Integer> arr) {
        HashMap<Integer, ArrayList<Integer>> adj = new HashMap<>();
        for(int i=0;i<V+1;i++)
        {
            adj.put(i,new ArrayList<Integer>()) ;
        }
        return adj;
    }
   
    // Add Edge
    public static void addEdge(int src, int dest, HashMap<Integer, ArrayList<Integer>> adjList)
    {
        adjList.get(src).add(dest);
        adjList.get(dest).add(src);
    }
   
    // BFS traversal
    public static void bfs(int start, HashMap<Integer, ArrayList<Integer>> adjList)
    {
        int V = adjList.size();
        int dist[] = new int[V];
        Arrays.fill(dist,Integer.MAX_VALUE);
        dist[0]=0;
        Queue<Pair<Integer,Integer>> q = new LinkedList<>();
        q.add(new Pair(0,0));
        while(!q.isEmpty())
        {
            int node=q.peek().first;
            int distance_node = q.peek().second;
            q.poll();
            for(int it: adjList.get(node))
            {
                if(distance_node + 1 < dist[it])
                {
                    dist[it]=distance_node + 1;
                    q.add(new Pair(it,distance_node + 1));
                }
            }
        }
        for(int it: dist)
        {
            System.out.print(it +" ");
        }
    }
}

BFS Q1) Level of nodes

Problem link: https://www.geeksforgeeks.org/problems/level-of-nodes-1587115620/1 

class Solution
{
    //Function to find the level of node X.
    int nodeLevel(int V, ArrayList<ArrayList<Integer>> adj, int x) {
        int ans = -1;
        boolean[] vis = new boolean[V];
        Arrays.fill(vis, false);
        Queue<Integer> q = new LinkedList<>();
        q.add(0);
        vis[0] = true;
        boolean fg = false;
        while (!q.isEmpty()) {
            int size = q.size();
            ans++; // Increment level for each level of nodes
            for (int i = 0; i < size; i++) {
                int node = q.poll();
                if (node == x) return ans; // If the target node is found, return its level
                for (int it : adj.get(node)) {
                    if (!vis[it]) {
                        vis[it] = true;
                        q.add(it);
                    }
                }
            }
        }
        return -1; // Return -1 if the target node is not found
    }
   
}

Simplified cycle detection via bfs

import java.util.*;
class Pair<Key, Value>{
    public Key first;
    public Value second;
    public Pair(Key first, Value second)
    {
        this.first=first;
        this.second=second;
    }
}
public class Main
{
    public static void main(String[] args) {
        System.out.println("Hello World");
        ArrayList<Integer> arr = new ArrayList<>();
        HashMap<Integer, ArrayList<Integer>> adj = makeAdjList(10,arr);
        addEdge(0,1,adj);
        addEdge(0,2,adj);
        addEdge(1,3,adj);
        addEdge(2,3,adj);
        addEdge(0,2,adj);
        addEdge(3,4,adj);
        addEdge(3,5,adj);
        addEdge(4,6,adj);
        addEdge(4,7,adj);
        addEdge(5,8,adj);
        addEdge(5,9,adj);
        addEdge(6,10,adj);
        addEdge(7,10,adj);
        addEdge(8,10,adj);
        addEdge(9,10,adj);
        System.out.println(adj);
        bfs(0,adj);
        System.out.println("Given graph contains cycle or not: true/false ?");
        System.out.println(isCycle(10,adj));
    }
   
    // Make adjList
    public static HashMap<Integer, ArrayList<Integer>> makeAdjList(int V, ArrayList<Integer> arr) {
        HashMap<Integer, ArrayList<Integer>> adj = new HashMap<>();
        for(int i=0;i<V+1;i++)
        {
            adj.put(i,new ArrayList<Integer>()) ;
        }
        return adj;
    }
   
    // Add Edge
    public static void addEdge(int src, int dest, HashMap<Integer, ArrayList<Integer>> adjList)
    {
        adjList.get(src).add(dest);
        adjList.get(dest).add(src);
    }
   
    // BFS traversal
    public static void bfs(int start, HashMap<Integer, ArrayList<Integer>> adjList)
    {
        ArrayList<Integer> ans = new ArrayList<>();
        int V = adjList.size();
        boolean vis[] = new boolean[V];
        Arrays.fill(vis,false);
        Queue<Integer> q = new LinkedList<>();
        q.add(0);
        vis[0]=true;
        while(!q.isEmpty())
        {
            int node=q.poll();
            ans.add(node);
            for(int it: adjList.get(node))
            {
                if(vis[it]==false)
                {
                    vis[it]=true;
                    q.add(it);
                }
            }
        }
        System.out.println(ans);
    }
   
    // Cycle detection in a graph via bfs traversal
    public static boolean checkCycle(int src, boolean vis[], int V, HashMap<Integer, ArrayList<Integer>> adjList)
    {
        //boolean vis[] = new boolean[V+1];
        //Arrays.fill(vis,false);
         Queue<Pair<Integer,Integer>> q = new LinkedList<>();
         q.add(new Pair(src,-1));
         vis[src]=true;
         while(!q.isEmpty())
         {
             int node=q.peek().first;
             int parent=q.peek().second;
             q.poll();
             for(int it: adjList.get(node))
             {
                 if(vis[it]==false)
                 {
                     vis[it]=true;
                     q.add(new Pair(it,node));
                 }
                 else if(parent!=it) return true;
             }
         }
         return false;
    }
   
    // Main cycle detection function using above
    public static boolean isCycle(int V, HashMap<Integer, ArrayList<Integer>> adjList)
    {
        boolean vis[] = new boolean[V+1];
        Arrays.fill(vis,false);
        for(int i=0;i<V;i++)
        {
            if(vis[i]==false)
            {
                if(checkCycle(i,vis,V,adjList)) return true;
            }
        }
        return false;
    }
}

Simplified bfs traversal in a graph

import java.util.*;
public class Main
{
    public static void main(String[] args) {
        System.out.println("Hello World");
        ArrayList<Integer> arr = new ArrayList<>();
        HashMap<Integer, ArrayList<Integer>> adj = makeAdjList(10,arr);
        addEdge(0,1,adj);
        addEdge(1,3,adj);
        addEdge(2,3,adj);
        addEdge(0,2,adj);
        addEdge(3,4,adj);
        addEdge(3,5,adj);
        addEdge(4,6,adj);
        addEdge(4,7,adj);
        addEdge(5,8,adj);
        addEdge(5,9,adj);
        addEdge(6,10,adj);
        addEdge(7,10,adj);
        addEdge(8,10,adj);
        addEdge(9,10,adj);
        System.out.println(adj);
        bfs(0,adj);
    }
   
    // Make adjList
    public static HashMap<Integer, ArrayList<Integer>> makeAdjList(int V, ArrayList<Integer> arr) {
        HashMap<Integer, ArrayList<Integer>> adj = new HashMap<>();
        for(int i=0;i<V+1;i++)
        {
            adj.put(i,new ArrayList<Integer>()) ;
        }
        return adj;
    }
   
    // Add Edge
    public static void addEdge(int src, int dest, HashMap<Integer, ArrayList<Integer>> adjList)
    {
        adjList.get(src).add(dest);
        adjList.get(dest).add(src);
    }
   
    // BFS traversal
    public static void bfs(int start, HashMap<Integer, ArrayList<Integer>> adjList)
    {
        ArrayList<Integer> ans = new ArrayList<>();
        int V = adjList.size();
        boolean vis[] = new boolean[V];
        Arrays.fill(vis,false);
        Queue<Integer> q = new LinkedList<>();
        q.add(0);
        vis[0]=true;
        while(!q.isEmpty())
        {
            int node=q.poll();
            ans.add(node);
            for(int it: adjList.get(node))
            {
                if(vis[it]==false)
                {
                    vis[it]=true;
                    q.add(it);
                }
            }
        }
        System.out.println(ans);
    }
}

Simplified Make adjacency list and add edge in graph

import java.util.*;
public class Main
{
    public static void main(String[] args) {
        System.out.println("Hello World");
        ArrayList<Integer> arr = new ArrayList<>();
        HashMap<Integer, ArrayList<Integer>> adj = makeAdjList(3,arr);
        addEdge(0,1,adj);
        addEdge(1,3,adj);
        addEdge(2,3,adj);
        addEdge(0,2,adj);
        System.out.println(adj);
    }
   
    // Make adjList
    public static HashMap<Integer, ArrayList<Integer>> makeAdjList(int V, ArrayList<Integer> arr) {
        HashMap<Integer, ArrayList<Integer>> adj = new HashMap<>();
        for(int i=0;i<V+1;i++)
        {
            adj.put(i,new ArrayList<Integer>()) ;
        }
        return adj;
    }
   
    // Add Edge
    public static void addEdge(int src, int dest, HashMap<Integer, ArrayList<Integer>> adjList)
    {
        adjList.get(src).add(dest);
        adjList.get(dest).add(src);
    }
}

Cycle detection in Graph via BFS

import java.util.*;

class Pair<Key, Value> {
    public Key first;
    public Value second;

    public Pair(Key first, Value second) {
        this.first = first;
        this.second = second;
    }
}
public class Main
{
    public static void main(String[] args) {
        System.out.println("Hello World");
        HashMap<Integer, ArrayList<Integer>> adjList = new HashMap<>();

        // Adding nodes to the graph
        for (int i = 0; i <= 8; i++) {
            adjList.put(i, new ArrayList<>());
        }

        // Adding edges to the graph
        addEdge(adjList, 1, 2);
        addEdge(adjList, 1, 3);
        addEdge(adjList, 3, 4);
        addEdge(adjList, 3, 6);
        addEdge(adjList, 6, 8);
        addEdge(adjList, 7, 5);
        addEdge(adjList, 2, 5);

        // Print the adjacency list
        System.out.println("Adjacency List: " + adjList);
        System.out.println("The graph has cycle: true/false ?");
        //ArrayList < Integer > ans = bfsOfGraph(7, adjList);
        //int n = ans.size();
        /*for(int i = 0;i<n;i++) {
            //System.out.print(ans.get(i)+" ");
           
        }*/
        System.out.println(isCycle(8,adjList));
    }
   
    public static boolean isCycle(int V, HashMap<Integer, ArrayList<Integer>> adjList)
    {
        boolean vis[] = new boolean[V+1];
        Arrays.fill(vis,false);
        for(int i=0;i<V;i++)
        {
            if(vis[i] == false)
            {
                if(bfsOfGraph(i, vis, V,adjList)) return true;
            }
        }
        return false;
    }
   
    public static boolean bfsOfGraph(int src, boolean vis[], int V, HashMap<Integer, ArrayList<Integer>> adjList) { // V is last number(max num) of graph
        //ArrayList < Integer > bfs = new ArrayList < > ();
        //boolean vis[] = new boolean[V+1];
        Queue <Pair<Integer,Integer>> q = new LinkedList < > ();
        q.add(new Pair(src,-1));
        vis[src] = true;
        while (!q.isEmpty()) {
            int node = q.peek().first;
            int parent = q.peek().second;
            q.poll();
            //bfs.add(node);
            for (int it: adjList.get(node)) {
                if (vis[it] == false) {
                    vis[it] = true;
                    q.add(new Pair(it,node));
                }
                else if(parent != it) return true;
            }
        }

        return false;
    }
   
   
    // Helper method to add an edge to the graph
    public static void addEdge(HashMap<Integer, ArrayList<Integer>> adjList, int source, int destination) {
        adjList.get(source).add(destination);
        adjList.get(destination).add(source); // If the graph is undirected
    }
}

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