Skip to content

Commit 950ed7f

Browse files
committed
Added tasks 100-918
1 parent 400bbfa commit 950ed7f

File tree

12 files changed

+903
-2
lines changed

12 files changed

+903
-2
lines changed

README.md

+26-2
Large diffs are not rendered by default.

src/main/ts/g0001_0100/s0098_validate_binary_search_tree/readme.md

+13
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,19 @@ A **valid BST** is defined as follows:
4141
```typescript
4242
import { TreeNode } from '../../com_github_leetcode/treenode'
4343

44+
/**
45+
* Definition for a binary tree node.
46+
* class TreeNode {
47+
* val: number
48+
* left: TreeNode | null
49+
* right: TreeNode | null
50+
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
51+
* this.val = (val===undefined ? 0 : val)
52+
* this.left = (left===undefined ? null : left)
53+
* this.right = (right===undefined ? null : right)
54+
* }
55+
* }
56+
*/
4457
function dfs(node: TreeNode | null, lowerBound: number, upperBound: number): boolean {
4558
if (!node) return true
4659
if (node.val <= lowerBound) return false
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-TypeScript/LeetCode-in-TypeScript?label=Stars&style=flat-square)](https://github.com/LeetCode-in-TypeScript/LeetCode-in-TypeScript)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-TypeScript/LeetCode-in-TypeScript?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-TypeScript/LeetCode-in-TypeScript/fork)
3+
4+
## 100\. Same Tree
5+
6+
Easy
7+
8+
Given the roots of two binary trees `p` and `q`, write a function to check if they are the same or not.
9+
10+
Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
11+
12+
**Example 1:**
13+
14+
![](https://assets.leetcode.com/uploads/2020/12/20/ex1.jpg)
15+
16+
**Input:** p = [1,2,3], q = [1,2,3]
17+
18+
**Output:** true
19+
20+
**Example 2:**
21+
22+
![](https://assets.leetcode.com/uploads/2020/12/20/ex2.jpg)
23+
24+
**Input:** p = [1,2], q = [1,null,2]
25+
26+
**Output:** false
27+
28+
**Example 3:**
29+
30+
![](https://assets.leetcode.com/uploads/2020/12/20/ex3.jpg)
31+
32+
**Input:** p = [1,2,1], q = [1,1,2]
33+
34+
**Output:** false
35+
36+
**Constraints:**
37+
38+
* The number of nodes in both trees is in the range `[0, 100]`.
39+
* <code>-10<sup>4</sup> <= Node.val <= 10<sup>4</sup></code>
40+
41+
## Solution
42+
43+
```typescript
44+
import { TreeNode } from '../../com_github_leetcode/treenode'
45+
46+
/**
47+
* Definition for a binary tree node.
48+
* class TreeNode {
49+
* val: number
50+
* left: TreeNode | null
51+
* right: TreeNode | null
52+
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
53+
* this.val = (val===undefined ? 0 : val)
54+
* this.left = (left===undefined ? null : left)
55+
* this.right = (right===undefined ? null : right)
56+
* }
57+
* }
58+
*/
59+
function isSameTree(p: TreeNode | null, q: TreeNode | null): boolean {
60+
if (p === null || q === null) {
61+
return p === null && q === null
62+
}
63+
const b1 = isSameTree(p.left, q.left)
64+
const b2 = isSameTree(p.right, q.right)
65+
return p.val === q.val && b1 && b2
66+
}
67+
68+
export { isSameTree }
69+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-TypeScript/LeetCode-in-TypeScript?label=Stars&style=flat-square)](https://github.com/LeetCode-in-TypeScript/LeetCode-in-TypeScript)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-TypeScript/LeetCode-in-TypeScript?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-TypeScript/LeetCode-in-TypeScript/fork)
3+
4+
## 274\. H-Index
5+
6+
Medium
7+
8+
Given an array of integers `citations` where `citations[i]` is the number of citations a researcher received for their <code>i<sup>th</sup></code> paper, return compute the researcher's `h`**\-index**.
9+
10+
According to the [definition of h-index on Wikipedia](https://en.wikipedia.org/wiki/H-index): A scientist has an index `h` if `h` of their `n` papers have at least `h` citations each, and the other `n − h` papers have no more than `h` citations each.
11+
12+
If there are several possible values for `h`, the maximum one is taken as the `h`**\-index**.
13+
14+
**Example 1:**
15+
16+
**Input:** citations = [3,0,6,1,5]
17+
18+
**Output:** 3
19+
20+
**Explanation:**
21+
22+
[3,0,6,1,5] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively.
23+
Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3.
24+
25+
**Example 2:**
26+
27+
**Input:** citations = [1,3,1]
28+
29+
**Output:** 1
30+
31+
**Constraints:**
32+
33+
* `n == citations.length`
34+
* `1 <= n <= 5000`
35+
* `0 <= citations[i] <= 1000`
36+
37+
## Solution
38+
39+
```typescript
40+
function hIndex(citations: number[]): number {
41+
const len = citations.length
42+
const freqArray = new Array(len + 1).fill(0)
43+
for (const citation of citations) {
44+
freqArray[Math.min(citation, len)]++
45+
}
46+
let totalSoFar = 0
47+
for (let k = len; k >= 0; k--) {
48+
totalSoFar += freqArray[k]
49+
if (totalSoFar >= k) {
50+
return k
51+
}
52+
}
53+
return -1
54+
}
55+
56+
export { hIndex }
57+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-TypeScript/LeetCode-in-TypeScript?label=Stars&style=flat-square)](https://github.com/LeetCode-in-TypeScript/LeetCode-in-TypeScript)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-TypeScript/LeetCode-in-TypeScript?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-TypeScript/LeetCode-in-TypeScript/fork)
3+
4+
## 380\. Insert Delete GetRandom O(1)
5+
6+
Medium
7+
8+
Implement the `RandomizedSet` class:
9+
10+
* `RandomizedSet()` Initializes the `RandomizedSet` object.
11+
* `bool insert(int val)` Inserts an item `val` into the set if not present. Returns `true` if the item was not present, `false` otherwise.
12+
* `bool remove(int val)` Removes an item `val` from the set if present. Returns `true` if the item was present, `false` otherwise.
13+
* `int getRandom()` Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the **same probability** of being returned.
14+
15+
You must implement the functions of the class such that each function works in **average** `O(1)` time complexity.
16+
17+
**Example 1:**
18+
19+
**Input**
20+
21+
["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"]
22+
[[], [1], [2], [2], [], [1], [2], []]
23+
24+
**Output:** [null, true, false, true, 2, true, false, 2]
25+
26+
**Explanation:**
27+
28+
RandomizedSet randomizedSet = new RandomizedSet();
29+
randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.
30+
randomizedSet.remove(2); // Returns false as 2 does not exist in the set.
31+
randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2].
32+
randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.
33+
randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2].
34+
randomizedSet.insert(2); // 2 was already in the set, so return false.
35+
randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.
36+
37+
**Constraints:**
38+
39+
* <code>-2<sup>31</sup> <= val <= 2<sup>31</sup> - 1</code>
40+
* At most `2 * `<code>10<sup>5</sup></code> calls will be made to `insert`, `remove`, and `getRandom`.
41+
* There will be **at least one** element in the data structure when `getRandom` is called.
42+
43+
## Solution
44+
45+
```typescript
46+
class RandomizedSet {
47+
private rand: () => number
48+
private list: number[]
49+
private map: Map<number, number>
50+
51+
constructor() {
52+
this.rand = () => Math.floor(Math.random() * this.list.length) // NOSONAR
53+
this.list = []
54+
this.map = new Map()
55+
}
56+
57+
insert(val: number): boolean {
58+
if (this.map.has(val)) {
59+
return false
60+
}
61+
this.map.set(val, this.list.length)
62+
this.list.push(val)
63+
return true
64+
}
65+
66+
remove(val: number): boolean {
67+
if (!this.map.has(val)) {
68+
return false
69+
}
70+
const swap1 = this.map.get(val)!
71+
const swap2 = this.list.length - 1
72+
const val2 = this.list[swap2]
73+
this.map.set(val2, swap1)
74+
this.map.delete(val)
75+
this.list[swap1] = val2
76+
this.list.pop()
77+
return true
78+
}
79+
80+
getRandom(): number {
81+
return this.list[this.rand()]
82+
}
83+
}
84+
85+
/**
86+
* Your RandomizedSet object will be instantiated and called as such:
87+
* var obj = new RandomizedSet()
88+
* var param_1 = obj.insert(val)
89+
* var param_2 = obj.remove(val)
90+
* var param_3 = obj.getRandom()
91+
*/
92+
93+
export { RandomizedSet }
94+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-TypeScript/LeetCode-in-TypeScript?label=Stars&style=flat-square)](https://github.com/LeetCode-in-TypeScript/LeetCode-in-TypeScript)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-TypeScript/LeetCode-in-TypeScript?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-TypeScript/LeetCode-in-TypeScript/fork)
3+
4+
## 399\. Evaluate Division
5+
6+
Medium
7+
8+
You are given an array of variable pairs `equations` and an array of real numbers `values`, where <code>equations[i] = [A<sub>i</sub>, B<sub>i</sub>]</code> and `values[i]` represent the equation <code>A<sub>i</sub> / B<sub>i</sub> = values[i]</code>. Each <code>A<sub>i</sub></code> or <code>B<sub>i</sub></code> is a string that represents a single variable.
9+
10+
You are also given some `queries`, where <code>queries[j] = [C<sub>j</sub>, D<sub>j</sub>]</code> represents the <code>j<sup>th</sup></code> query where you must find the answer for <code>C<sub>j</sub> / D<sub>j</sub> = ?</code>.
11+
12+
Return _the answers to all queries_. If a single answer cannot be determined, return `-1.0`.
13+
14+
**Note:** The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.
15+
16+
**Example 1:**
17+
18+
**Input:** equations = \[\["a","b"],["b","c"]], values = [2.0,3.0], queries = \[\["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]]
19+
20+
**Output:** [6.00000,0.50000,-1.00000,1.00000,-1.00000]
21+
22+
**Explanation:**
23+
24+
Given: _a / b = 2.0_, _b / c = 3.0_
25+
26+
queries are: _a / c = ?_, _b / a = ?_, _a / e = ?_, _a / a = ?_, _x / x = ?_
27+
28+
return: [6.0, 0.5, -1.0, 1.0, -1.0 ]
29+
30+
**Example 2:**
31+
32+
**Input:** equations = \[\["a","b"],["b","c"],["bc","cd"]], values = [1.5,2.5,5.0], queries = \[\["a","c"],["c","b"],["bc","cd"],["cd","bc"]]
33+
34+
**Output:** [3.75000,0.40000,5.00000,0.20000]
35+
36+
**Example 3:**
37+
38+
**Input:** equations = \[\["a","b"]], values = [0.5], queries = \[\["a","b"],["b","a"],["a","c"],["x","y"]]
39+
40+
**Output:** [0.50000,2.00000,-1.00000,-1.00000]
41+
42+
**Constraints:**
43+
44+
* `1 <= equations.length <= 20`
45+
* `equations[i].length == 2`
46+
* <code>1 <= A<sub>i</sub>.length, B<sub>i</sub>.length <= 5</code>
47+
* `values.length == equations.length`
48+
* `0.0 < values[i] <= 20.0`
49+
* `1 <= queries.length <= 20`
50+
* `queries[i].length == 2`
51+
* <code>1 <= C<sub>j</sub>.length, D<sub>j</sub>.length <= 5</code>
52+
* <code>A<sub>i</sub>, B<sub>i</sub>, C<sub>j</sub>, D<sub>j</sub></code> consist of lower case English letters and digits.
53+
54+
## Solution
55+
56+
```typescript
57+
type MapType = Map<string, string>
58+
type RateType = Map<string, number>
59+
60+
function calcEquation(equations: [string, string][], values: number[], queries: [string, string][]): number[] {
61+
const root: MapType = new Map()
62+
const rate: RateType = new Map()
63+
for (const [x, y] of equations) {
64+
if (!root.has(x)) {
65+
root.set(x, x)
66+
rate.set(x, 1.0)
67+
}
68+
if (!root.has(y)) {
69+
root.set(y, y)
70+
rate.set(y, 1.0)
71+
}
72+
}
73+
for (let i = 0; i < equations.length; ++i) {
74+
const [x, y] = equations[i]
75+
union(x, y, values[i], root, rate)
76+
}
77+
const result: number[] = []
78+
for (const [x, y] of queries) {
79+
if (!root.has(x) || !root.has(y)) {
80+
result.push(-1.0)
81+
} else {
82+
const rootX = findRoot(x, x, 1.0, root, rate)
83+
const rootY = findRoot(y, y, 1.0, root, rate)
84+
if (rootX === rootY) {
85+
result.push(rate.get(x)! / rate.get(y)!)
86+
} else {
87+
result.push(-1.0)
88+
}
89+
}
90+
}
91+
return result
92+
}
93+
94+
function union(x: string, y: string, value: number, root: MapType, rate: RateType): void {
95+
const rootX = findRoot(x, x, 1.0, root, rate)
96+
const rootY = findRoot(y, y, 1.0, root, rate)
97+
98+
if (rootX !== rootY) {
99+
root.set(rootX, rootY)
100+
const rateX = rate.get(x)!
101+
const rateY = rate.get(y)!
102+
rate.set(rootX, (value * rateY) / rateX)
103+
}
104+
}
105+
106+
function findRoot(originalX: string, x: string, rateSoFar: number, root: MapType, rate: RateType): string {
107+
if (root.get(x) === x) {
108+
root.set(originalX, x)
109+
rate.set(originalX, rateSoFar * rate.get(x)!)
110+
return x
111+
}
112+
return findRoot(originalX, root.get(x)!, rateSoFar * rate.get(x)!, root, rate)
113+
}
114+
115+
export { calcEquation }
116+
```

0 commit comments

Comments
 (0)