Skip to content

Commit

Permalink
Merge branch 'release/1.28.0'
Browse files Browse the repository at this point in the history
  • Loading branch information
ecgan committed Jul 18, 2020
2 parents 8583800 + b711ff1 commit e782e30
Show file tree
Hide file tree
Showing 92 changed files with 2,920 additions and 3 deletions.
30 changes: 29 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,20 @@ The listing below is sorted based on LeetCode #. If you are interested to see my
| 49 | [Group Anagrams](/problems/group-anagrams) | Medium | Hash Table, String |
| 53 | [Maximum Subarray](/problems/maximum-subarray) | Easy | Array, Divide and Conquer, Dynamic Programming |
| 55 | [Jump Game](/problems/jump-game) | Medium | Array, Greedy |
| 60 | [Permutation Sequence](/problems/permutation-sequence) | Medium | Math, Backtracking |
| 62 | [Unique Paths](/problems/unique-paths) | Medium | Array, Dynamic Programming |
| 64 | [Minimum Path Sum](/problems/minimum-path-sum) | Medium | Array, Dynamic Programming |
| 70 | [Climbing Stairs](/problems/climbing-stairs) | Easy | Dynamic Programming |
| 72 | [Edit Distance](/problems/edit-distance) | Hard | String, Dynamic Programming |
| 75 | [Sort Colors](/problems/sort-colors) | Medium | Array, Two Pointers, Sort |
| 96 | [Unique Binary Search Trees](/problems/unique-binary-search-trees) | Medium | Dynamic Programming, Tree |
| 121 | [Best Time to Buy and Sell Stock](/problems/best-time-to-buy-and-sell-stock) | Easy | Array, Dynamic Programming |
| 122 | [Best Time to Buy and Sell Stock II](/problems/best-time-to-buy-and-sell-stock-ii) | Easy | Array, Greedy |
| 124 | [Binary Tree Maximum Path Sum](/problems/binary-tree-maximum-path-sum) | Hard | Tree, Depth-first Search |
| 129 | [Sum Root to Leaf Numbers](/problems/sum-root-to-leaf-numbers) | Medium | Tree, Depth-first Search |
| 130 | [Surrounded Regions](/problems/surrounded-regions) | Medium | Depth-first Search, Breadth-first Search, Union Find |
| 136 | [Single Number](/problems/single-number) | Easy | Hash table, bit manipulation |
| 137 | [Single Number II](/problems/single-number-ii) | Medium | Bit Manipulation |
| 146 | [LRU Cache](/problems/lru-cache) | Medium | Design |
| 155 | [Min Stack](/problems/min-stack) | Easy | Stack, Design |
| 169 | [Majority Element](/problems/majority-element) | Easy | Array, Divide and Conquer, Bit Manipulation |
Expand All @@ -70,33 +77,52 @@ The listing below is sorted based on LeetCode #. If you are interested to see my
| 202 | [Happy Number](/problems/happy-number) | Easy | Hash Table, Math |
| 207 | [Course Schedule](/problems/course-schedule) | Medium | Depth-first Search, Breadth-first Search, Graph, Topological Sort |
| 208 | [Implement Trie (Prefix Tree)](/problems/implement-trie-prefix-tree) | Medium | Design, Trie |
| 212 | [Word Search II](/problems/word-search-ii) | Hard | Backtracking, Trie |
| 221 | [Maximal Square](/problems/maximal-square) | Medium | Dynamic Programming |
| 222 | [Count Complete Tree Nodes](/problems/count-complete-tree-nodes) | Medium | Binary Search, Tree |
| 226 | [Invert Binary Tree](/problems/invert-binary-tree) | Easy | Tree |
| 230 | [Kth Smallest Element in a BST](/problems/kth-smallest-element-in-a-bst) | Medium | Binary Search, Tree |
| 231 | [Power of Two](/problems/power-of-two) | Easy | Math, Bit Manipulation |
| 237 | [Delete Node in a Linked List](/problems/delete-node-in-a-linked-list) | Easy | Linked List |
| 238 | [Product of Array Except Self](/problems/product-of-array-except-self) | Medium | Array |
| 275 | [H-Index II](/problems/h-index-ii) | Medium | Binary Search |
| 278 | [First Bad Version](/problems/first-bad-version) | Easy | Binary Search |
| 279 | [Perfect Squares](/problems/perfect-squares) | Medium | Math, Dynamic Programming, Breadth-first Search |
| 283 | [Move Zeroes](/problems/move-zeroes) | Easy | Array, Two Pointers |
| 287 | [Find the Duplicate Number](/problems/find-the-duplicate-number) | Medium | Array, Two Pointers, Binary Search |
| 303 | [Range Sum Query - Immutable](/problems/range-sum-query-immutable) | Easy | Dynamic Programming |
| 328 | [Odd Even Linked List](/problems/odd-even-linked-list) | Medium | Linked List |
| 332 | [Reconstruct Itinerary](/problems/reconstruct-itinerary) | Medium | Depth-first Search, Graph |
| 338 | [Counting Bits](/problems/counting-bits) | Medium | Dynamic Programming, Bit Manipulation |
| 344 | [Reverse String](/problems/reverse-string) | Easy | Two Pointers, String |
| 349 | [Intersection of Two Arrays](/problems/intersection-of-two-arrays) | Easy | Hash table, two pointers, binary search, sort, set |
| 350 | [Intersection of Two Arrays II](/problems/intersection-of-two-arrays-ii) | Easy | Hash Table, two pointers, binary search, sort |
| 367 | [Valid Perfect Square](/problems/valid-perfect-square) | Easy | Math, Binary Search |
| 368 | [Largest Divisible Subset](/problems/largest-divisible-subset) | Medium | Math, Dynamic Programming |
| 380 | [Insert Delete GetRandom O(1)](/problems/insert-delete-getrandom-o1) | Medium | Array, Hash Table, Design |
| 383 | [Ransom Note](/problems/ransom-note) | Easy | String |
| 387 | [First Unique Character in a String](/problems/first-unique-character-in-a-string) | Easy | Hash Table, String |
| 392 | [Is Subsequence](/problems/is-subsequence) | Easy | Binary Search, Dynamic Programming, Greedy |
| 402 | [Remove K Digits](/problems/remove-k-digits) | Medium | Stack, Greedy |
| 406 | [Queue Reconstruction by Height](/problems/queue-reconstruction-by-height) | Medium | Greedy |
| 438 | [Find All Anagrams in a String](/problems/find-all-anagrams-in-a-string) | Medium | Hash Table |
| 451 | [Sort Characters By Frequency](/problems/sort-characters-by-frequency) | Medium | Hash Table, Heap |
| 468 | [Validate IP Address](/problems/validate-ip-address) | Medium | String |
| 476 | [Number Complement](/problems/number-complement) | Easy | Bit Manipulation |
| 518 | [Coin Change 2](/problems/coin-change-2) | Medium | - |
| 525 | [Contiguous Array](/problems/contiguous-array) | Medium | Hash Table |
| 528 | [Random Pick with Weight](/problems/random-pick-with-weight) | Medium | Binary Search, Random |
| 540 | [Single Element in a Sorted Array](/problems/single-element-in-a-sorted-array) | Medium | - |
| 543 | [Diameter of Binary Tree](/problems/diameter-of-binary-tree) | Easy | Tree |
| 560 | [Subarray Sum Equals K](/problems/subarray-sum-equals-k) | Medium | Array, Hash Table |
| 567 | [Permutation in String](/problems/permutation-in-string) | Medium | Two Pointers, Sliding Window |
| 678 | [Valid Parenthesis String](/problems/valid-parenthesis-string) | Medium | String |
| 700 | [Search in a Binary Search Tree](/problems/search-in-a-binary-search-tree) | Easy | Tree |
| 714 | [Dungeon Game](/problems/dungeon-game) | Hard | Binary Search, Dynamic Programming |
| 733 | [Flood Fill](/problems/flood-fill) | Easy | Depth-first Search |
| 746 | [Min Cost Climbing Stairs](/problems/min-cost-climbing-stairs) | Easy | Array, Dynamic Programming |
| 771 | [Jewels and Stones](/problems/jewels-and-stones) | Easy | Hash Table |
| 787 | [Cheapest Flights Within K Stops](/problems/cheapest-flights-within-k-stops) | Medium | Dynamic Programming, Heap, Breadth-first Search |
| 844 | [Backspace String Compare](/problems/backspace-string-compare) | Easy | Two Pointers, Stack |
| 876 | [Middle of the Linked List](/problems/middle-of-the-linked-list) | Easy | Linked List |
| 886 | [Possible Bipartition](/problems/possible-bipartition) | Medium | Depth-first Search |
Expand All @@ -108,7 +134,9 @@ The listing below is sorted based on LeetCode #. If you are interested to see my
| 997 | [Find the Town Judge](/problems/find-the-town-judge) | Easy | Graph |
| 1008 | [Construct Binary Search Tree from Preorder Traversal](/problems/construct-binary-search-tree-from-preorder-traversal) | Medium | Tree |
| 1025 | [Divisor Game](/problems/divisor-game) | Easy | Math, Dynamic Programming |
| 1029 | [Two City Scheduling](/problems/two-city-scheduling) | Easy | Greedy |
| 1035 | [Uncrossed Lines](/problems/uncrossed-lines) | Medium | Array |
| 1044 | [Longest Duplicate Substring](/problems/longest-duplicate-substring) | Hard | Hash Table, Binary Search |
| 1046 | [Last Stone Weight](/problems/last-stone-weight) | Easy | Heap, Greedy |
| 1143 | [Longest Common Subsequence](/problems/longest-common-subsequence) | Medium | Dynamic Programming |
| 1144 | [Decrease Elements To Make Array Zigzag](/problems/decrease-elements-to-make-array-zigzag) | Medium | Array |
Expand Down Expand Up @@ -180,7 +208,7 @@ The listing below is sorted based on LeetCode #. If you are interested to see my
| 1476 | [Subrectangle Queries](/problems/subrectangle-queries) | Medium | Array |
| 1480 | [Running Sum of 1d Array](/problems/running-sum-of-1d-array) | Easy | Array |
| 1481 | [Least Number of Unique Integers after K Removals](/problems/least-number-of-unique-integers-after-k-removals) | Medium | Array, Sort |
| 1491 | [Average Salary Excluding the Minimum and Maximum Salary](/problems/average-salary-excluding-the-minimum-and-maximum-salary) | Easy | Array, Sort. |
| 1491 | [Average Salary Excluding the Minimum and Maximum Salary](/problems/average-salary-excluding-the-minimum-and-maximum-salary) | Easy | Array, Sort |
| 1492 | [The kth Factor of n](/problems/the-kth-factor-of-n) | Medium | Math |
| 1493 | [Longest Subarray of 1's After Deleting One Element](/problems/longest-subarray-of-1s-after-deleting-one-element) | Medium | Array |

Expand Down
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "leetcode",
"version": "1.27.0",
"version": "1.28.0",
"description": "My solutions for LeetCode problems.",
"main": "index.js",
"scripts": {
Expand Down
54 changes: 54 additions & 0 deletions problems/cheapest-flights-within-k-stops/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Cheapest Flights Within K Stops

LeetCode #: [787](https://leetcode.com/problems/cheapest-flights-within-k-stops/)

Difficulty: Medium

Topics: Dynamic Programming, Heap, Breadth-first Search.

## Problem

There are `n` cities connected by `m` flights. Each flight starts from city `u` and arrives at `v` with a price `w`.

Now given all the cities and flights, together with starting city `src` and the destination `dst`, your task is to find the cheapest price from `src` to `dst` with up to `k` stops. If there is no such route, output `-1`.

Example 1:

![image](https://s3-lc-upload.s3.amazonaws.com/uploads/2018/02/16/995.png)

```text
Input:
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 1
Output: 200
Explanation:
The cheapest price from city 0 to city 2 with at most 1 stop costs 200, as marked red in the picture.
```

Example 2:

![image](https://s3-lc-upload.s3.amazonaws.com/uploads/2018/02/16/995.png)

```text
Input:
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 0
Output: 500
Explanation:
The cheapest price from city 0 to city 2 with at most 0 stop costs 500, as marked blue in the picture.
```

Constraints:

- The number of nodes `n` will be in range `[1, 100]`, with nodes labeled from `0` to `n - 1`.
- The size of flights will be in range `[0, n * (n - 1) / 2]`.
- The format of each flight will be `(src, dst, price)`.
- The price of each flight will be in the range `[1, 10000]`.
- `k` is in the range of `[0, n - 1]`.
- There will not be any duplicated flights or self cycles.

## Solution Explanation

The idea is based on [Dijkstra's algorithm](https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm).

Reference: [[Java/Python] Priority Queue Solution](https://leetcode.com/problems/cheapest-flights-within-k-stops/discuss/115541/JavaPython-Priority-Queue-Solution) by [lee215](https://leetcode.com/lee215)
53 changes: 53 additions & 0 deletions problems/cheapest-flights-within-k-stops/findCheapestPrice.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
const sortedIndexBy = require('lodash/sortedIndexBy')

// get a src->dst->price map object based on flights.
const getSrcDstPriceMap = (flights) => {
const srcDstPriceMap = new Map()

for (let i = 0; i < flights.length; i++) {
const [src, dst, price] = flights[i]
srcDstPriceMap.set(src, (srcDstPriceMap.get(src) || new Map()).set(dst, price))
}

return srcDstPriceMap
}

/**
* @param {number} n
* @param {number[][]} flights
* @param {number} src
* @param {number} dst
* @param {number} K
* @return {number}
*/
const findCheapestPrice = function (n, flights, src, dst, k) {
const srcDstPriceMap = getSrcDstPriceMap(flights)

// a priority queue that sorts based on accumulated price.
// each item is in the format [accumulated price, current city, remaining flights].
// note that remaining flights is equal to k+1.
const queue = []
queue.push([0, src, k + 1])

while (queue.length > 0) {
const [accPrice, city, remainingFlights] = queue.shift()

if (city === dst) {
return accPrice
}

if (remainingFlights > 0) {
const adjDstPriceMap = srcDstPriceMap.get(city) || new Map()

for (const [dst, price] of adjDstPriceMap.entries()) {
const next = [accPrice + price, dst, remainingFlights - 1]
const idx = sortedIndexBy(queue, next, (o) => o[0])
queue.splice(idx, 0, next)
}
}
}

return -1
}

module.exports = findCheapestPrice
49 changes: 49 additions & 0 deletions problems/cheapest-flights-within-k-stops/findCheapestPrice.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
const findCheapestPrice = require('./findCheapestPrice')

test('Example 1', () => {
const n = 3
const flights = [[0, 1, 100], [1, 2, 100], [0, 2, 500]]
const src = 0
const dst = 2
const k = 1

const result = findCheapestPrice(n, flights, src, dst, k)

expect(result).toBe(200)
})

test('Example 2', () => {
const n = 3
const flights = [[0, 1, 100], [1, 2, 100], [0, 2, 500]]
const src = 0
const dst = 2
const k = 0

const result = findCheapestPrice(n, flights, src, dst, k)

expect(result).toBe(500)
})

test('no such route should return -1', () => {
const n = 4
const flights = [[0, 1, 100], [1, 2, 100], [0, 2, 500], [2, 3, 200]]
const src = 0
const dst = 3
const k = 0

const result = findCheapestPrice(n, flights, src, dst, k)

expect(result).toBe(-1)
})

test('intermediate city 4 has no flight out', () => {
const n = 4
const flights = [[0, 1, 100], [1, 4, 120], [0, 2, 500], [2, 3, 200]]
const src = 0
const dst = 3
const k = 5

const result = findCheapestPrice(n, flights, src, dst, k)

expect(result).toBe(700)
})
61 changes: 61 additions & 0 deletions problems/coin-change-2/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# Coin Change 2

LeetCode #: [518](https://leetcode.com/problems/coin-change-2/)

Difficulty: Medium

Topics: -

## Problem

You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that amount. You may assume that you have infinite number of each kind of coin.

Example 1:

```text
Input: amount = 5, coins = [1, 2, 5]
Output: 4
Explanation: there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1
```

Example 2:

```text
Input: amount = 3, coins = [2]
Output: 0
Explanation: the amount of 3 cannot be made up just with coins of 2.
```

Example 3:

```text
Input: amount = 10, coins = [10]
Output: 1
```

Note:

You can assume that

- `0 <= amount <= 5000`
- `1 <= coin <= 5000`
- the number of coins is less than 500
- the answer is guaranteed to fit into signed 32-bit integer

## Solution Explanation

This is a [knapsack problem](https://en.wikipedia.org/wiki/Knapsack_problem) which can be solved by using dynamic programming.

Reference: [Knapsack problem - Java solution with thinking process O(nm) Time and O(m) Space](https://leetcode.com/problems/coin-change-2/discuss/99212/Knapsack-problem-Java-solution-with-thinking-process-O(nm)-Time-and-O(m)-Space) by [tankztc](https://leetcode.com/tankztc)

## Complexity Analysis

Assume m is the amount and n is the number of coins.

Time complexity: O(mn)

Space complexity: O(m)
18 changes: 18 additions & 0 deletions problems/coin-change-2/change.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* @param {number} amount
* @param {number[]} coins
* @return {number}
*/
const change = function (amount, coins) {
const dp = new Array(amount + 1).fill(0)
dp[0] = 1
for (const coin of coins) {
for (let i = coin; i <= amount; i++) {
dp[i] += dp[i - coin]
}
}

return dp[amount]
}

module.exports = change
37 changes: 37 additions & 0 deletions problems/coin-change-2/change.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
const change = require('./change')

test('Example 1', () => {
const amount = 5
const coins = [1, 2, 5]

const result = change(amount, coins)

expect(result).toBe(4)
})

test('Example 2', () => {
const amount = 3
const coins = [2]

const result = change(amount, coins)

expect(result).toBe(0)
})

test('Example 3', () => {
const amount = 10
const coins = [10]

const result = change(amount, coins)

expect(result).toBe(1)
})

test('amount 0 should return 1 (empty combination)', () => {
const amount = 0
const coins = [1, 2, 5]

const result = change(amount, coins)

expect(result).toBe(1)
})
Loading

0 comments on commit e782e30

Please sign in to comment.