Skip to content

Commit 727f728

Browse files
authored
Merge branch 'master' into feature/div
2 parents f17c022 + d28ad7a commit 727f728

File tree

4 files changed

+211
-0
lines changed

4 files changed

+211
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
# Explanation of the Program
2+
3+
### **Objective**
4+
The goal of the program is to count the number of distinct shortest paths from node `0` to node `n-1` in a weighted, undirected graph. The result is returned modulo \( 10^9 + 7 \).
5+
6+
---
7+
8+
### **Key Components**
9+
1. **Class `Pair`:**
10+
- Represents a pair of values (distance and node index).
11+
- Used for storing the distance of a node from the source and the index of the node.
12+
13+
2. **Adjacency List (`adj`):**
14+
- The graph is represented as an adjacency list where each node's neighbors and edge weights are stored.
15+
- The adjacency list is built using input data from the `roads` array.
16+
17+
3. **Priority Queue (`pq`):**
18+
- Implements a min-heap to efficiently get the node with the smallest distance.
19+
- Helps in applying Dijkstra's algorithm.
20+
21+
4. **Arrays `dist` and `ways`:**
22+
- `dist[i]`: Stores the shortest distance from the source node (node `0`) to node `i`.
23+
- `ways[i]`: Stores the number of distinct ways to reach node `i` with the shortest distance.
24+
25+
---
26+
27+
### **Step-by-Step Process**
28+
1. **Input Parsing and Graph Construction:**
29+
- The graph is built using the `roads` array, where each road connects two nodes (`u` and `v`) with a specific weight (`w`).
30+
- Two directed edges are created for each road since the graph is undirected.
31+
32+
2. **Initialization:**
33+
- Initialize the `dist` array with `Long.MAX_VALUE` to signify unreachable nodes.
34+
- Initialize the `ways` array to `0` (initially no paths to any node).
35+
- Set `dist[0] = 0` (distance from node `0` to itself is `0`).
36+
- Set `ways[0] = 1` (only one way to stay at the source).
37+
38+
3. **Dijkstra's Algorithm:**
39+
- Use the priority queue to process the node with the smallest distance.
40+
- For each neighbor of the current node:
41+
- If a shorter path is found, update the distance and reset the number of ways.
42+
- If a path with the same shortest distance is found, add the number of ways to reach the current node to the neighbor's path count.
43+
44+
4. **Return Result:**
45+
- The number of ways to reach the destination node (`n-1`) is returned modulo \( 10^9 + 7 \).
46+
47+
---
48+
49+
### **Code Explanation**
50+
#### 1. **Graph Representation**
51+
```java
52+
ArrayList<ArrayList<Pair>> adj = new ArrayList<>();
53+
for(int i = 0; i < n; i++) {
54+
adj.add(new ArrayList<>());
55+
}
56+
for(int i = 0; i < m; i++) {
57+
adj.get(roads[i][0]).add(new Pair(roads[i][2], roads[i][1]));
58+
adj.get(roads[i][1]).add(new Pair(roads[i][2], roads[i][0]));
59+
}
60+
61+
Time Complexity: O((n+m)log(n))
62+
The program processes all m roads to build the adjacency list.
63+
This operation takes O(m) time.
64+
Dijkstra’s Algorithm:
65+
Each node and its neighbors are processed through the priority queue.
66+
Popping a node from the priority queue takes O(log n) time.
67+
Over all m edges, the operations amount to O((n + m) log n) time.
68+
Overall Time Complexity:
69+
The dominant factor is Dijkstra’s algorithm, so the time complexity is O((n + m) log n).
70+
71+
Space Complexity: O(n)
72+
The adjacency list stores all m edges, requiring O(m) space.
73+
The dist and ways arrays require O(n) space each.
74+
The priority queue stores up to O(n) nodes.
75+
Overall Space Complexity:
76+
The total space complexity is O(n + m)
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
class Pair{
2+
long first;
3+
long second;
4+
public Pair(long first,long second) {
5+
this.first = first;
6+
this.second = second;
7+
}
8+
}
9+
class Solution {
10+
public int countPaths(int n, int[][] roads) {
11+
ArrayList<ArrayList<Pair>> adj = new ArrayList<>();
12+
for(int i = 0;i < n; i++){
13+
adj.add(new ArrayList<>());
14+
}
15+
int m = roads.length;
16+
for(int i = 0; i<m; i++){
17+
adj.get(roads[i][0]).add(new Pair(roads[i][2], roads[i][1]));
18+
adj.get(roads[i][1]).add(new Pair(roads[i][2], roads[i][0]));
19+
}
20+
PriorityQueue<Pair> pq = new PriorityQueue<>((x,y)->Long.compare(x.first, y.first));
21+
long dist[] = new long[n];
22+
long ways[] = new long[n];
23+
24+
25+
for(int i = 0;i < n; i++){
26+
dist[i] = Long.MAX_VALUE;
27+
ways[i] = 0;
28+
}
29+
pq.add(new Pair(0,0));
30+
dist[0] = 0;
31+
ways[0] = 1;
32+
int mod = (int)(1e9 + 7);
33+
while(!pq.isEmpty()){
34+
long dis = pq.peek().first;
35+
int node = (int)(pq.peek().second);
36+
pq.remove();
37+
for(Pair it : adj.get(node)){
38+
long newDis = it.first;
39+
int adjNode = (int)it.second;
40+
if(dis + newDis < dist[adjNode]){
41+
dist[adjNode] = dis + newDis;
42+
pq.add(new Pair(dis + newDis, adjNode));
43+
ways[adjNode] = ways[node];
44+
}
45+
else if(dis + newDis == dist[adjNode]){
46+
ways[adjNode] = (ways[adjNode] + ways[node])%mod;
47+
}
48+
}
49+
}
50+
return (int)(ways[n-1]%mod);
51+
}
52+
}
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# Explanation of the Code
2+
3+
## **Objective**
4+
The program aims to count the minimum number of operations required to transform a binary array `nums` into a specific format where every element equals `1`. Each operation flips the value of three consecutive elements in the array (from `0` to `1` or vice versa).
5+
6+
---
7+
8+
## **Step-by-Step Explanation**
9+
10+
### **1. Initialize Variables**
11+
```java
12+
int n = nums.length;
13+
int count = 0;
14+
15+
for (int i = 0; i <= n - 3; i++) {
16+
if (nums[i] == 0) {
17+
nums[i] = 1 - nums[i];
18+
nums[i + 1] = 1 - nums[i + 1];
19+
nums[i + 2] = 1 - nums[i + 2];
20+
count++;
21+
}
22+
}
23+
This loop checks each element nums[i] in the array until n - 3 (ensuring there are at least three consecutive elements remaining).
24+
25+
Condition (nums[i] == 0):
26+
27+
If the current element is 0, it is flipped, along with the next two consecutive elements.
28+
29+
This transformation ensures the first position of the current window becomes 1.
30+
31+
count is incremented to record the operation.
32+
33+
for (int i = n - 2; i < n; i++) {
34+
if (nums[i] != 1) {
35+
return -1;
36+
}
37+
}
38+
After completing transformations for three-element windows, the final two elements are checked:
39+
40+
If either of them is not 1, it means the target format cannot be achieved, and the function returns -1.
41+
42+
return count;
43+
If all elements are transformed into 1, the function returns the total number of operations required.
44+
45+
Time Complexity
46+
First Loop (for i = 0 to n - 3):
47+
48+
Iterates up to n - 3 elements, performing constant-time operations for each. Time Complexity: O(n)
49+
50+
Second Loop (for i = n - 2 to n):
51+
52+
Iterates over the last two elements of the array. Time Complexity: O(1)
53+
54+
Overall Time Complexity: O(n)
55+
56+
Space Complexity
57+
The program modifies the input array nums in-place and uses only a few integer variables (n, count, i). No additional data structures are required.
58+
59+
Overall Space Complexity: O(1)
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class Solution {
2+
public int minOperations(int[] nums) {
3+
int n = nums.length;
4+
int count = 0;
5+
6+
for (int i = 0; i <= n - 3; i++) {
7+
if (nums[i] == 0) {
8+
9+
nums[i] = 1 - nums[i];
10+
nums[i + 1] = 1 - nums[i + 1];
11+
nums[i + 2] = 1 - nums[i + 2];
12+
count++;
13+
}
14+
}
15+
16+
for (int i = n - 2; i < n; i++) {
17+
if (nums[i] != 1) {
18+
return -1;
19+
}
20+
}
21+
22+
return count;
23+
}
24+
}

0 commit comments

Comments
 (0)