Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package g1501_1600.s1514_path_with_maximum_probability;

// #Medium #Heap_Priority_Queue #Graph #Shortest_Path
// #2022_04_09_Time_31_ms_(93.10%)_Space_51.7_MB_(98.80%)

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

public class Solution {
public double maxProbability(int n, int[][] edges, double[] succProb, int start, int end) {
List<Integer>[] nodeToNodesList = new List[n];
List<Double>[] nodeToProbabilitiesList = new List[n];
for (int i = 0; i < n; i++) {
nodeToNodesList[i] = new ArrayList<>();
nodeToProbabilitiesList[i] = new ArrayList<>();
}
for (int i = 0; i < edges.length; i++) {
int u = edges[i][0];
int v = edges[i][1];
double w = succProb[i];
nodeToNodesList[u].add(v);
nodeToProbabilitiesList[u].add(w);

nodeToNodesList[v].add(u);
nodeToProbabilitiesList[v].add(w);
}

double[] probabilities = new double[n];
probabilities[start] = 1.0;
boolean[] visited = new boolean[n];
Queue<Integer> queue = new ArrayDeque<>();
queue.add(start);
visited[start] = true;
while (!queue.isEmpty()) {
int u = queue.poll();
visited[u] = false;

for (int i = 0; i < nodeToNodesList[u].size(); i++) {
int v = nodeToNodesList[u].get(i);
double w = nodeToProbabilitiesList[u].get(i);
if (probabilities[u] * w > probabilities[v]) {
probabilities[v] = probabilities[u] * w;
if (!visited[v]) {
visited[v] = true;
queue.add(v);
}
}
}
}

return probabilities[end];
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
1514\. Path with Maximum Probability

Medium

You are given an undirected weighted graph of `n` nodes (0-indexed), represented by an edge list where `edges[i] = [a, b]` is an undirected edge connecting the nodes `a` and `b` with a probability of success of traversing that edge `succProb[i]`.

Given two nodes `start` and `end`, find the path with the maximum probability of success to go from `start` to `end` and return its success probability.

If there is no path from `start` to `end`, **return 0**. Your answer will be accepted if it differs from the correct answer by at most **1e-5**.

**Example 1:**

**![](https://assets.leetcode.com/uploads/2019/09/20/1558_ex1.png)**

**Input:** n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2

**Output:** 0.25000

**Explanation:** There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 \* 0.5 = 0.25.

**Example 2:**

**![](https://assets.leetcode.com/uploads/2019/09/20/1558_ex2.png)**

**Input:** n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2

**Output:** 0.30000

**Example 3:**

**![](https://assets.leetcode.com/uploads/2019/09/20/1558_ex3.png)**

**Input:** n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2

**Output:** 0.00000

**Explanation:** There is no path between 0 and 2.

**Constraints:**

* `2 <= n <= 10^4`
* `0 <= start, end < n`
* `start != end`
* `0 <= a, b < n`
* `a != b`
* `0 <= succProb.length == edges.length <= 2*10^4`
* `0 <= succProb[i] <= 1`
* There is at most one edge between every two nodes.
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package g1501_1600.s1515_best_position_for_a_service_centre;

// #Hard #Math #Geometry #Randomized #2022_04_09_Time_6_ms_(87.14%)_Space_43_MB_(5.71%)

import java.util.ArrayList;
import java.util.List;

public class Solution {
public double getMinDistSum(int[][] positions) {
double minX = Integer.MAX_VALUE;
double minY = Integer.MAX_VALUE;
double maxX = Integer.MIN_VALUE;
double maxY = Integer.MIN_VALUE;
for (int[] pos : positions) {
maxX = Math.max(maxX, pos[0]);
maxY = Math.max(maxY, pos[1]);
minX = Math.min(minX, pos[0]);
minY = Math.min(minY, pos[1]);
}
double xMid = minX + (maxX - minX) / 2;
double yMid = minY + (maxY - minY) / 2;

double jump = Math.max(maxX - minX, maxY - minY);

double ans = getTotalDistance(xMid, yMid, positions);

while (jump > 0.00001) {
List<double[]> list = getFourCorners(xMid, yMid, jump);
boolean found = false;
for (double[] point : list) {
double pointAns = getTotalDistance(point[0], point[1], positions);
if (ans > pointAns) {
xMid = point[0];
yMid = point[1];
ans = pointAns;
found = true;
}
}

if (!found) {
jump = jump / 2;
}
}

return ans;
}

private List<double[]> getFourCorners(double xMid, double yMid, double jump) {
List<double[]> list = new ArrayList<>();
list.add(new double[] {xMid - jump, yMid + jump});
list.add(new double[] {xMid + jump, yMid + jump});
list.add(new double[] {xMid - jump, yMid - jump});
list.add(new double[] {xMid + jump, yMid - jump});

return list;
}

private double getTotalDistance(double x, double y, int[][] positions) {
double totalDistanceSum = 0;
for (int[] point : positions) {
double xDistance = x - point[0];
double yDistance = y - point[1];
totalDistanceSum += Math.sqrt(xDistance * xDistance + yDistance * yDistance);
}

return totalDistanceSum;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
1515\. Best Position for a Service Centre

Hard

A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that **the sum of the euclidean distances to all customers is minimum**.

Given an array `positions` where <code>positions[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> is the position of the `ith` customer on the map, return _the minimum sum of the euclidean distances_ to all customers.

In other words, you need to choose the position of the service center <code>[x<sub>centre</sub>, y<sub>centre</sub>]</code> such that the following formula is minimized:

![](https://assets.leetcode.com/uploads/2020/06/25/q4_edited.jpg)

Answers within <code>10<sup>-5</sup></code> of the actual value will be accepted.

**Example 1:**

![](https://assets.leetcode.com/uploads/2020/06/25/q4_e1.jpg)

**Input:** positions = [[0,1],[1,0],[1,2],[2,1]]

**Output:** 4.00000

**Explanation:** As shown, you can see that choosing [x<sub>centre</sub>, y<sub>centre</sub>] = [1, 1] will make the distance to each customer = 1, the sum of all distances is 4 which is the minimum possible we can achieve.

**Example 2:**

![](https://assets.leetcode.com/uploads/2020/06/25/q4_e3.jpg)

**Input:** positions = [[1,1],[3,3]]

**Output:** 2.82843

**Explanation:** The minimum possible sum of distances = sqrt(2) + sqrt(2) = 2.82843

**Constraints:**

* `1 <= positions.length <= 50`
* `positions[i].length == 2`
* <code>0 <= x<sub>i</sub>, y<sub>i</sub> <= 100</code>
17 changes: 17 additions & 0 deletions src/main/java/g1501_1600/s1518_water_bottles/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package g1501_1600.s1518_water_bottles;

// #Easy #Math #Simulation #2022_04_09_Time_0_ms_(100.00%)_Space_40.5_MB_(71.92%)

public class Solution {
public int numWaterBottles(int numBottles, int numExchange) {
int drunk = numBottles;
int emptyBottles = numBottles;
while (emptyBottles >= numExchange) {
int exchangedBottles = emptyBottles / numExchange;
drunk += exchangedBottles;
int unUsedEmptyBottles = emptyBottles % numExchange;
emptyBottles = exchangedBottles + unUsedEmptyBottles;
}
return drunk;
}
}
34 changes: 34 additions & 0 deletions src/main/java/g1501_1600/s1518_water_bottles/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
1518\. Water Bottles

Easy

There are `numBottles` water bottles that are initially full of water. You can exchange `numExchange` empty water bottles from the market with one full water bottle.

The operation of drinking a full water bottle turns it into an empty bottle.

Given the two integers `numBottles` and `numExchange`, return _the **maximum** number of water bottles you can drink_.

**Example 1:**

![](https://assets.leetcode.com/uploads/2020/07/01/sample_1_1875.png)

**Input:** numBottles = 9, numExchange = 3

**Output:** 13

**Explanation:** You can exchange 3 empty bottles to get 1 full water bottle. Number of water bottles you can drink: 9 + 3 + 1 = 13.

**Example 2:**

![](https://assets.leetcode.com/uploads/2020/07/01/sample_2_1875.png)

**Input:** numBottles = 15, numExchange = 4

**Output:** 19

**Explanation:** You can exchange 4 empty bottles to get 1 full water bottle. Number of water bottles you can drink: 15 + 3 + 1 = 19.

**Constraints:**

* `1 <= numBottles <= 100`
* `2 <= numExchange <= 100`
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package g1501_1600.s1519_number_of_nodes_in_the_sub_tree_with_the_same_label;

// #Medium #Depth_First_Search #Breadth_First_Search #Tree
// #2022_04_09_Time_60_ms_(98.13%)_Space_107.7_MB_(97.66%)

import java.util.ArrayList;

public class Solution {
public int[] countSubTrees(int n, int[][] edges, String labelsString) {
int[] labelsCount = new int[n];
if (n <= 0 || edges == null || labelsString == null) {
return labelsCount;
}

int[] labels = new int[n];
int nodeNumber = 0;
for (char label : labelsString.toCharArray()) {
labels[nodeNumber++] = label - 'a';
}

ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
for (int i = 0; i < n; i++) {
graph.add(new ArrayList<>());
}
for (int[] edge : edges) {
int parent = edge[0];
int child = edge[1];
graph.get(parent).add(child);
graph.get(child).add(parent);
}

getLabelsFrequency(0, graph, labels, labelsCount, 0);

return labelsCount;
}

private int[] getLabelsFrequency(
int root,
ArrayList<ArrayList<Integer>> graph,
int[] labels,
int[] labelsCount,
int parent) {
int[] labelsFrequency = new int[26];
int rootLabel = labels[root];
labelsFrequency[rootLabel]++;

for (int child : graph.get(root)) {
if (child == parent) {
continue;
}
int[] childLabelsFrequency =
getLabelsFrequency(child, graph, labels, labelsCount, root);
for (int i = 0; i < childLabelsFrequency.length; i++) {
labelsFrequency[i] += childLabelsFrequency[i];
}
}

labelsCount[root] = labelsFrequency[rootLabel];
return labelsFrequency;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
1519\. Number of Nodes in the Sub-Tree With the Same Label

Medium

You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of `n` nodes numbered from `0` to `n - 1` and exactly `n - 1` `edges`. The **root** of the tree is the node `0`, and each node of the tree has **a label** which is a lower-case character given in the string `labels` (i.e. The node with the number `i` has the label `labels[i]`).

The `edges` array is given on the form <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code>, which means there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the tree.

Return _an array of size `n`_ where `ans[i]` is the number of nodes in the subtree of the <code>i<sup>th</sup></code> node which have the same label as node `i`.

A subtree of a tree `T` is the tree consisting of a node in `T` and all of its descendant nodes.

**Example 1:**

![](https://assets.leetcode.com/uploads/2020/07/01/q3e1.jpg)

**Input:** n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], labels = "abaedcd"

**Output:** [2,1,1,1,1,1,1]

**Explanation:** Node 0 has label 'a' and its sub-tree has node 2 with label 'a' as well, thus the answer is 2. Notice that any node is part of its sub-tree.

Node 1 has a label 'b'. The sub-tree of node 1 contains nodes 1,4 and 5, as nodes 4 and 5 have different labels than node 1, the answer is just 1 (the node itself).

**Example 2:**

![](https://assets.leetcode.com/uploads/2020/07/01/q3e2.jpg)

**Input:** n = 4, edges = [[0,1],[1,2],[0,3]], labels = "bbbb"

**Output:** [4,2,1,1]

**Explanation:** The sub-tree of node 2 contains only node 2, so the answer is 1.

The sub-tree of node 3 contains only node 3, so the answer is 1.

The sub-tree of node 1 contains nodes 1 and 2, both have label 'b', thus the answer is 2.

The sub-tree of node 0 contains nodes 0, 1, 2 and 3, all with label 'b', thus the answer is 4.

**Example 3:**

![](https://assets.leetcode.com/uploads/2020/07/01/q3e3.jpg)

**Input:** n = 5, edges = [[0,1],[0,2],[1,3],[0,4]], labels = "aabab"

**Output:** [3,2,1,1,1]

**Constraints:**

* <code>1 <= n <= 10<sup>5</sup></code>
* `edges.length == n - 1`
* `edges[i].length == 2`
* <code>0 <= a<sub>i</sub>, b<sub>i</sub> < n</code>
* <code>a<sub>i</sub> != b<sub>i</sub></code>
* `labels.length == n`
* `labels` is consisting of only of lowercase English letters.
Loading