Skip to content

Commit f17c022

Browse files
authored
Merge branch 'master' into feature/div
2 parents 0bfaf14 + df92f81 commit f17c022

File tree

8 files changed

+364
-0
lines changed

8 files changed

+364
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
Shortest Common Supersequence Solution
2+
Overview
3+
The goal of this solution is to find the shortest common supersequence (SCS) of two given strings, str1 and str2. The shortest common supersequence is the shortest string that has both str1 and str2 as subsequences.
4+
5+
Steps
6+
Create DP Table:
7+
8+
We first create a dynamic programming (DP) table dp of size (m + 1) x (n + 1), where m is the length of str1 and n is the length of str2.
9+
10+
Fill the DP Table:
11+
12+
We fill the DP table based on the following conditions:
13+
14+
If characters of str1 and str2 match, we take the diagonal value and add 1: dp[i][j] = dp[i - 1][j - 1] + 1.
15+
16+
If characters do not match, we take the maximum value from the left or the top cell: dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]).
17+
18+
Build the Shortest Common Supersequence:
19+
20+
We use a StringBuilder to construct the SCS.
21+
22+
Starting from the bottom-right corner of the DP table, we move based on the values in the DP table:
23+
24+
If characters match, we add that character to the result and move diagonally up-left.
25+
26+
If characters do not match, we move in the direction of the larger DP value (either up or left).
27+
28+
Finally, we add any remaining characters from str1 or str2.
29+
30+
Reverse the Result:
31+
32+
The result is constructed in reverse order, so we reverse it before returning.
33+
34+
Time Complexity
35+
The time complexity is O(m * n) because we traverse the DP table of size (m + 1) x (n + 1).
36+
37+
Space Complexity
38+
The space complexity is O(m * n) because we use a DP table of size (m + 1) x (n + 1).
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
class Solution {
2+
public String shortestCommonSupersequence(String str1, String str2) {
3+
int m = str1.length();
4+
int n = str2.length();
5+
6+
// Create DP table
7+
int[][] dp = new int[m + 1][n + 1];
8+
9+
// Fill the DP table
10+
for (int i = 1; i <= m; i++) {
11+
for (int j = 1; j <= n; j++) {
12+
if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
13+
dp[i][j] = dp[i - 1][j - 1] + 1; // If characters match
14+
} else {
15+
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); // Take max from either previous row or column
16+
}
17+
}
18+
}
19+
20+
// Build the shortest common supersequence
21+
StringBuilder result = new StringBuilder();
22+
int i = m, j = n;
23+
while (i > 0 && j > 0) {
24+
// If characters are the same, add to the result
25+
if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
26+
result.append(str1.charAt(i - 1));
27+
i--;
28+
j--;
29+
} else if (dp[i - 1][j] > dp[i][j - 1]) { // Move in the direction of the larger dp value
30+
result.append(str1.charAt(i - 1));
31+
i--;
32+
} else {
33+
result.append(str2.charAt(j - 1));
34+
j--;
35+
}
36+
}
37+
38+
// If there are any remaining characters in str1
39+
while (i > 0) {
40+
result.append(str1.charAt(i - 1));
41+
i--;
42+
}
43+
44+
// If there are any remaining characters in str2
45+
while (j > 0) {
46+
result.append(str2.charAt(j - 1));
47+
j--;
48+
}
49+
50+
// Reverse the result before returning
51+
return result.reverse().toString();
52+
}
53+
}
54+
55+
//Time Complexity : O(m*n)
56+
//Space Complexity : O(m*n)
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
## Explanation of the `numberOfAlternatingGroups` Method
2+
3+
The `numberOfAlternatingGroups` method in the `Solution` class takes an array of integers `colors` and an integer `k` as input, and returns the number of alternating groups of size `k` within the array.
4+
5+
### Code Breakdown
6+
7+
1. **Initialization**
8+
```java
9+
int window = 1;
10+
int res = 0;
11+
int n = colors.length;
12+
int i = 0;
13+
int j = 1;
14+
```
15+
- `window`: Keeps track of the current window size.
16+
- `res`: Stores the count of alternating groups of size `k`.
17+
- `n`: Stores the length of the `colors` array.
18+
- `i`, `j`: Pointers to traverse the array.
19+
20+
2. **While Loop to Traverse the Array**
21+
```java
22+
while(i < colors.length) {
23+
if(colors[(j-1) % n] != colors[j%n]) {
24+
window++;
25+
j++;
26+
}else {
27+
i = j;
28+
j = i + 1;
29+
window = 1;
30+
continue;
31+
}
32+
33+
if(window == k) {
34+
res++;
35+
if(colors[(j-1) % n] != colors[j%n]) {
36+
i++;
37+
window -= 1;
38+
}else {
39+
i = j;
40+
j = i + 1;
41+
window = 1;
42+
}
43+
}
44+
}
45+
```
46+
- The loop iterates through the array while `i` is less than the length of `colors`.
47+
- It checks if the current and the next colors are different. If they are different, the window size is incremented, and `j` is incremented.
48+
- If they are the same, it resets the window and continues the iteration.
49+
- When the window size reaches `k`, it increments the `res` count and adjusts the window accordingly.
50+
51+
3. **Return the Result**
52+
```java
53+
return res;
54+
```
55+
- Returns the total count of alternating groups of size `k`.
56+
57+
### Example
58+
59+
Given the `colors` array `[1, 2, 1, 2, 1]` and `k = 3`:
60+
- The method will return `2` since there are two alternating groups of size 3: `[1, 2, 1]` and `[2, 1, 2]`.
61+
62+
### Time Complexity
63+
- The time complexity of this method is O(n), where `n` is the length of the `colors` array, as it traverses the array a constant number of times.
64+
65+
### Space Complexity
66+
- The space complexity is O(n) as only a few variables are used, and no additional data structures are required.
67+
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution {
2+
public int numberOfAlternatingGroups(int[] colors, int k) {
3+
int window = 1;
4+
int res = 0;
5+
int n = colors.length;
6+
int i = 0;
7+
int j = 1;
8+
while(i < colors.length) {
9+
if(colors[(j-1) % n] != colors[j%n]) {
10+
window++;
11+
j++;
12+
}else {
13+
i = j;
14+
j = i + 1;
15+
window = 1;
16+
continue;
17+
}
18+
19+
if(window == k) {
20+
res++;
21+
if(colors[(j-1) % n] != colors[j%n]) {
22+
i++;
23+
window -= 1;
24+
}else {
25+
i = j;
26+
j = i + 1;
27+
window = 1;
28+
}
29+
}
30+
}
31+
32+
return res;
33+
}
34+
}

