Skip to content

Commit 4bb070f

Browse files
authored
Added tasks 2503, 2506, 2507, 2508, 2509
1 parent 97e9a06 commit 4bb070f

File tree

15 files changed

+612
-0
lines changed

15 files changed

+612
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package g2501_2600.s2503_maximum_number_of_points_from_grid_queries;
2+
3+
// #Hard #Array #Sorting #Heap_Priority_Queue #Union_Find #Breadth_First_Search
4+
// #2023_03_20_Time_47_ms_(96.38%)_Space_59.9_MB_(49.28%)
5+
6+
import java.util.ArrayDeque;
7+
import java.util.Arrays;
8+
import java.util.Comparator;
9+
import java.util.PriorityQueue;
10+
import java.util.Queue;
11+
12+
public class Solution {
13+
private final int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
14+
15+
public int[] maxPoints(int[][] grid, int[] q) {
16+
int r = grid.length;
17+
int c = grid[0].length;
18+
int[] res = new int[q.length];
19+
Integer[] index = new Integer[q.length];
20+
for (int i = 0; i < q.length; i++) {
21+
index[i] = i;
22+
}
23+
Arrays.sort(index, Comparator.comparingInt(o -> q[o]));
24+
Queue<int[]> q1 = new ArrayDeque<>();
25+
PriorityQueue<int[]> q2 = new PriorityQueue<>(Comparator.comparingInt(a -> a[2]));
26+
q2.offer(new int[] {0, 0, grid[0][0]});
27+
boolean[][] visited = new boolean[r][c];
28+
int count = 0;
29+
visited[0][0] = true;
30+
for (int i = 0; i < q.length; i++) {
31+
int currLimit = q[index[i]];
32+
while (!q2.isEmpty() && q2.peek()[2] < currLimit) {
33+
q1.offer(q2.poll());
34+
}
35+
while (!q1.isEmpty()) {
36+
int[] curr = q1.poll();
37+
count++;
38+
for (int[] dir : dirs) {
39+
int x = dir[0] + curr[0];
40+
int y = dir[1] + curr[1];
41+
if (x < 0 || y < 0 || x >= r || y >= c || visited[x][y]) {
42+
continue;
43+
}
44+
if (!visited[x][y] && grid[x][y] < currLimit) {
45+
q1.offer(new int[] {x, y, grid[x][y]});
46+
} else {
47+
q2.offer(new int[] {x, y, grid[x][y]});
48+
}
49+
visited[x][y] = true;
50+
}
51+
}
52+
res[index[i]] = count;
53+
}
54+
return res;
55+
}
56+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
2503\. Maximum Number of Points From Grid Queries
2+
3+
Hard
4+
5+
You are given an `m x n` integer matrix `grid` and an array `queries` of size `k`.
6+
7+
Find an array `answer` of size `k` such that for each integer `queries[i]` you start in the **top left** cell of the matrix and repeat the following process:
8+
9+
* If `queries[i]` is **strictly** greater than the value of the current cell that you are in, then you get one point if it is your first time visiting this cell, and you can move to any **adjacent** cell in all `4` directions: up, down, left, and right.
10+
* Otherwise, you do not get any points, and you end this process.
11+
12+
After the process, `answer[i]` is the **maximum** number of points you can get. **Note** that for each query you are allowed to visit the same cell **multiple** times.
13+
14+
Return _the resulting array_ `answer`.
15+
16+
**Example 1:**
17+
18+
![](https://assets.leetcode.com/uploads/2022/10/19/yetgriddrawio.png)
19+
20+
**Input:** grid = [[1,2,3],[2,5,7],[3,5,1]], queries = [5,6,2]
21+
22+
**Output:** [5,8,1]
23+
24+
**Explanation:** The diagrams above show which cells we visit to get points for each query.
25+
26+
**Example 2:**
27+
28+
![](https://assets.leetcode.com/uploads/2022/10/20/yetgriddrawio-2.png)
29+
30+
**Input:** grid = [[5,2,1],[1,1,2]], queries = [3]
31+
32+
**Output:** [0]
33+
34+
**Explanation:** We can not get any points because the value of the top left cell is already greater than or equal to 3.
35+
36+
**Constraints:**
37+
38+
* `m == grid.length`
39+
* `n == grid[i].length`
40+
* `2 <= m, n <= 1000`
41+
* <code>4 <= m * n <= 10<sup>5</sup></code>
42+
* `k == queries.length`
43+
* <code>1 <= k <= 10<sup>4</sup></code>
44+
* <code>1 <= grid[i][j], queries[i] <= 10<sup>6</sup></code>
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package g2501_2600.s2506_count_pairs_of_similar_strings;
2+
3+
// #Easy #Array #String #Hash_Table #2023_03_20_Time_6_ms_(85.15%)_Space_42.4_MB_(59.86%)
4+
5+
import java.util.HashMap;
6+
import java.util.Map;
7+
8+
public class Solution {
9+
public int similarPairs(String[] words) {
10+
int len = words.length;
11+
if (len == 1) {
12+
return 0;
13+
}
14+
byte[][] alPh = new byte[len][26];
15+
Map<String, Integer> map = new HashMap<>();
16+
for (int i = 0; i < len; i++) {
17+
String word = words[i];
18+
for (char c : word.toCharArray()) {
19+
int idx = c - 'a';
20+
if (alPh[i][idx] == 0) {
21+
alPh[i][idx]++;
22+
}
23+
}
24+
String s = new String(alPh[i]);
25+
if (map.containsKey(s)) {
26+
map.put(s, map.get(s) + 1);
27+
} else {
28+
map.put(s, 1);
29+
}
30+
}
31+
int pairs = 0;
32+
for (Map.Entry<String, Integer> entry : map.entrySet()) {
33+
int freq = entry.getValue();
34+
if (freq > 1) {
35+
pairs += (freq * (freq - 1)) / 2;
36+
}
37+
}
38+
return pairs;
39+
}
40+
}
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
2506\. Count Pairs Of Similar Strings
2+
3+
Easy
4+
5+
You are given a **0-indexed** string array `words`.
6+
7+
Two strings are **similar** if they consist of the same characters.
8+
9+
* For example, `"abca"` and `"cba"` are similar since both consist of characters `'a'`, `'b'`, and `'c'`.
10+
* However, `"abacba"` and `"bcfd"` are not similar since they do not consist of the same characters.
11+
12+
Return _the number of pairs_ `(i, j)` _such that_ `0 <= i < j <= word.length - 1` _and the two strings_ `words[i]` _and_ `words[j]` _are similar_.
13+
14+
**Example 1:**
15+
16+
**Input:** words = ["aba","aabb","abcd","bac","aabc"]
17+
18+
**Output:** 2
19+
20+
**Explanation:** There are 2 pairs that satisfy the conditions:
21+
22+
- i = 0 and j = 1 : both words[0] and words[1] only consist of characters 'a' and 'b'.
23+
24+
- i = 3 and j = 4 : both words[3] and words[4] only consist of characters 'a', 'b', and 'c'.
25+
26+
**Example 2:**
27+
28+
**Input:** words = ["aabb","ab","ba"]
29+
30+
**Output:** 3
31+
32+
**Explanation:** There are 3 pairs that satisfy the conditions:
33+
34+
- i = 0 and j = 1 : both words[0] and words[1] only consist of characters 'a' and 'b'.
35+
36+
- i = 0 and j = 2 : both words[0] and words[2] only consist of characters 'a' and 'b'.
37+
38+
- i = 1 and j = 2 : both words[1] and words[2] only consist of characters 'a' and 'b'.
39+
40+
**Example 3:**
41+
42+
**Input:** words = ["nba","cba","dba"]
43+
44+
**Output:** 0
45+
46+
**Explanation:** Since there does not exist any pair that satisfies the conditions, we return 0.
47+
48+
**Constraints:**
49+
50+
* `1 <= words.length <= 100`
51+
* `1 <= words[i].length <= 100`
52+
* `words[i]` consist of only lowercase English letters.
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package g2501_2600.s2507_smallest_value_after_replacing_with_sum_of_prime_factors;
2+
3+
// #Medium #Math #Number_Theory #2023_03_20_Time_1_ms_(84.27%)_Space_40_MB_(31.46%)
4+
5+
import java.util.HashMap;
6+
import java.util.Map;
7+
8+
public class Solution {
9+
private final Map<Integer, Integer> memo = new HashMap<>();
10+
11+
public int smallestValue(int n) {
12+
while (get(n) != n) {
13+
n = get(n);
14+
}
15+
return n;
16+
}
17+
18+
private int get(int n) {
19+
if (memo.containsKey(n)) {
20+
return memo.get(n);
21+
}
22+
double r = Math.pow(n, 0.5);
23+
int r1 = (int) r;
24+
if (r - r1 == 0) {
25+
return 2 * get(r1);
26+
}
27+
int res = 0;
28+
for (int i = r1; i >= 2; i--) {
29+
if (n % i == 0) {
30+
res = get(i) + get(n / i);
31+
}
32+
}
33+
res = res == 0 ? n : res;
34+
memo.put(n, res);
35+
return res;
36+
}
37+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
2507\. Smallest Value After Replacing With Sum of Prime Factors
2+
3+
Medium
4+
5+
You are given a positive integer `n`.
6+
7+
Continuously replace `n` with the sum of its **prime factors**.
8+
9+
* Note that if a prime factor divides `n` multiple times, it should be included in the sum as many times as it divides `n`.
10+
11+
Return _the smallest value_ `n` _will take on._
12+
13+
**Example 1:**
14+
15+
**Input:** n = 15
16+
17+
**Output:** 5
18+
19+
**Explanation:** Initially, n = 15.
20+
21+
15 = 3 \* 5, so replace n with 3 + 5 = 8.
22+
23+
8 = 2 \* 2 \* 2, so replace n with 2 + 2 + 2 = 6.
24+
25+
6 = 2 \* 3, so replace n with 2 + 3 = 5.
26+
27+
5 is the smallest value n will take on.
28+
29+
**Example 2:**
30+
31+
**Input:** n = 3
32+
33+
**Output:** 3
34+
35+
**Explanation:** Initially, n = 3. 3 is the smallest value n will take on.
36+
37+
**Constraints:**
38+
39+
* <code>2 <= n <= 10<sup>5</sup></code>
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
package g2501_2600.s2508_add_edges_to_make_degrees_of_all_nodes_even;
2+
3+
// #Hard #Hash_Table #Graph #2023_03_20_Time_33_ms_(100.00%)_Space_109.7_MB_(42.70%)
4+
5+
import java.util.ArrayList;
6+
import java.util.HashSet;
7+
import java.util.List;
8+
import java.util.Set;
9+
10+
public class Solution {
11+
public boolean isPossible(int n, List<List<Integer>> edges) {
12+
// first find odd edge nodes
13+
int[] degree = new int[n + 1];
14+
for (List<Integer> edge : edges) {
15+
degree[edge.get(0)]++;
16+
degree[edge.get(1)]++;
17+
}
18+
List<Integer> oddNodes = new ArrayList<>();
19+
for (int i = 1; i <= n; i++) {
20+
if ((degree[i] & 1) == 1) {
21+
oddNodes.add(i);
22+
}
23+
if (oddNodes.size() > 4) {
24+
// cannot be larger than four
25+
return false;
26+
}
27+
}
28+
if ((oddNodes.size() & 1) == 1) {
29+
// can only have even numbers of odd nodes
30+
return false;
31+
} else if (oddNodes.isEmpty()) {
32+
// zero situation
33+
return true;
34+
}
35+
// find all edges of oddListNode
36+
Set[] adjList = new HashSet[oddNodes.size()];
37+
for (int i = 0; i < oddNodes.size(); i++) {
38+
adjList[i] = new HashSet<>();
39+
}
40+
for (List<Integer> edge : edges) {
41+
for (int i = 0; i < oddNodes.size(); i++) {
42+
if ((int) edge.get(0) == oddNodes.get(i)) {
43+
adjList[i].add(edge.get(1));
44+
}
45+
if ((int) edge.get(1) == oddNodes.get(i)) {
46+
adjList[i].add(edge.get(0));
47+
}
48+
}
49+
}
50+
// to see if it is two or four
51+
if (oddNodes.size() == 4) {
52+
// can only connect each other
53+
// have to detect if they have an edge or not
54+
return adjList[0].size() < (n - 1)
55+
&& adjList[1].size() < (n - 1)
56+
&& adjList[2].size() < (n - 1)
57+
&& adjList[3].size() < (n - 1)
58+
&& ((!adjList[0].contains(oddNodes.get(1))
59+
&& !adjList[1].contains(oddNodes.get(0))
60+
&& !adjList[2].contains(oddNodes.get(3))
61+
&& !adjList[3].contains(oddNodes.get(2)))
62+
|| (!adjList[0].contains(oddNodes.get(2))
63+
&& !adjList[2].contains(oddNodes.get(0))
64+
&& !adjList[1].contains(oddNodes.get(3))
65+
&& !adjList[3].contains(oddNodes.get(1)))
66+
|| (!adjList[0].contains(oddNodes.get(3))
67+
&& !adjList[1].contains(oddNodes.get(2))
68+
&& !adjList[2].contains(oddNodes.get(1))));
69+
} else {
70+
// if two dont have an edge, could use it
71+
if (adjList[0].contains(oddNodes.get(1))) {
72+
// need to find a spare node
73+
for (int i = 1; i <= n; i++) {
74+
if (adjList[0].contains(i) || adjList[1].contains(i)) {
75+
continue;
76+
}
77+
return true;
78+
}
79+
return false;
80+
}
81+
return true;
82+
}
83+
}
84+
}

0 commit comments

Comments
 (0)