Showing posts with label LeetCode. Show all posts
Showing posts with label LeetCode. Show all posts

LeetCode Solution: Number of Good Paths

 Question: There is a tree (i.e. a connected, undirected graph with no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges.

You are given a 0-indexed integer array vals of length n where vals[i] denotes the value of the ith node. You are also given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting nodes ai and bi.

A good path is a simple path that satisfies the following conditions:

The starting node and the ending node have the same value.

All nodes between the starting node and the ending node have values less than or equal to the starting node (i.e. the starting node's value should be the maximum value along the path).

Return the number of distinct good paths.

Note that a path and its reverse are counted as the same path. For example, 0 -> 1 is considered to be the same as 1 -> 0. A single node is also considered as a valid path.

Constraints:

  • n == vals.length
  • 1 <= n <= 3 * 104
  • 0 <= vals[i] <= 105
  • edges.length == n - 1
  • edges[i].length == 2
  • 0 <= ai, bi < n
  • ai != bi
  • edges represents a valid tree.

 

Solution: To solve this problem, you can use a depth-first search (DFS) algorithm to traverse the tree, starting from each node. For each node, you can check whether the path from that node to any of its descendant nodes satisfies the conditions for a good path. If it does, you can increment a counter variable.

This algorithm first convert the input edge list to adjacency list to traverse the tree easily. Then it iterates over all the nodes and for each node it calls a dfs function to traverse the tree and check the conditions for good path. If the path is good it increments the counter variable. Finally, it returns the count of good paths.


class Solution {

    int[] parents;

    private int find(int x){

        if(x != parents[x]) 

            parents[x] = find(parents[x]);

        return parents[x];

    }

    public int numberOfGoodPaths(int[] vals, int[][] edges) {

        int n = vals.length;

        if(n == 1) return 1;

        parents = new int[n];

        List<Integer> ids = new ArrayList<>();

        for(int i = 0; i < n; i++){

            parents[i] = i;

            ids.add(i);

        }


        Map<Integer, Set<Integer>> graph = new HashMap<>();

        

        for (int[] edge : edges) {

            int u = edge[0];

            int v = edge[1];

            

            graph.putIfAbsent(u, new HashSet<>());

            graph.putIfAbsent(v, new HashSet<>());

            

            graph.get(u).add(v);

            graph.get(v).add(u);

        }


        Collections.sort(ids, (a, b) -> (vals[a] - vals[b]));


        int ret = 0;

        for (int i = 0; i < n; i++) {

            int j = i + 1;

            while(j < n && vals[ids.get(j)] == vals[ids.get(i)]) j++;

            for (int k = i; k < j; k++) {

                int x = ids.get(k);

                for(int neighbor : graph.get(x)){

                    if (vals[x] >= vals[neighbor]) {

                        parents[find(x)] = find(neighbor);

                    }

                }

            }

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

            for(int k = i; k < j; k++){

                int root = find(ids.get(k));

                temp.put(root, temp.getOrDefault(root, 0) + 1);  // # of current val in the {root} group

            }


            for (int v : temp.values()){

                ret += v * (v + 1) / 2;

            }

            

            i = j - 1;

        }

        

        return ret;

    }

}

LeetCode Solution: Longest Path With Different Adjacent Characters

 Question: You are given a tree (i.e. a connected, undirected graph that has no cycles) rooted at node 0 consisting of n nodes numbered from 0 to n - 1. The tree is represented by a 0-indexed array parent of size n, where parent[i] is the parent of node i. Since node 0 is the root, parent[0] == -1.

You are also given a string s of length n, where s[i] is the character assigned to node i.

Return the length of the longest path in the tree such that no pair of adjacent nodes on the path have the same character assigned to them.

Constraints:

  • n == parent.length == s.length
  • 1 <= n <= 10^5
  • 0 <= parent[i] <= n - 1 for all i >= 1
  • parent[0] == -1
  • parent represents a valid tree.
  • s consists of only lowercase English letters.
Solution: You can solve this problem using dynamic programming.


  • Create an array dp of size n, where dp[i] represents the longest path ending at node i that satisfies the given condition.
  • Initialize dp[i] as 1 for all i, since every node itself is a valid path of length 1.
  • Iterate through the nodes in the tree in a bottom-up fashion, starting from the leaf nodes and working towards the root. For each node i, iterate through its children j and update dp[i] as follows:
                If s[i] is different from s[j], dp[i] = max(dp[i], dp[j] + 1)
  • Return the maximum value in the dp array.

Note that, in this solution, the time complexity is O(n) and the space complexity is O(n) as well.

class Solution {
    public int longestPath(int[] parent, String s) {
        int n = parent.length;
        int[] dp = new int[n];
        Arrays.fill(dp, 1);
        
        for (int i = n - 1; i >= 0; i--) {
            for (int j = 0; j < n; j++) {
                if (parent[j] == i && s.charAt(i) != s.charAt(j)) {
                    dp[i] = Math.max(dp[i], dp[j] + 1);
                }
            }
        }
        int max = 0;
        for (int i = 0; i < n; i++) {
            max = Math.max(max, dp[i]);
        }
        return max;
    }
}

LeetCode Solution: Same Tree

 Question: Given the roots of two binary trees p and q, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.

Constraints:

  • The number of nodes in both trees is in the range [0, 100].
  • -10^4 <= Node.val <= 10^4
Solution: This solution first checks if both trees are empty, in which case they are the same. If only one of the trees is empty, they are not the same. If the values of the nodes are different, the trees are not the same. Otherwise, the function recursively checks the left and right subtrees.

class Solution {

    public boolean isSameTree(TreeNode p, TreeNode q) {
        // If both trees are empty, they are the same
        if (p == null && q == null) {
            return true;
        }
        // If only one tree is empty, they are not the same
        if (p == null || q == null) {
            return false;
        }
        // If the values of the nodes are different, the trees are not the same
        if (p.val != q.val) {
            return false;
        }
        // Check the left and right subtrees recursively
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
}

LeetCode Solution: Max Points on a Line

 Question: Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line.

Constraints:

  • 1 <= points.length <= 300
  • points[i].length == 2
  • -104 <= xi, yi <= 104
  • All the points are unique.

Solution: 
To solve this problem, you can iterate through each point in the array and check how many other points lie on the same straight line with it. You can do this by calculating the slope between the two points and checking if the slope is the same for all other points.

import java.util.HashMap;

import java.util.Map;

class Solution {
    public int maxPoints(int[][] points) {
        int maxPoints = 0;
        for (int i = 0; i < points.length; i++) {
            int samePoints = 1;
            Map<String, Integer> slopeCount = new HashMap<>();
            for (int j = 0; j < points.length; j++) {
                if (i == j) {
                    continue;
                }
                int dx = points[i][0] - points[j][0];
                int dy = points[i][1] - points[j][1];
                if (dx == 0 && dy == 0) {
                    samePoints++;
                    continue;
                }
                int gcd = gcd(dx, dy);
                String slope = (dy / gcd) + "/" + (dx / gcd);
                slopeCount.put(slope, slopeCount.getOrDefault(slope, 1) + 1);
            }
            int sameSlopePoints = samePoints;
            for (int count : slopeCount.values()) {
                sameSlopePoints = Math.max(sameSlopePoints, count);
            }
            maxPoints = Math.max(maxPoints, sameSlopePoints);
        }
        return maxPoints;
    }

    private static int gcd(int a, int b) {
        if (b == 0) {
            return a;
        }
        return gcd(b, a % b);
    }
}

LeetCode Solution: Maximum Ice Cream Bars question

Question: It is a sweltering summer day, and a boy wants to buy some ice cream bars.

At the store, there are n ice cream bars. You are given an array costs of length n, where costs[i] is the price of the ith ice cream bar in coins. The boy initially has coins coins to spend, and he wants to buy as many ice cream bars as possible. 

Return the maximum number of ice cream bars the boy can buy with coins coins.

Note: The boy can buy the ice cream bars in any order.


Solution: This solution first sorts the costs array in ascending order, and then iterates through the costs array. For each cost, it checks if the cost is less than or equal to the available coins. If it is, it adds one to the maximum number of ice cream bars and subtracts the cost from the available coins. If the cost is greater than the available coins, the loop is broken and the maximum number of ice cream bars is returned.

public class IceCreamBars {

    public int maximumIceCreamBars(int[] costs, int coins) {

        // Sort the costs array in ascending order

        Arrays.sort(costs);

        

        // Initialize the maximum number of ice cream bars to 0

        int maxIceCreamBars = 0;

        

        // Iterate through the costs array

        for (int cost : costs) {

            // If the current cost is greater than the available coins, break the loop

            if (cost > coins) {

                break;

            }

            // Otherwise, add one to the maximum number of ice cream bars and subtract the cost from the available coins

            maxIceCreamBars++;

            coins -= cost;

        }

        

        return maxIceCreamBars;

    }

}