Skip to content

Commit f8ee4f1

Browse files
Merge branch 'CodeHarborHub:main' into main
2 parents 24aad4e + 2353481 commit f8ee4f1

File tree

3 files changed

+379
-2
lines changed

3 files changed

+379
-2
lines changed

dsa-problems/leetcode-problems/0000-0099.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -109,13 +109,13 @@ export const problems = [
109109
"problemName": "17. Letter Combinations of a Phone Number",
110110
"difficulty": "Medium",
111111
"leetCodeLink": "https://leetcode.com/problems/letter-combinations-of-a-phone-number/",
112-
"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/four-sum"
112+
"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/letter-combination"
113113
},
114114
{
115115
"problemName": "18. 4Sum",
116116
"difficulty": "Medium",
117117
"leetCodeLink": "https://leetcode.com/problems/4sum/",
118-
"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/"
118+
"solutionLink": "/dsa-solutions/lc-solutions/0000-0099/four-sum"
119119
},
120120
{
121121
"problemName": "19. Remove Nth Node From End of List",
Lines changed: 217 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,217 @@
1+
---
2+
id: letter-combination
3+
title: Letter Combinations of a Phone Number (LeetCode)
4+
sidebar_label: 0017 - letter-combination
5+
tags:
6+
- Array
7+
- Backtracking
8+
- String
9+
description: "Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent."
10+
---
11+
12+
## Problem Description
13+
14+
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.
15+
16+
A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
17+
18+
19+
### Examples
20+
21+
**Example 1:**
22+
23+
```
24+
Input
25+
digits = "
26+
Output
27+
["ad","ae","af","bd","be","bf","cd","ce","cf"]
28+
29+
```
30+
**Example 2:**
31+
32+
```
33+
Input: digits = ""
34+
Output: []
35+
```
36+
**Example 3:**
37+
38+
```
39+
Input: digits = "2"
40+
Output: ["a","b","c"]
41+
```
42+
### Constraints
43+
44+
- `0 <= digits.length <= 4`
45+
- `digits[i] is a digit in the range ['2', '9']`
46+
47+
48+
## Solution for Letter combination of phone number
49+
50+
### Intuition
51+
Using backtracking to create all possible combinations
52+
53+
54+
55+
56+
### Complexity Analysis
57+
58+
#### Time Complexity: $O(3^n)$
59+
60+
#### Space Complexity: $O(N)$
61+
62+
63+
## Approach
64+
65+
- This is based on a Python solution. Other implementations might differ a bit.
66+
67+
- Initialize an empty list `res` to store the generated combinations.
68+
69+
- Check if the `digits` string is empty. If it is, return an empty list since there are no digits to process.
70+
71+
- Create a dictionary `digit_to_letters` that maps each digit from '2' to '9' to the corresponding letters on a phone keypad.
72+
73+
- Define a recursive function `backtrack(idx, comb)` that takes two parameters:
74+
- `idx`: The current index of the digit being processed in the `digits` string.
75+
- `comb`: The current combination being formed by appending letters.
76+
77+
- Inside the `backtrack` function:
78+
- Check if `idx` is equal to the length of the `digits` string. If it is, it means a valid combination has been formed, so append the current `comb` to the `res` list.
79+
- If not, iterate through each letter corresponding to the digit at `digits[idx]` using the `digit_to_letters` dictionary.
80+
- For each letter, recursively call `backtrack` with `idx + 1` to process the next digit and `comb + letter` to add the current letter to the combination.
81+
82+
- Initialize the `res` list.
83+
84+
- Start the initial call to `backtrack` with `idx` set to 0 and an empty string as `comb`. This will start the process of generating combinations.
85+
86+
- After the recursive calls have been made, return the `res` list containing all the generated combinations.
87+
88+
- The algorithm works by iteratively exploring all possible combinations of letters that can be formed from the given input digits. It uses a recursive approach to generate combinations, building them one letter at a time. The base case for the recursion is when all digits have been processed, at which point a combination is complete and added to the `res` list. The backtracking nature of the algorithm ensures that all possible combinations are explored.
89+
90+
91+
### Code in Different Languages
92+
93+
<Tabs>
94+
<TabItem value="cpp" label="C++">
95+
<SolutionAuthor name="@Shreyash3087"/>
96+
97+
```cpp
98+
#include <vector>
99+
#include <algorithm>
100+
#include <climits>
101+
102+
class Solution {
103+
public:
104+
int cherryPickup(std::vector<std::vector<int>>& grid) {
105+
int N = grid.size();
106+
std::vector<std::vector<int>> dp(N, std::vector<int>(N, INT_MIN));
107+
dp[0][0] = grid[0][0];
108+
109+
for (int t = 1; t <= 2 * N - 2; ++t) {
110+
std::vector<std::vector<int>> dp2(N, std::vector<int>(N, INT_MIN));
111+
112+
for (int i = std::max(0, t - (N - 1)); i <= std::min(N - 1, t); ++i) {
113+
for (int j = std::max(0, t - (N - 1)); j <= std::min(N - 1, t); ++j) {
114+
if (grid[i][t - i] == -1 || grid[j][t - j] == -1) {
115+
continue;
116+
}
117+
int val = grid[i][t - i];
118+
if (i != j) {
119+
val += grid[j][t - j];
120+
}
121+
for (int pi = i - 1; pi <= i; ++pi) {
122+
for (int pj = j - 1; pj <= j; ++pj) {
123+
if (pi >= 0 && pj >= 0) {
124+
dp2[i][j] = std::max(dp2[i][j], dp[pi][pj] + val);
125+
}
126+
}
127+
}
128+
}
129+
}
130+
dp = std::move(dp2);
131+
}
132+
return std::max(0, dp[N - 1][N - 1]);
133+
}
134+
};
135+
136+
137+
```
138+
</TabItem>
139+
<TabItem value="java" label="Java">
140+
<SolutionAuthor name="@Shreyash3087"/>
141+
142+
```java
143+
class Solution {
144+
public int cherryPickup(int[][] grid) {
145+
int N = grid.length;
146+
int[][] dp = new int[N][N];
147+
for (int[] row: dp) {
148+
Arrays.fill(row, Integer.MIN_VALUE);
149+
}
150+
dp[0][0] = grid[0][0];
151+
152+
for (int t = 1; t <= 2*N - 2; ++t) {
153+
int[][] dp2 = new int[N][N];
154+
for (int[] row: dp2) {
155+
Arrays.fill(row, Integer.MIN_VALUE);
156+
}
157+
158+
for (int i = Math.max(0, t - (N - 1)); i <= Math.min(N - 1, t); ++i) {
159+
for (int j = Math.max(0, t - (N - 1)); j <= Math.min(N - 1, t); ++j) {
160+
if (grid[i][t - i] == -1 || grid[j][t - j] == -1) {
161+
continue;
162+
}
163+
int val = grid[i][t-i];
164+
if (i != j) {
165+
val += grid[j][t - j];
166+
}
167+
for (int pi = i - 1; pi <= i; ++pi) {
168+
for (int pj = j - 1; pj <= j; ++pj) {
169+
if (pi >= 0 && pj >= 0) {
170+
dp2[i][j] = Math.max(dp2[i][j], dp[pi][pj] + val);
171+
}
172+
}
173+
}
174+
}
175+
}
176+
dp = dp2;
177+
}
178+
return Math.max(0, dp[N - 1][N - 1]);
179+
}
180+
}
181+
```
182+
183+
</TabItem>
184+
<TabItem value="python" label="Python">
185+
<SolutionAuthor name="@Shreyash3087"/>
186+
187+
```python
188+
class Solution(object):
189+
def cherryPickup(self, grid):
190+
N = len(grid)
191+
dp = [[float('-inf')] * N for _ in xrange(N)]
192+
dp[0][0] = grid[0][0]
193+
for t in xrange(1, 2 * N - 1):
194+
dp2 = [[float('-inf')] * N for _ in xrange(N)]
195+
for i in xrange(max(0, t - (N - 1)), min(N - 1, t) + 1):
196+
for j in xrange(max(0, t - (N - 1)), min(N - 1, t) + 1):
197+
if grid[i][t - i] == -1 or grid[j][t - j] == -1:
198+
continue
199+
val = grid[i][t - i]
200+
if i != j:
201+
val += grid[j][t - j]
202+
dp2[i][j] = max(dp[pi][pj] + val
203+
for pi in (i - 1, i) for pj in (j - 1, j)
204+
if pi >= 0 and pj >= 0)
205+
dp = dp2
206+
return max(0, dp[N - 1][N - 1])
207+
```
208+
</TabItem>
209+
</Tabs>
210+
211+
212+
213+
## References
214+
215+
- **LeetCode Problem**: [Letter combinatino of Phone number](https://leetcode.com/problems/cherry-pickup/description/)
216+
217+
- **Solution Link**: [letter combination of phone number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/solutions/5125020/video-simple-solution/)
Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
1+
---
2+
id: Happy-Number
3+
title: Happy Number
4+
sidebar_label: Happy Number
5+
tags:
6+
- Math
7+
- Hash Table
8+
- Two Pointers
9+
---
10+
11+
## Problem Description
12+
13+
| Problem Statement | Solution Link | LeetCode Profile |
14+
| :------------------------------------------------------ | :------------------------------------------------------------------------- | :------------------------------------------------------ |
15+
| [Happy-Number](https://leetcode.com/problems/Happy-Number/description/) | [Happy-Number Solution on LeetCode](https://leetcode.com/problems/Happy-Number/solutions/) | [Nikita Saini](https://leetcode.com/u/Saini_Nikita/) |
16+
17+
## Problem Description
18+
19+
A happy number is a number defined by the following process:
20+
Starting with any positive integer, replace the number by the sum of the squares of its digits.
21+
Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
22+
Those numbers for which this process ends in 1 are happy.
23+
24+
Given a positive integer `n`, determine if it is a happy number.
25+
26+
### Example 1:
27+
28+
Input: `n = 19`
29+
Output: `true`
30+
Explanation:
31+
1^2 + 9^2 = 82
32+
8^2 + 2^2 = 68
33+
6^2 + 8^2 = 100
34+
1^2 + 0^2 + 0^2 = 1
35+
36+
### Example 2:
37+
38+
Input: `n = 2`
39+
Output: `false`
40+
Explanation:
41+
$2^2 = 4$
42+
$4^2 = 16$
43+
$1^2 + 6^2 = 37$
44+
$3^2 + 7^2 = 58$
45+
$5^2 + 8^2 = 89$
46+
$8^2 + 9^2 = 145$
47+
$1^2 + 4^2 + 5^2 = 42$
48+
$4^2 + 2^2 = 20$
49+
$2^2 + 0^2 = 4$ (cycle repeats endlessly)
50+
51+
## Constraints
52+
53+
- `1 <= n <= 2^31 - 1`
54+
55+
## Approach
56+
57+
To determine if a number `n` is a happy number:
58+
1. Use a set to keep track of numbers seen during the process to detect cycles.
59+
2. Repeat the process of replacing `n` by the sum of the squares of its digits until `n` becomes 1 or a cycle is detected (a number repeats).
60+
3. If `n` becomes 1, return true; otherwise, return false.
61+
62+
## Solution in Python
63+
64+
```python
65+
def isHappy(n: int) -> bool:
66+
seen = set()
67+
while n != 1 and n not in seen:
68+
seen.add(n)
69+
n = sum(int(digit)**2 for digit in str(n))
70+
return n == 1
71+
```
72+
73+
## Solution in Java
74+
```java
75+
import java.util.HashSet;
76+
import java.util.Set;
77+
78+
class Solution {
79+
public boolean isHappy(int n) {
80+
Set<Integer> seen = new HashSet<>();
81+
while (n != 1 && !seen.contains(n)) {
82+
seen.add(n);
83+
int sum = 0;
84+
while (n > 0) {
85+
int digit = n % 10;
86+
sum += digit * digit;
87+
n /= 10;
88+
}
89+
n = sum;
90+
}
91+
return n == 1;
92+
}
93+
}
94+
```
95+
96+
## Solution in C++
97+
```cpp
98+
class Solution {
99+
public:
100+
bool isHappy(int n) {
101+
unordered_set<int> seen;
102+
while (n != 1 && seen.find(n) == seen.end()) {
103+
seen.insert(n);
104+
int sum = 0;
105+
while (n > 0) {
106+
int digit = n % 10;
107+
sum += digit * digit;
108+
n /= 10;
109+
}
110+
n = sum;
111+
}
112+
return n == 1;
113+
}
114+
};
115+
```
116+
117+
## Solution in C
118+
```c
119+
#include <stdbool.h>
120+
#include <stdio.h>
121+
#include <stdlib.h>
122+
123+
bool isHappy(int n) {
124+
int seen[1000] = {0};
125+
while (n != 1 && !seen[n]) {
126+
seen[n] = 1;
127+
int sum = 0;
128+
while (n > 0) {
129+
int digit = n % 10;
130+
sum += digit * digit;
131+
n /= 10;
132+
}
133+
n = sum;
134+
}
135+
return n == 1;
136+
}
137+
```
138+
139+
## Solution in JavaScript
140+
```js
141+
var isHappy = function(n) {
142+
let seen = new Set();
143+
while (n !== 1 && !seen.has(n)) {
144+
seen.add(n);
145+
n = String(n).split('').reduce((sum, digit) => sum + digit * digit, 0);
146+
}
147+
return n === 1;
148+
};
149+
```
150+
151+
## Step-By_Step Algorithm
152+
1. Initialize an empty set `seen` to keep track of numbers encountered.
153+
2. While `n` is not 1 and `n` is not in `seen`:
154+
- Add `n` to `seen`.
155+
- Compute the sum of the squares of its digits for `n`.
156+
- Update `n` to this computed sum.
157+
3. Check if `n` equals 1. If yes, return true (it is a happy number). If no, return false (it is not a happy number).
158+
159+
## Conclusion
160+
The provided solutions use a similar approach to solve the happy number problem across different programming languages. They efficiently detect cycles and determine if a number eventually leads to 1 or loops endlessly. The use of a set ensures that the algorithm runs in linear time relative to the number of digits in `n`, making it suitable for the given constraints.

0 commit comments

Comments
 (0)