Skip to content

Commit 35d5f64

Browse files
committedDec 24, 2024·
Added js tasks
1 parent 9d4c488 commit 35d5f64

File tree

14 files changed

+1016
-0
lines changed

14 files changed

+1016
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 322\. Coin Change
5+
6+
Medium
7+
8+
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money.
9+
10+
Return _the fewest number of coins that you need to make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `-1`.
11+
12+
You may assume that you have an infinite number of each kind of coin.
13+
14+
**Example 1:**
15+
16+
**Input:** coins = [1,2,5], amount = 11
17+
18+
**Output:** 3
19+
20+
**Explanation:** 11 = 5 + 5 + 1
21+
22+
**Example 2:**
23+
24+
**Input:** coins = [2], amount = 3
25+
26+
**Output:** -1
27+
28+
**Example 3:**
29+
30+
**Input:** coins = [1], amount = 0
31+
32+
**Output:** 0
33+
34+
**Constraints:**
35+
36+
* `1 <= coins.length <= 12`
37+
* <code>1 <= coins[i] <= 2<sup>31</sup> - 1</code>
38+
* <code>0 <= amount <= 10<sup>4</sup></code>
39+
40+
## Solution
41+
42+
```javascript
43+
/**
44+
* @param {number[]} coins
45+
* @param {number} amount
46+
* @return {number}
47+
*/
48+
var coinChange = function(coins, amount) {
49+
const dp = new Array(amount + 1).fill(0)
50+
dp[0] = 1
51+
52+
for (const coin of coins) {
53+
for (let i = coin; i <= amount; i++) {
54+
const prev = dp[i - coin]
55+
if (prev > 0) {
56+
if (dp[i] === 0) {
57+
dp[i] = prev + 1
58+
} else {
59+
dp[i] = Math.min(dp[i], prev + 1)
60+
}
61+
}
62+
}
63+
}
64+
65+
return dp[amount] - 1
66+
};
67+
68+
export { coinChange }
69+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 338\. Counting Bits
5+
6+
Easy
7+
8+
Given an integer `n`, return _an array_ `ans` _of length_ `n + 1` _such that for each_ `i` (`0 <= i <= n`)_,_ `ans[i]` _is the **number of**_ `1`_**'s** in the binary representation of_ `i`.
9+
10+
**Example 1:**
11+
12+
**Input:** n = 2
13+
14+
**Output:** [0,1,1]
15+
16+
**Explanation:**
17+
18+
0 --> 0
19+
1 --> 1
20+
2 --> 10
21+
22+
**Example 2:**
23+
24+
**Input:** n = 5
25+
26+
**Output:** [0,1,1,2,1,2]
27+
28+
**Explanation:**
29+
30+
0 --> 0
31+
1 --> 1
32+
2 --> 10
33+
3 --> 11
34+
4 --> 100
35+
5 --> 101
36+
37+
**Constraints:**
38+
39+
* <code>0 <= n <= 10<sup>5</sup></code>
40+
41+
**Follow up:**
42+
43+
* It is very easy to come up with a solution with a runtime of `O(n log n)`. Can you do it in linear time `O(n)` and possibly in a single pass?
44+
* Can you do it without using any built-in function (i.e., like `__builtin_popcount` in C++)?
45+
46+
## Solution
47+
48+
```javascript
49+
/**
50+
* @param {number} n
51+
* @return {number[]}
52+
*/
53+
var countBits = function(num) {
54+
const result = new Array(num + 1).fill(0)
55+
let borderPos = 1
56+
let incrPos = 1
57+
58+
for (let i = 1; i <= num; i++) {
59+
// When we reach a power of 2, reset `borderPos` and `incrPos`
60+
if (incrPos === borderPos) {
61+
result[i] = 1
62+
incrPos = 1
63+
borderPos = i
64+
} else {
65+
result[i] = 1 + result[incrPos++]
66+
}
67+
}
68+
69+
return result
70+
}
71+
72+
export { countBits }
73+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 347\. Top K Frequent Elements
5+
6+
Medium
7+
8+
Given an integer array `nums` and an integer `k`, return _the_ `k` _most frequent elements_. You may return the answer in **any order**.
9+
10+
**Example 1:**
11+
12+
**Input:** nums = [1,1,1,2,2,3], k = 2
13+
14+
**Output:** [1,2]
15+
16+
**Example 2:**
17+
18+
**Input:** nums = [1], k = 1
19+
20+
**Output:** [1]
21+
22+
**Constraints:**
23+
24+
* <code>1 <= nums.length <= 10<sup>5</sup></code>
25+
* <code>-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup></code>
26+
* `k` is in the range `[1, the number of unique elements in the array]`.
27+
* It is **guaranteed** that the answer is **unique**.
28+
29+
**Follow up:** Your algorithm's time complexity must be better than `O(n log n)`, where n is the array's size.
30+
31+
## Solution
32+
33+
```javascript
34+
/**
35+
* @param {number[]} nums
36+
* @param {number} k
37+
* @return {number[]}
38+
*/
39+
var topKFrequent = function (nums, k) {
40+
let obj = {}, result = []
41+
for (let item of nums) {
42+
obj[item] = (obj[item] ? obj[item] : 0) + 1
43+
}
44+
let temp = Object.entries(obj).sort((a, b) => b[1] - a[1])
45+
for (let i = 0; i < k; i++) {
46+
result.push(Number(temp[i][0]))
47+
}
48+
return result
49+
};
50+
51+
export { topKFrequent }
52+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 394\. Decode String
5+
6+
Medium
7+
8+
Given an encoded string, return its decoded string.
9+
10+
The encoding rule is: `k[encoded_string]`, where the `encoded_string` inside the square brackets is being repeated exactly `k` times. Note that `k` is guaranteed to be a positive integer.
11+
12+
You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, `k`. For example, there will not be input like `3a` or `2[4]`.
13+
14+
The test cases are generated so that the length of the output will never exceed <code>10<sup>5</sup></code>.
15+
16+
**Example 1:**
17+
18+
**Input:** s = "3[a]2[bc]"
19+
20+
**Output:** "aaabcbc"
21+
22+
**Example 2:**
23+
24+
**Input:** s = "3[a2[c]]"
25+
26+
**Output:** "accaccacc"
27+
28+
**Example 3:**
29+
30+
**Input:** s = "2[abc]3[cd]ef"
31+
32+
**Output:** "abcabccdcdcdef"
33+
34+
**Constraints:**
35+
36+
* `1 <= s.length <= 30`
37+
* `s` consists of lowercase English letters, digits, and square brackets `'[]'`.
38+
* `s` is guaranteed to be **a valid** input.
39+
* All the integers in `s` are in the range `[1, 300]`.
40+
41+
## Solution
42+
43+
```javascript
44+
/**
45+
* @param {string} s
46+
* @return {string}
47+
*/
48+
var decodeString = function(s) {
49+
let i = 0
50+
51+
const helper = () => {
52+
let count = 0
53+
let sb = ''
54+
55+
while (i < s.length) {
56+
const c = s[i]
57+
i++
58+
59+
if (/[a-zA-Z]/.test(c)) {
60+
sb += c
61+
} else if (/\d/.test(c)) {
62+
count = count * 10 + Number(c)
63+
} else if (c === ']') {
64+
break
65+
} else if (c === '[') {
66+
// Recursive call for the substring
67+
const repeat = helper()
68+
while (count > 0) {
69+
sb += repeat
70+
count--
71+
}
72+
}
73+
}
74+
75+
return sb
76+
}
77+
78+
return helper()
79+
};
80+
81+
export { decodeString }
82+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 416\. Partition Equal Subset Sum
5+
6+
Medium
7+
8+
Given a **non-empty** array `nums` containing **only positive integers**, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
9+
10+
**Example 1:**
11+
12+
**Input:** nums = [1,5,11,5]
13+
14+
**Output:** true
15+
16+
**Explanation:** The array can be partitioned as [1, 5, 5] and [11].
17+
18+
**Example 2:**
19+
20+
**Input:** nums = [1,2,3,5]
21+
22+
**Output:** false
23+
24+
**Explanation:** The array cannot be partitioned into equal sum subsets.
25+
26+
**Constraints:**
27+
28+
* `1 <= nums.length <= 200`
29+
* `1 <= nums[i] <= 100`
30+
31+
## Solution
32+
33+
```javascript
34+
/**
35+
* @param {number[]} nums
36+
* @return {boolean}
37+
*/
38+
var canPartition = function(nums) {
39+
let sum = nums.reduce((acc, val) => acc + val, 0)
40+
if (sum % 2 !== 0) {
41+
return false
42+
}
43+
sum /= 2
44+
45+
const set = new Array(sum + 1).fill(false)
46+
const arr = new Array(sum + 2).fill(0)
47+
let top = 0
48+
49+
for (let val of nums) {
50+
for (let i = top; i >= 0; i--) {
51+
const tempSum = val + arr[i]
52+
if (tempSum <= sum && !set[tempSum]) {
53+
if (tempSum === sum) {
54+
return true
55+
}
56+
set[tempSum] = true
57+
arr[++top] = tempSum
58+
}
59+
}
60+
}
61+
62+
return false
63+
};
64+
65+
export { canPartition }
66+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 437\. Path Sum III
5+
6+
Medium
7+
8+
Given the `root` of a binary tree and an integer `targetSum`, return _the number of paths where the sum of the values along the path equals_ `targetSum`.
9+
10+
The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).
11+
12+
**Example 1:**
13+
14+
![](https://assets.leetcode.com/uploads/2021/04/09/pathsum3-1-tree.jpg)
15+
16+
**Input:** root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8
17+
18+
**Output:** 3
19+
20+
**Explanation:** The paths that sum to 8 are shown.
21+
22+
**Example 2:**
23+
24+
**Input:** root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
25+
26+
**Output:** 3
27+
28+
**Constraints:**
29+
30+
* The number of nodes in the tree is in the range `[0, 1000]`.
31+
* <code>-10<sup>9</sup> <= Node.val <= 10<sup>9</sup></code>
32+
* `-1000 <= targetSum <= 1000`
33+
34+
## Solution
35+
36+
```javascript
37+
/**
38+
* Definition for a binary tree node.
39+
* function TreeNode(val, left, right) {
40+
* this.val = (val===undefined ? 0 : val)
41+
* this.left = (left===undefined ? null : left)
42+
* this.right = (right===undefined ? null : right)
43+
* }
44+
*/
45+
/**
46+
* @param {TreeNode} root
47+
* @param {number} targetSum
48+
* @return {number}
49+
*/
50+
var pathSum = function(root, targetSum) {
51+
const h = new Map()
52+
return dfs(root, targetSum, h, 0)
53+
};
54+
55+
function dfs(root, targetSum, h, currentSum) {
56+
let count = 0
57+
if (root === null) {
58+
return 0
59+
}
60+
61+
const sumKey = currentSum + root.val
62+
63+
if (sumKey === targetSum) {
64+
count += 1
65+
}
66+
67+
if (h.has(sumKey - targetSum)) {
68+
count += h.get(sumKey - targetSum)
69+
}
70+
71+
h.set(sumKey, (h.get(sumKey) || 0) + 1)
72+
73+
count += dfs(root.left, targetSum, h, sumKey)
74+
count += dfs(root.right, targetSum, h, sumKey)
75+
76+
h.set(sumKey, h.get(sumKey) - 1)
77+
78+
return count
79+
};
80+
81+
export { pathSum }
82+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 438\. Find All Anagrams in a String
5+
6+
Medium
7+
8+
Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**.
9+
10+
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
11+
12+
**Example 1:**
13+
14+
**Input:** s = "cbaebabacd", p = "abc"
15+
16+
**Output:** [0,6]
17+
18+
**Explanation:**
19+
20+
The substring with start index = 0 is "cba", which is an anagram of "abc".
21+
22+
The substring with start index = 6 is "bac", which is an anagram of "abc".
23+
24+
**Example 2:**
25+
26+
**Input:** s = "abab", p = "ab"
27+
28+
**Output:** [0,1,2]
29+
30+
**Explanation:**
31+
32+
The substring with start index = 0 is "ab", which is an anagram of "ab".
33+
34+
The substring with start index = 1 is "ba", which is an anagram of "ab".
35+
36+
The substring with start index = 2 is "ab", which is an anagram of "ab".
37+
38+
**Constraints:**
39+
40+
* <code>1 <= s.length, p.length <= 3 * 10<sup>4</sup></code>
41+
* `s` and `p` consist of lowercase English letters.
42+
43+
## Solution
44+
45+
```javascript
46+
/**
47+
* @param {string} s
48+
* @param {string} p
49+
* @return {number[]}
50+
*/
51+
var findAnagrams = function(s, p) {
52+
const map = new Array(26).fill(0)
53+
for (let i = 0; i < p.length; i++) {
54+
map[p.charCodeAt(i) - 'a'.charCodeAt(0)]++
55+
}
56+
57+
const res = []
58+
let i = 0
59+
let j = 0
60+
61+
while (i < s.length) {
62+
const idx = s.charCodeAt(i) - 'a'.charCodeAt(0)
63+
// Add the new character
64+
map[idx]--
65+
66+
// If the length is greater than the window's length, pop the left character
67+
if (i >= p.length) {
68+
map[s.charCodeAt(j++) - 'a'.charCodeAt(0)]++
69+
}
70+
71+
let finish = true
72+
for (let k = 0; k < 26; k++) {
73+
// If it's not an anagram of string p
74+
if (map[k] !== 0) {
75+
finish = false
76+
break
77+
}
78+
}
79+
80+
if (i >= p.length - 1 && finish) {
81+
res.push(j)
82+
}
83+
i++
84+
}
85+
86+
return res
87+
};
88+
89+
export { findAnagrams }
90+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 494\. Target Sum
5+
6+
Medium
7+
8+
You are given an integer array `nums` and an integer `target`.
9+
10+
You want to build an **expression** out of nums by adding one of the symbols `'+'` and `'-'` before each integer in nums and then concatenate all the integers.
11+
12+
* For example, if `nums = [2, 1]`, you can add a `'+'` before `2` and a `'-'` before `1` and concatenate them to build the expression `"+2-1"`.
13+
14+
Return the number of different **expressions** that you can build, which evaluates to `target`.
15+
16+
**Example 1:**
17+
18+
**Input:** nums = [1,1,1,1,1], target = 3
19+
20+
**Output:** 5
21+
22+
**Explanation:** There are 5 ways to assign symbols to make the sum of nums be target 3.
23+
24+
-1 + 1 + 1 + 1 + 1 = 3
25+
26+
+1 - 1 + 1 + 1 + 1 = 3
27+
28+
+1 + 1 - 1 + 1 + 1 = 3
29+
30+
+1 + 1 + 1 - 1 + 1 = 3
31+
32+
+1 + 1 + 1 + 1 - 1 = 3
33+
34+
**Example 2:**
35+
36+
**Input:** nums = [1], target = 1
37+
38+
**Output:** 1
39+
40+
**Constraints:**
41+
42+
* `1 <= nums.length <= 20`
43+
* `0 <= nums[i] <= 1000`
44+
* `0 <= sum(nums[i]) <= 1000`
45+
* `-1000 <= target <= 1000`
46+
47+
## Solution
48+
49+
```javascript
50+
/**
51+
* @param {number[]} nums
52+
* @param {number} target
53+
* @return {number}
54+
*/
55+
var findTargetSumWays = function(nums, target) {
56+
const n = nums.length
57+
let totalSum = 0
58+
for (let i = 0; i < n; i++) {
59+
totalSum += nums[i]
60+
}
61+
62+
const sum = totalSum - target
63+
if (sum < 0 || sum % 2 === 1) {
64+
return 0
65+
}
66+
67+
const targetSum = Math.floor(sum / 2)
68+
69+
// Helper function to solve the problem
70+
const solve = (nums, target) => {
71+
let prev = new Array(target + 1).fill(0)
72+
73+
if (nums[0] === 0) {
74+
prev[0] = 2 // Two ways to form sum 0: +0 and -0
75+
} else {
76+
prev[0] = 1
77+
}
78+
79+
if (nums[0] !== 0 && nums[0] <= target) {
80+
prev[nums[0]] = 1
81+
}
82+
83+
for (let i = 1; i < nums.length; i++) {
84+
const curr = new Array(target + 1).fill(0)
85+
for (let j = 0; j <= target; j++) {
86+
const taken = j >= nums[i] ? prev[j - nums[i]] : 0
87+
const nonTaken = prev[j]
88+
curr[j] = taken + nonTaken
89+
}
90+
prev = curr
91+
}
92+
93+
return prev[target]
94+
}
95+
96+
return solve(nums, targetSum)
97+
};
98+
99+
export { findTargetSumWays }
100+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 543\. Diameter of Binary Tree
5+
6+
Easy
7+
8+
Given the `root` of a binary tree, return _the length of the **diameter** of the tree_.
9+
10+
The **diameter** of a binary tree is the **length** of the longest path between any two nodes in a tree. This path may or may not pass through the `root`.
11+
12+
The **length** of a path between two nodes is represented by the number of edges between them.
13+
14+
**Example 1:**
15+
16+
![](https://assets.leetcode.com/uploads/2021/03/06/diamtree.jpg)
17+
18+
**Input:** root = [1,2,3,4,5]
19+
20+
**Output:** 3
21+
22+
**Explanation:** 3 is the length of the path [4,2,1,3] or [5,2,1,3].
23+
24+
**Example 2:**
25+
26+
**Input:** root = [1,2]
27+
28+
**Output:** 1
29+
30+
**Constraints:**
31+
32+
* The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.
33+
* `-100 <= Node.val <= 100`
34+
35+
## Solution
36+
37+
```javascript
38+
/**
39+
* Definition for a binary tree node.
40+
* function TreeNode(val, left, right) {
41+
* this.val = (val===undefined ? 0 : val)
42+
* this.left = (left===undefined ? null : left)
43+
* this.right = (right===undefined ? null : right)
44+
* }
45+
*/
46+
/**
47+
* @param {TreeNode} root
48+
* @return {number}
49+
*/
50+
var diameterOfBinaryTree = function(root) {
51+
let diameter = 0
52+
53+
const diameterOfBinaryTreeUtil = (node) => {
54+
if (node === null) {
55+
return 0
56+
}
57+
58+
const leftLength = node.left ? 1 + diameterOfBinaryTreeUtil(node.left) : 0
59+
const rightLength = node.right ? 1 + diameterOfBinaryTreeUtil(node.right) : 0
60+
61+
// Update the diameter
62+
diameter = Math.max(diameter, leftLength + rightLength)
63+
64+
// Return the longest path from this node
65+
return Math.max(leftLength, rightLength)
66+
}
67+
68+
diameterOfBinaryTreeUtil(root)
69+
return diameter
70+
};
71+
72+
export { diameterOfBinaryTree }
73+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 560\. Subarray Sum Equals K
5+
6+
Medium
7+
8+
Given an array of integers `nums` and an integer `k`, return _the total number of subarrays whose sum equals to_ `k`.
9+
10+
A subarray is a contiguous **non-empty** sequence of elements within an array.
11+
12+
**Example 1:**
13+
14+
**Input:** nums = [1,1,1], k = 2
15+
16+
**Output:** 2
17+
18+
**Example 2:**
19+
20+
**Input:** nums = [1,2,3], k = 3
21+
22+
**Output:** 2
23+
24+
**Constraints:**
25+
26+
* <code>1 <= nums.length <= 2 * 10<sup>4</sup></code>
27+
* `-1000 <= nums[i] <= 1000`
28+
* <code>-10<sup>7</sup> <= k <= 10<sup>7</sup></code>
29+
30+
## Solution
31+
32+
```javascript
33+
/**
34+
* @param {number[]} nums
35+
* @param {number} k
36+
* @return {number}
37+
*/
38+
var subarraySum = function(nums, k) {
39+
let tempSum = 0
40+
let ret = 0
41+
const sumCount = new Map()
42+
sumCount.set(0, 1)
43+
44+
for (const num of nums) {
45+
tempSum += num
46+
if (sumCount.has(tempSum - k)) {
47+
ret += sumCount.get(tempSum - k)
48+
}
49+
if (sumCount.has(tempSum)) {
50+
sumCount.set(tempSum, sumCount.get(tempSum) + 1)
51+
} else {
52+
sumCount.set(tempSum, 1)
53+
}
54+
}
55+
56+
return ret
57+
};
58+
59+
export { subarraySum }
60+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 647\. Palindromic Substrings
5+
6+
Medium
7+
8+
Given a string `s`, return _the number of **palindromic substrings** in it_.
9+
10+
A string is a **palindrome** when it reads the same backward as forward.
11+
12+
A **substring** is a contiguous sequence of characters within the string.
13+
14+
**Example 1:**
15+
16+
**Input:** s = "abc"
17+
18+
**Output:** 3
19+
20+
**Explanation:** Three palindromic strings: "a", "b", "c".
21+
22+
**Example 2:**
23+
24+
**Input:** s = "aaa"
25+
26+
**Output:** 6
27+
28+
**Explanation:** Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
29+
30+
**Constraints:**
31+
32+
* `1 <= s.length <= 1000`
33+
* `s` consists of lowercase English letters.
34+
35+
## Solution
36+
37+
```javascript
38+
/**
39+
* @param {string} s
40+
* @return {number}
41+
*/
42+
var countSubstrings = function(s) {
43+
const expand = (a, l, r, res) => {
44+
while (l >= 0 && r < a.length) {
45+
if (a[l] !== a[r]) {
46+
return
47+
} else {
48+
res.count++
49+
l--
50+
r++
51+
}
52+
}
53+
}
54+
55+
const a = s.split('')
56+
const res = { count: 0 }
57+
58+
for (let i = 0; i < a.length; i++) {
59+
expand(a, i, i, res) // Odd-length palindromes
60+
expand(a, i, i + 1, res) // Even-length palindromes
61+
}
62+
63+
return res.count
64+
};
65+
66+
export { countSubstrings }
67+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 739\. Daily Temperatures
5+
6+
Medium
7+
8+
Given an array of integers `temperatures` represents the daily temperatures, return _an array_ `answer` _such that_ `answer[i]` _is the number of days you have to wait after the_ <code>i<sup>th</sup></code> _day to get a warmer temperature_. If there is no future day for which this is possible, keep `answer[i] == 0` instead.
9+
10+
**Example 1:**
11+
12+
**Input:** temperatures = [73,74,75,71,69,72,76,73]
13+
14+
**Output:** [1,1,4,2,1,1,0,0]
15+
16+
**Example 2:**
17+
18+
**Input:** temperatures = [30,40,50,60]
19+
20+
**Output:** [1,1,1,0]
21+
22+
**Example 3:**
23+
24+
**Input:** temperatures = [30,60,90]
25+
26+
**Output:** [1,1,0]
27+
28+
**Constraints:**
29+
30+
* <code>1 <= temperatures.length <= 10<sup>5</sup></code>
31+
* `30 <= temperatures[i] <= 100`
32+
33+
## Solution
34+
35+
```javascript
36+
/**
37+
* @param {number[]} temperatures
38+
* @return {number[]}
39+
*/
40+
var dailyTemperatures = function(temperatures) {
41+
const sol = new Array(temperatures.length).fill(0)
42+
sol[temperatures.length - 1] = 0
43+
44+
for (let i = temperatures.length - 2; i >= 0; i--) {
45+
let j = i + 1
46+
while (j < temperatures.length) {
47+
if (temperatures[i] < temperatures[j]) {
48+
sol[i] = j - i
49+
break
50+
} else {
51+
if (sol[j] === 0) {
52+
break
53+
}
54+
j += sol[j]
55+
}
56+
}
57+
}
58+
59+
return sol
60+
};
61+
62+
export { dailyTemperatures }
63+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 763\. Partition Labels
5+
6+
Medium
7+
8+
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part.
9+
10+
Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`.
11+
12+
Return _a list of integers representing the size of these parts_.
13+
14+
**Example 1:**
15+
16+
**Input:** s = "ababcbacadefegdehijhklij"
17+
18+
**Output:** [9,7,8]
19+
20+
**Explanation:** The partition is "ababcbaca", "defegde", "hijhklij". This is a partition so that each letter appears in at most one part. A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits s into less parts.
21+
22+
**Example 2:**
23+
24+
**Input:** s = "eccbbbbdec"
25+
26+
**Output:** [10]
27+
28+
**Constraints:**
29+
30+
* `1 <= s.length <= 500`
31+
* `s` consists of lowercase English letters.
32+
33+
## Solution
34+
35+
```javascript
36+
/**
37+
* @param {string} s
38+
* @return {number[]}
39+
*/
40+
var partitionLabels = function(s) {
41+
const letters = s.split('')
42+
const result = []
43+
const position = new Array(26).fill(0)
44+
45+
// Record the last occurrence of each character
46+
for (let i = 0; i < letters.length; i++) {
47+
position[letters[i].charCodeAt(0) - 'a'.charCodeAt(0)] = i
48+
}
49+
50+
let prev = -1
51+
let max = 0
52+
53+
for (let i = 0; i < letters.length; i++) {
54+
max = Math.max(max, position[letters[i].charCodeAt(0) - 'a'.charCodeAt(0)])
55+
if (i === max) {
56+
result.push(i - prev)
57+
prev = i
58+
}
59+
}
60+
61+
return result
62+
};
63+
64+
export { partitionLabels }
65+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
[![](https://img.shields.io/github/stars/javadev/LeetCode-in-All?label=Stars&style=flat-square)](https://github.com/javadev/LeetCode-in-All)
2+
[![](https://img.shields.io/github/forks/javadev/LeetCode-in-All?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/javadev/LeetCode-in-All/fork)
3+
4+
## 1143\. Longest Common Subsequence
5+
6+
Medium
7+
8+
Given two strings `text1` and `text2`, return _the length of their longest **common subsequence**._ If there is no **common subsequence**, return `0`.
9+
10+
A **subsequence** of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
11+
12+
* For example, `"ace"` is a subsequence of `"abcde"`.
13+
14+
A **common subsequence** of two strings is a subsequence that is common to both strings.
15+
16+
**Example 1:**
17+
18+
**Input:** text1 = "abcde", text2 = "ace"
19+
20+
**Output:** 3
21+
22+
**Explanation:** The longest common subsequence is "ace" and its length is 3.
23+
24+
**Example 2:**
25+
26+
**Input:** text1 = "abc", text2 = "abc"
27+
28+
**Output:** 3
29+
30+
**Explanation:** The longest common subsequence is "abc" and its length is 3.
31+
32+
**Example 3:**
33+
34+
**Input:** text1 = "abc", text2 = "def"
35+
36+
**Output:** 0
37+
38+
**Explanation:** There is no such common subsequence, so the result is 0.
39+
40+
**Constraints:**
41+
42+
* `1 <= text1.length, text2.length <= 1000`
43+
* `text1` and `text2` consist of only lowercase English characters.
44+
45+
## Solution
46+
47+
```javascript
48+
/**
49+
* @param {string} text1
50+
* @param {string} text2
51+
* @return {number}
52+
*/
53+
var longestCommonSubsequence = function(text1, text2) {
54+
const rows = text1.length
55+
const columns = text2.length
56+
let prevRow = new Array(text2.length + 1).fill(0)
57+
58+
for(let i = rows - 1; i >= 0; i--) {
59+
const curRow = new Array(text2.length + 1).fill(0)
60+
for(let j = columns - 1; j >= 0; j--) {
61+
if(text1[i] == text2[j]) {
62+
curRow[j] = 1 + prevRow[j + 1]
63+
} else {
64+
curRow[j] = Math.max(prevRow[j], curRow[j + 1])
65+
}
66+
}
67+
prevRow = curRow
68+
}
69+
70+
return prevRow[0]
71+
};
72+
73+
export { longestCommonSubsequence }
74+
```

0 commit comments

Comments
 (0)
Please sign in to comment.