Explanation-Template.md

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
# Problem Title
2+
3+
**Difficulty:** *(Easy / Medium / Hard)*
4+
**Category:** *(Arrays, Strings, Dynamic Programming, Graphs, etc.)*
5+
**Leetcode Link:** [Problem Link](#)
6+
7+
---
8+
9+
## 📝 Introduction
10+
11+
*A brief introduction to the problem. Mention the key aspects, constraints, and expected output.*
12+
13+
---
14+
15+
## 💡 Approach & Key Insights
16+
17+
*Describe the main idea behind solving the problem. What observations lead to a solution? Mention brute force or naive approaches first, then discuss optimal solutions.*
18+
19+
---
20+
21+
## 🛠️ Breakdown of Approaches
22+
23+
### 1️⃣ Brute Force / Naive Approach
24+
25+
- **Explanation:** *Describe the brute force solution and why it works.*
26+
- **Time Complexity:** *O(?) - Explanation*
27+
- **Space Complexity:** *O(?) - Explanation*
28+
- **Example/Dry Run:**
29+
30+
Example input: [Insert example] Step 1 → Step 2 → Step 3 → Output
31+
32+
33+
### 2️⃣ Optimized Approach
34+
35+
- **Explanation:** *Describe an optimized approach with clear reasoning.*
36+
- **Time Complexity:** *O(?) - Explanation*
37+
- **Space Complexity:** *O(?) - Explanation*
38+
- **Example/Dry Run:**
39+
40+
Example input: [Insert example] Step 1 → Step 2 → Step 3 → Output
41+
42+
43+
### 3️⃣ Best / Final Optimized Approach (if applicable)
44+
45+
- **Explanation:** *Discuss the best possible solution.*
46+
- **Time Complexity:** *O(?) - Explanation*
47+
- **Space Complexity:** *O(?) - Explanation*
48+
- **Example/Dry Run:**
49+
50+
Example input: [Insert example] Step 1 → Step 2 → Step 3 → Output
51+
52+
---
53+
54+
## 📊 Complexity Analysis
55+
56+
| Approach | Time Complexity | Space Complexity |
57+
| ------------- | --------------- | ---------------- |
58+
| Brute Force | O(?) | O(?) |
59+
| Optimized | O(?) | O(?) |
60+
| Best Approach | O(?) | O(?) |
61+
62+
---
63+
64+
## 📉 Optimization Ideas
65+
66+
*Are there any ways to further improve the solution? Can we reduce memory usage or optimize certain operations?*
67+
68+
---
69+
70+
## 📌 Example Walkthroughs & Dry Runs
71+
72+
*Use visuals, ASCII diagrams, or step-by-step breakdowns for clarity.*
73+
74+
```plaintext
75+
Example:
76+
Input: 1 -> 2 -> 3 -> 4
77+
Process:
78+
1 -> Swap 2 & 3
79+
2 -> Reverse half of list
80+
3 -> Merge both halves
81+
Output: 1 -> 3 -> 2 -> 4
82+
```
83+
84+
---
85+
86+
## 🔗 Additional Resources
87+
88+
- [Resource 1]()
89+
- [Resource 2]()
90+
- [Resource 3]()
91+
92+
---
93+
94+
Author: Your Name
95+
Date: DD/MM/YYYY
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# Explanation of the `climbStairs` Code
2+
3+
This Java class provides a solution to the classic "Climbing Stairs" problem using dynamic programming. The goal is to determine the number of distinct ways to climb a staircase with `n` steps, where you can take either 1 step or 2 steps at a time.
4+
5+
---
6+
7+
## Class: `Solution`
8+
9+
### Method: `climbStairs(int n)`
10+
11+
#### **Purpose**
12+
This method calculates the number of ways to climb a staircase with `n` steps.
13+
14+
#### **Parameters**
15+
- `n`: An integer representing the total number of steps in the staircase.
16+
17+
#### **Logic**
18+
1. **Base Cases**:
19+
- If `n == 1`, return `1` since there is only one way to climb a single step.
20+
- If `n == 2`, return `2` since there are two ways to climb two steps: either `1+1` or `2`.
21+
22+
2. **Dynamic Programming Array**:
23+
- Create an integer array `a` of size `n`.
24+
- Initialize the first two elements:
25+
- `a[0] = 1` (1 way to climb 1 step).
26+
- `a[1] = 2` (2 ways to climb 2 steps).
27+
28+
3. **Iterative Calculation**:
29+
- Use a loop from `i = 2` to `n - 1`:
30+
- For each step `i`, calculate the number of ways to reach it as the sum of the ways to reach the previous two steps:
31+
32+
33+
\[
34+
a[i] = a[i - 1] + a[i - 2]
35+
\]
36+
37+
38+
- This is based on the observation that to reach step `i`, you can either:
39+
- Take one step from `i - 1` (contributing `a[i - 1]` ways).
40+
- Take two steps from `i - 2` (contributing `a[i - 2]` ways).
41+
42+
4. **Return Result**:
43+
- Return `a[n - 1]`, which contains the total number of ways to climb `n` steps.
44+
45+
---
46+
47+
### Example Execution
48+
#### Input:
49+
```java
50+
int n = 5;
51+
52+
Time Complexity: O(n)
53+
Space Complexity: O(n)
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class Solution {
2+
public int climbStairs(int n) {
3+
if(n==1) return 1;
4+
5+
if(n==2) return 2;
6+
7+
int[] a = new int[n];
8+
a[0]=1;
9+
a[1]=2;
10+
11+
for(int i=2;i<n;i++){
12+
a[i]=a[i-1]+a[i-2];
13+
}
14+
return a[n-1];
15+
}
16+
}

README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,9 @@ Thank you for considering contributing to **LeetCode-Solutions**! This repositor
3030
├── 2 Sum - Solution.py
3131
├── 2 Sum - Explanation.md
3232
```
33+
34+
> Note: Make sure to use this [Explanation Template](https://github.com/Dijkstra-Edu/LeetCode-Solutions/blob/master/Explanation-Template.md) as reference while writing down your explanations!
35+
3336
5. **Commit your changes**: Use the following format for commit messages:
3437
```sh
3538
git commit -m "Solution #num - Creator/Edited - Date - commit #num"
@@ -52,6 +55,8 @@ Thank you for considering contributing to **LeetCode-Solutions**! This repositor
5255
- **Discussions**: Use GitHub Issues for bug reports, feature requests, or discussions before implementing major changes.
5356
- **Documentation**: Ensure that the `Explanation.md` file is well-written and clearly explains the approach used in the solutions.
5457

58+
> Note: Make sure to use this [Explanation Template](https://github.com/Dijkstra-Edu/LeetCode-Solutions/blob/master/Explanation-Template.md) as reference while writing down your explanations!
59+
5560
## 🚀 Issue Tracking
5661

5762
- If you find an issue with an existing solution or have a suggestion, please [open an issue](https://github.com/Dijkstra-Edu/LeetCode-Solutions/issues).

0 commit comments

Comments
 (0)