From 7ad7e5c1c040510b7b7bd225ed4297054464dbc6 Mon Sep 17 00:00:00 2001 From: franklingu Date: Mon, 2 Jan 2023 10:05:35 +0800 Subject: [PATCH] add more solutions --- README.md | 60 +++++++++- download_solutions.py | 35 +++--- .../Solution.sql | 47 ++++++++ .../add-to-array-form-of-integer/Solution.py | 58 ++++++++++ .../Solution.py | 60 ++++++++++ questions/article-views-i/Solution.sql | 50 ++++++++ questions/basic-calculator/Solution.py | 90 +++++++++++++++ .../binary-prefix-divisible-by-5/Solution.py | 41 +++++++ .../Solution.py | 55 +++++++++ .../Solution.sql | 52 +++++++++ questions/day-of-the-week/Solution.py | 34 ++++++ questions/day-of-the-year/Solution.py | 32 ++++++ questions/defanging-an-ip-address/Solution.py | 23 ++++ .../delete-columns-to-make-sorted/Solution.py | 66 +++++++++++ .../Solution.py | 56 +++++++++ questions/di-string-match/Solution.py | 44 +++++++ .../distance-between-bus-stops/Solution.py | 49 ++++++++ .../distribute-candies-to-people/Solution.py | 53 +++++++++ questions/divisor-game/Solution.py | 50 ++++++++ questions/duplicate-zeros/Solution.py | 57 +++++++++ questions/find-common-characters/Solution.py | 40 +++++++ questions/find-customer-referee/Solution.sql | 49 ++++++++ .../find-if-path-exists-in-graph/Solution.py | 63 ++++++++++ .../Solution.py | 66 +++++++++++ .../Solution.py | 41 +++++++ questions/game-play-analysis-i/Solution.sql | 49 ++++++++ questions/height-checker/Solution.py | 46 ++++++++ .../largest-perimeter-triangle/Solution.py | 43 +++++++ questions/long-pressed-name/Solution.py | 53 +++++++++ .../Solution.py | 39 +++++++ .../Solution.py | 41 +++++++ .../Solution.py | 56 +++++++++ .../maximum-number-of-balloons/Solution.py | 46 ++++++++ .../Solution.py | 53 +++++++++ .../Solution.py | 50 ++++++++ .../minimum-absolute-difference/Solution.py | 48 ++++++++ .../minimum-average-difference/Solution.py | 64 +++++++++++ .../Solution.py | 50 ++++++++ .../minimum-falling-path-sum/Solution.py | 47 ++++++++ .../Solution.py | 50 ++++++++ questions/n-th-tribonacci-number/Solution.py | 38 ++++++ .../Solution.py | 82 +++++++++++++ .../non-decreasing-subsequences/Solution.py | 45 ++++++++ .../Solution.py | 38 ++++++ .../occurrences-after-bigram/Solution.py | 35 ++++++ .../Solution.py | 56 +++++++++ questions/print-in-order/Solution.py | 60 ++++++++++ questions/rectangle-area/Solution.py | 32 ++++++ questions/relative-sort-array/Solution.py | 41 +++++++ .../Solution.py | 50 ++++++++ questions/sales-analysis-iii/Solution.sql | 108 ++++++++++++++++++ questions/sales-person/Solution.sql | 102 +++++++++++++++++ questions/shift-2d-grid/Solution.py | 51 +++++++++ .../shortest-completing-word/Solution.py | 58 ++++++++++ questions/single-threaded-cpu/Solution.py | 72 ++++++++++++ .../Solution.py | 49 ++++++++ .../unique-number-of-occurrences/Solution.py | 34 ++++++ questions/unique-paths-iii/Solution.py | 89 +++++++++++++++ .../Solution.sql | 58 ++++++++++ questions/valid-boomerang/Solution.py | 30 +++++ 60 files changed, 3114 insertions(+), 20 deletions(-) create mode 100644 questions/actors-and-directors-who-cooperated-at-least-three-times/Solution.sql create mode 100644 questions/add-to-array-form-of-integer/Solution.py create mode 100644 questions/arithmetic-slices-ii-subsequence/Solution.py create mode 100644 questions/article-views-i/Solution.sql create mode 100644 questions/basic-calculator/Solution.py create mode 100644 questions/binary-prefix-divisible-by-5/Solution.py create mode 100644 questions/cells-with-odd-values-in-a-matrix/Solution.py create mode 100644 questions/customer-placing-the-largest-number-of-orders/Solution.sql create mode 100644 questions/day-of-the-week/Solution.py create mode 100644 questions/day-of-the-year/Solution.py create mode 100644 questions/defanging-an-ip-address/Solution.py create mode 100644 questions/delete-columns-to-make-sorted/Solution.py create mode 100644 questions/determine-if-two-strings-are-close/Solution.py create mode 100644 questions/di-string-match/Solution.py create mode 100644 questions/distance-between-bus-stops/Solution.py create mode 100644 questions/distribute-candies-to-people/Solution.py create mode 100644 questions/divisor-game/Solution.py create mode 100644 questions/duplicate-zeros/Solution.py create mode 100644 questions/find-common-characters/Solution.py create mode 100644 questions/find-customer-referee/Solution.sql create mode 100644 questions/find-if-path-exists-in-graph/Solution.py create mode 100644 questions/find-players-with-zero-or-one-losses/Solution.py create mode 100644 questions/find-words-that-can-be-formed-by-characters/Solution.py create mode 100644 questions/game-play-analysis-i/Solution.sql create mode 100644 questions/height-checker/Solution.py create mode 100644 questions/largest-perimeter-triangle/Solution.py create mode 100644 questions/long-pressed-name/Solution.py create mode 100644 questions/longest-subsequence-with-limited-sum/Solution.py create mode 100644 questions/matrix-cells-in-distance-order/Solution.py create mode 100644 questions/maximum-bags-with-full-capacity-of-rocks/Solution.py create mode 100644 questions/maximum-number-of-balloons/Solution.py create mode 100644 questions/maximum-product-of-splitted-binary-tree/Solution.py create mode 100644 questions/maximum-profit-in-job-scheduling/Solution.py create mode 100644 questions/minimum-absolute-difference/Solution.py create mode 100644 questions/minimum-average-difference/Solution.py create mode 100644 questions/minimum-cost-to-move-chips-to-the-same-position/Solution.py create mode 100644 questions/minimum-falling-path-sum/Solution.py create mode 100644 questions/minimum-time-visiting-all-points/Solution.py create mode 100644 questions/n-th-tribonacci-number/Solution.py create mode 100644 questions/nearest-exit-from-entrance-in-maze/Solution.py create mode 100644 questions/non-decreasing-subsequences/Solution.py create mode 100644 questions/number-of-equivalent-domino-pairs/Solution.py create mode 100644 questions/occurrences-after-bigram/Solution.py create mode 100644 questions/partition-array-into-three-parts-with-equal-sum/Solution.py create mode 100644 questions/print-in-order/Solution.py create mode 100644 questions/rectangle-area/Solution.py create mode 100644 questions/relative-sort-array/Solution.py create mode 100644 questions/remove-stones-to-minimize-the-total/Solution.py create mode 100644 questions/sales-analysis-iii/Solution.sql create mode 100644 questions/sales-person/Solution.sql create mode 100644 questions/shift-2d-grid/Solution.py create mode 100644 questions/shortest-completing-word/Solution.py create mode 100644 questions/single-threaded-cpu/Solution.py create mode 100644 questions/split-a-string-in-balanced-strings/Solution.py create mode 100644 questions/unique-number-of-occurrences/Solution.py create mode 100644 questions/unique-paths-iii/Solution.py create mode 100644 questions/user-activity-for-the-past-30-days-i/Solution.sql create mode 100644 questions/valid-boomerang/Solution.py diff --git a/README.md b/README.md index 3124b24..9d53833 100644 --- a/README.md +++ b/README.md @@ -223,6 +223,8 @@ LeetCode is a very good website to sharpen your programming/problem-solving skil |220|[Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii/)|[Python](./questions/contains-duplicate-iii/)|![Hard](https://img.shields.io/badge/-Hard-red)| |221|[Maximal Square](https://leetcode.com/problems/maximal-square/)|[Python](./questions/maximal-square/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |222|[Count Complete Tree Nodes](https://leetcode.com/problems/count-complete-tree-nodes/)|[Python](./questions/count-complete-tree-nodes/)|![Medium](https://img.shields.io/badge/-Medium-orange)| +|223|[Rectangle Area](https://leetcode.com/problems/rectangle-area/)|[Python](./questions/rectangle-area/)|![Medium](https://img.shields.io/badge/-Medium-orange)| +|224|[Basic Calculator](https://leetcode.com/problems/basic-calculator/)|[Python](./questions/basic-calculator/)|![Hard](https://img.shields.io/badge/-Hard-red)| |225|[Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues/)|[Python](./questions/implement-stack-using-queues/)|![Easy](https://img.shields.io/badge/-Easy-green)| |226|[Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/)|[Java,Python](./questions/invert-binary-tree/)|![Easy](https://img.shields.io/badge/-Easy-green)| |227|[Basic Calculator II](https://leetcode.com/problems/basic-calculator-ii/)|[Python](./questions/basic-calculator-ii/)|![Medium](https://img.shields.io/badge/-Medium-orange)| @@ -374,6 +376,7 @@ LeetCode is a very good website to sharpen your programming/problem-solving skil |442|[Find All Duplicates in an Array](https://leetcode.com/problems/find-all-duplicates-in-an-array/)|[Python](./questions/find-all-duplicates-in-an-array/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |443|[String Compression](https://leetcode.com/problems/string-compression/)|[Python](./questions/string-compression/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |445|[Add Two Numbers II](https://leetcode.com/problems/add-two-numbers-ii/)|[Python](./questions/add-two-numbers-ii/)|![Medium](https://img.shields.io/badge/-Medium-orange)| +|446|[Arithmetic Slices II - Subsequence](https://leetcode.com/problems/arithmetic-slices-ii-subsequence/)|[Python](./questions/arithmetic-slices-ii-subsequence/)|![Hard](https://img.shields.io/badge/-Hard-red)| |447|[Number of Boomerangs](https://leetcode.com/problems/number-of-boomerangs/)|[Python](./questions/number-of-boomerangs/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |448|[Find All Numbers Disappeared in an Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/)|[Java](./questions/find-all-numbers-disappeared-in-an-array/)|![Easy](https://img.shields.io/badge/-Easy-green)| |449|[Serialize and Deserialize BST](https://leetcode.com/problems/serialize-and-deserialize-bst/)|[Python](./questions/serialize-and-deserialize-bst/)|![Medium](https://img.shields.io/badge/-Medium-orange)| @@ -399,7 +402,7 @@ LeetCode is a very good website to sharpen your programming/problem-solving skil |485|[Max Consecutive Ones](https://leetcode.com/problems/max-consecutive-ones/)|[Java](./questions/max-consecutive-ones/)|![Easy](https://img.shields.io/badge/-Easy-green)| |487|[Max Consecutive Ones II](https://leetcode.com/problems/max-consecutive-ones-ii/)|[Python](./questions/max-consecutive-ones-ii/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |489|[Robot Room Cleaner](https://leetcode.com/problems/robot-room-cleaner/)|[Python](./questions/robot-room-cleaner/)|![Hard](https://img.shields.io/badge/-Hard-red)| -|491|[Increasing Subsequences](https://leetcode.com/problems/increasing-subsequences/)|[Python](./questions/increasing-subsequences/)|![Medium](https://img.shields.io/badge/-Medium-orange)| +|491|[Non-decreasing Subsequences](https://leetcode.com/problems/non-decreasing-subsequences/)|[Python](./questions/non-decreasing-subsequences/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |492|[Construct the Rectangle](https://leetcode.com/problems/construct-the-rectangle/)|[Python](./questions/construct-the-rectangle/)|![Easy](https://img.shields.io/badge/-Easy-green)| |494|[Target Sum](https://leetcode.com/problems/target-sum/)|[Python](./questions/target-sum/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |495|[Teemo Attacking](https://leetcode.com/problems/teemo-attacking/)|[Python](./questions/teemo-attacking/)|![Easy](https://img.shields.io/badge/-Easy-green)| @@ -412,6 +415,7 @@ LeetCode is a very good website to sharpen your programming/problem-solving skil |506|[Relative Ranks](https://leetcode.com/problems/relative-ranks/)|[Python](./questions/relative-ranks/)|![Easy](https://img.shields.io/badge/-Easy-green)| |507|[Perfect Number](https://leetcode.com/problems/perfect-number/)|[Python](./questions/perfect-number/)|![Easy](https://img.shields.io/badge/-Easy-green)| |509|[Fibonacci Number](https://leetcode.com/problems/fibonacci-number/)|[Python](./questions/fibonacci-number/)|![Easy](https://img.shields.io/badge/-Easy-green)| +|511|[Game Play Analysis I](https://leetcode.com/problems/game-play-analysis-i/)|[SQL](./questions/game-play-analysis-i/)|![Easy](https://img.shields.io/badge/-Easy-green)| |516|[Longest Palindromic Subsequence](https://leetcode.com/problems/longest-palindromic-subsequence/)|[Python](./questions/longest-palindromic-subsequence/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |518|[Coin Change II](https://leetcode.com/problems/coin-change-ii/)|[Python](./questions/coin-change-ii/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |520|[Detect Capital](https://leetcode.com/problems/detect-capital/)|[Python](./questions/detect-capital/)|![Easy](https://img.shields.io/badge/-Easy-green)| @@ -450,6 +454,8 @@ LeetCode is a very good website to sharpen your programming/problem-solving skil |575|[Distribute Candies](https://leetcode.com/problems/distribute-candies/)|[Python](./questions/distribute-candies/)|![Easy](https://img.shields.io/badge/-Easy-green)| |576|[Out of Boundary Paths](https://leetcode.com/problems/out-of-boundary-paths/)|[Python](./questions/out-of-boundary-paths/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |581|[Shortest Unsorted Continuous Subarray](https://leetcode.com/problems/shortest-unsorted-continuous-subarray/)|[Java](./questions/shortest-unsorted-continuous-subarray/)|![Medium](https://img.shields.io/badge/-Medium-orange)| +|584|[Find Customer Referee](https://leetcode.com/problems/find-customer-referee/)|[SQL](./questions/find-customer-referee/)|![Easy](https://img.shields.io/badge/-Easy-green)| +|586|[Customer Placing the Largest Number of Orders](https://leetcode.com/problems/customer-placing-the-largest-number-of-orders/)|[SQL](./questions/customer-placing-the-largest-number-of-orders/)|![Easy](https://img.shields.io/badge/-Easy-green)| |587|[Erect the Fence](https://leetcode.com/problems/erect-the-fence/)|[Python](./questions/erect-the-fence/)|![Hard](https://img.shields.io/badge/-Hard-red)| |589|[N-ary Tree Preorder Traversal](https://leetcode.com/problems/n-ary-tree-preorder-traversal/)|[Python](./questions/n-ary-tree-preorder-traversal/)|![Easy](https://img.shields.io/badge/-Easy-green)| |590|[N-ary Tree Postorder Traversal](https://leetcode.com/problems/n-ary-tree-postorder-traversal/)|[Python](./questions/n-ary-tree-postorder-traversal/)|![Easy](https://img.shields.io/badge/-Easy-green)| @@ -461,6 +467,7 @@ LeetCode is a very good website to sharpen your programming/problem-solving skil |601|[Human Traffic of Stadium](https://leetcode.com/problems/human-traffic-of-stadium/)|[SQL](./questions/human-traffic-of-stadium/)|![Hard](https://img.shields.io/badge/-Hard-red)| |605|[Can Place Flowers](https://leetcode.com/problems/can-place-flowers/)|[Java](./questions/can-place-flowers/)|![Easy](https://img.shields.io/badge/-Easy-green)| |606|[Construct String from Binary Tree](https://leetcode.com/problems/construct-string-from-binary-tree/)|[Python](./questions/construct-string-from-binary-tree/)|![Easy](https://img.shields.io/badge/-Easy-green)| +|607|[Sales Person](https://leetcode.com/problems/sales-person/)|[SQL](./questions/sales-person/)|![Easy](https://img.shields.io/badge/-Easy-green)| |609|[Find Duplicate File in System](https://leetcode.com/problems/find-duplicate-file-in-system/)|[Python](./questions/find-duplicate-file-in-system/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |611|[Valid Triangle Number](https://leetcode.com/problems/valid-triangle-number/)|[Python](./questions/valid-triangle-number/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |617|[Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees/)|[Java](./questions/merge-two-binary-trees/)|![Easy](https://img.shields.io/badge/-Easy-green)| @@ -533,6 +540,7 @@ LeetCode is a very good website to sharpen your programming/problem-solving skil |745|[Prefix and Suffix Search](https://leetcode.com/problems/prefix-and-suffix-search/)|[Python](./questions/prefix-and-suffix-search/)|![Hard](https://img.shields.io/badge/-Hard-red)| |746|[Min Cost Climbing Stairs](https://leetcode.com/problems/min-cost-climbing-stairs/)|[Python](./questions/min-cost-climbing-stairs/)|![Easy](https://img.shields.io/badge/-Easy-green)| |747|[Largest Number At Least Twice of Others](https://leetcode.com/problems/largest-number-at-least-twice-of-others/)|[Python](./questions/largest-number-at-least-twice-of-others/)|![Easy](https://img.shields.io/badge/-Easy-green)| +|748|[Shortest Completing Word](https://leetcode.com/problems/shortest-completing-word/)|[Python](./questions/shortest-completing-word/)|![Easy](https://img.shields.io/badge/-Easy-green)| |752|[Open the Lock](https://leetcode.com/problems/open-the-lock/)|[Python](./questions/open-the-lock/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |753|[Cracking the Safe](https://leetcode.com/problems/cracking-the-safe/)|[Python](./questions/cracking-the-safe/)|![Hard](https://img.shields.io/badge/-Hard-red)| |760|[Find Anagram Mappings](https://leetcode.com/problems/find-anagram-mappings/)|[Python](./questions/find-anagram-mappings/)|![Easy](https://img.shields.io/badge/-Easy-green)| @@ -628,13 +636,17 @@ LeetCode is a very good website to sharpen your programming/problem-solving skil |918|[Maximum Sum Circular Subarray](https://leetcode.com/problems/maximum-sum-circular-subarray/)|[Python](./questions/maximum-sum-circular-subarray/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |921|[Minimum Add to Make Parentheses Valid](https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/)|[Python](./questions/minimum-add-to-make-parentheses-valid/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |922|[Sort Array By Parity II](https://leetcode.com/problems/sort-array-by-parity-ii/)|[Python](./questions/sort-array-by-parity-ii/)|![Easy](https://img.shields.io/badge/-Easy-green)| +|925|[Long Pressed Name](https://leetcode.com/problems/long-pressed-name/)|[Python](./questions/long-pressed-name/)|![Easy](https://img.shields.io/badge/-Easy-green)| |929|[Unique Email Addresses](https://leetcode.com/problems/unique-email-addresses/)|[Python](./questions/unique-email-addresses/)|![Easy](https://img.shields.io/badge/-Easy-green)| +|931|[Minimum Falling Path Sum](https://leetcode.com/problems/minimum-falling-path-sum/)|[Python](./questions/minimum-falling-path-sum/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |932|[Beautiful Array](https://leetcode.com/problems/beautiful-array/)|[Python](./questions/beautiful-array/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |933|[Number of Recent Calls](https://leetcode.com/problems/number-of-recent-calls/)|[Python](./questions/number-of-recent-calls/)|![Easy](https://img.shields.io/badge/-Easy-green)| |935|[Knight Dialer](https://leetcode.com/problems/knight-dialer/)|[Python](./questions/knight-dialer/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |938|[Range Sum of BST](https://leetcode.com/problems/range-sum-of-bst/)|[Python](./questions/range-sum-of-bst/)|![Easy](https://img.shields.io/badge/-Easy-green)| |939|[Minimum Area Rectangle](https://leetcode.com/problems/minimum-area-rectangle/)|[Python](./questions/minimum-area-rectangle/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |941|[Valid Mountain Array](https://leetcode.com/problems/valid-mountain-array/)|[Python](./questions/valid-mountain-array/)|![Easy](https://img.shields.io/badge/-Easy-green)| +|942|[DI String Match](https://leetcode.com/problems/di-string-match/)|[Python](./questions/di-string-match/)|![Easy](https://img.shields.io/badge/-Easy-green)| +|944|[Delete Columns to Make Sorted](https://leetcode.com/problems/delete-columns-to-make-sorted/)|[Python](./questions/delete-columns-to-make-sorted/)|![Easy](https://img.shields.io/badge/-Easy-green)| |946|[Validate Stack Sequences](https://leetcode.com/problems/validate-stack-sequences/)|[Python](./questions/validate-stack-sequences/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |947|[Most Stones Removed with Same Row or Column](https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/)|[Python](./questions/most-stones-removed-with-same-row-or-column/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |948|[Bag of Tokens](https://leetcode.com/problems/bag-of-tokens/)|[Python](./questions/bag-of-tokens/)|![Medium](https://img.shields.io/badge/-Medium-orange)| @@ -652,54 +664,90 @@ LeetCode is a very good website to sharpen your programming/problem-solving skil |970|[Powerful Integers](https://leetcode.com/problems/powerful-integers/)|[Python](./questions/powerful-integers/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |973|[K Closest Points to Origin](https://leetcode.com/problems/k-closest-points-to-origin/)|[Python](./questions/k-closest-points-to-origin/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |975|[Odd Even Jump](https://leetcode.com/problems/odd-even-jump/)|[Python](./questions/odd-even-jump/)|![Hard](https://img.shields.io/badge/-Hard-red)| +|976|[Largest Perimeter Triangle](https://leetcode.com/problems/largest-perimeter-triangle/)|[Python](./questions/largest-perimeter-triangle/)|![Easy](https://img.shields.io/badge/-Easy-green)| |977|[Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/)|[Python](./questions/squares-of-a-sorted-array/)|![Easy](https://img.shields.io/badge/-Easy-green)| +|980|[Unique Paths III](https://leetcode.com/problems/unique-paths-iii/)|[Python](./questions/unique-paths-iii/)|![Hard](https://img.shields.io/badge/-Hard-red)| |981|[Time Based Key-Value Store](https://leetcode.com/problems/time-based-key-value-store/)|[Python](./questions/time-based-key-value-store/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |985|[Sum of Even Numbers After Queries](https://leetcode.com/problems/sum-of-even-numbers-after-queries/)|[Python](./questions/sum-of-even-numbers-after-queries/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |986|[Interval List Intersections](https://leetcode.com/problems/interval-list-intersections/)|[Python](./questions/interval-list-intersections/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |987|[Vertical Order Traversal of a Binary Tree](https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/)|[Python](./questions/vertical-order-traversal-of-a-binary-tree/)|![Hard](https://img.shields.io/badge/-Hard-red)| +|989|[Add to Array-Form of Integer](https://leetcode.com/problems/add-to-array-form-of-integer/)|[Python](./questions/add-to-array-form-of-integer/)|![Easy](https://img.shields.io/badge/-Easy-green)| |991|[Broken Calculator](https://leetcode.com/problems/broken-calculator/)|[Python](./questions/broken-calculator/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |993|[Cousins in Binary Tree](https://leetcode.com/problems/cousins-in-binary-tree/)|[Python](./questions/cousins-in-binary-tree/)|![Easy](https://img.shields.io/badge/-Easy-green)| |997|[Find the Town Judge](https://leetcode.com/problems/find-the-town-judge/)|[Python](./questions/find-the-town-judge/)|![Easy](https://img.shields.io/badge/-Easy-green)| |999|[Available Captures for Rook](https://leetcode.com/problems/available-captures-for-rook/)|[Python](./questions/available-captures-for-rook/)|![Easy](https://img.shields.io/badge/-Easy-green)| +|1002|[Find Common Characters](https://leetcode.com/problems/find-common-characters/)|[Python](./questions/find-common-characters/)|![Easy](https://img.shields.io/badge/-Easy-green)| |1004|[Max Consecutive Ones III](https://leetcode.com/problems/max-consecutive-ones-iii/)|[Python](./questions/max-consecutive-ones-iii/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |1005|[Maximize Sum Of Array After K Negations](https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/)|[Python](./questions/maximize-sum-of-array-after-k-negations/)|![Easy](https://img.shields.io/badge/-Easy-green)| |1007|[Minimum Domino Rotations For Equal Row](https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/)|[Python](./questions/minimum-domino-rotations-for-equal-row/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |1008|[Construct Binary Search Tree from Preorder Traversal](https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/)|[Python](./questions/construct-binary-search-tree-from-preorder-traversal/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |1009|[Complement of Base 10 Integer](https://leetcode.com/problems/complement-of-base-10-integer/)|[Python](./questions/complement-of-base-10-integer/)|![Easy](https://img.shields.io/badge/-Easy-green)| |1010|[Pairs of Songs With Total Durations Divisible by 60](https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/)|[Python](./questions/pairs-of-songs-with-total-durations-divisible-by-60/)|![Medium](https://img.shields.io/badge/-Medium-orange)| +|1013|[Partition Array Into Three Parts With Equal Sum](https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/)|[Python](./questions/partition-array-into-three-parts-with-equal-sum/)|![Easy](https://img.shields.io/badge/-Easy-green)| |1015|[Smallest Integer Divisible by K](https://leetcode.com/problems/smallest-integer-divisible-by-k/)|[Python](./questions/smallest-integer-divisible-by-k/)|![Medium](https://img.shields.io/badge/-Medium-orange)| +|1018|[Binary Prefix Divisible By 5](https://leetcode.com/problems/binary-prefix-divisible-by-5/)|[Python](./questions/binary-prefix-divisible-by-5/)|![Easy](https://img.shields.io/badge/-Easy-green)| |1019|[Next Greater Node In Linked List](https://leetcode.com/problems/next-greater-node-in-linked-list/)|[Python](./questions/next-greater-node-in-linked-list/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |1021|[Remove Outermost Parentheses](https://leetcode.com/problems/remove-outermost-parentheses/)|[Python](./questions/remove-outermost-parentheses/)|![Easy](https://img.shields.io/badge/-Easy-green)| |1022|[Sum of Root To Leaf Binary Numbers](https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/)|[Python](./questions/sum-of-root-to-leaf-binary-numbers/)|![Easy](https://img.shields.io/badge/-Easy-green)| +|1025|[Divisor Game](https://leetcode.com/problems/divisor-game/)|[Python](./questions/divisor-game/)|![Easy](https://img.shields.io/badge/-Easy-green)| |1026|[Maximum Difference Between Node and Ancestor](https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/)|[Python](./questions/maximum-difference-between-node-and-ancestor/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |1027|[Longest Arithmetic Subsequence](https://leetcode.com/problems/longest-arithmetic-subsequence/)|[Python](./questions/longest-arithmetic-subsequence/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |1029|[Two City Scheduling](https://leetcode.com/problems/two-city-scheduling/)|[Python](./questions/two-city-scheduling/)|![Medium](https://img.shields.io/badge/-Medium-orange)| +|1030|[Matrix Cells in Distance Order](https://leetcode.com/problems/matrix-cells-in-distance-order/)|[Python](./questions/matrix-cells-in-distance-order/)|![Easy](https://img.shields.io/badge/-Easy-green)| |1032|[Stream of Characters](https://leetcode.com/problems/stream-of-characters/)|[Python](./questions/stream-of-characters/)|![Hard](https://img.shields.io/badge/-Hard-red)| |1035|[Uncrossed Lines](https://leetcode.com/problems/uncrossed-lines/)|[Python](./questions/uncrossed-lines/)|![Medium](https://img.shields.io/badge/-Medium-orange)| +|1037|[Valid Boomerang](https://leetcode.com/problems/valid-boomerang/)|[Python](./questions/valid-boomerang/)|![Easy](https://img.shields.io/badge/-Easy-green)| |1044|[Longest Duplicate Substring](https://leetcode.com/problems/longest-duplicate-substring/)|[Python](./questions/longest-duplicate-substring/)|![Hard](https://img.shields.io/badge/-Hard-red)| |1046|[Last Stone Weight](https://leetcode.com/problems/last-stone-weight/)|[Python](./questions/last-stone-weight/)|![Easy](https://img.shields.io/badge/-Easy-green)| |1047|[Remove All Adjacent Duplicates In String](https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/)|[Python](./questions/remove-all-adjacent-duplicates-in-string/)|![Easy](https://img.shields.io/badge/-Easy-green)| |1048|[Longest String Chain](https://leetcode.com/problems/longest-string-chain/)|[Python](./questions/longest-string-chain/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |1049|[Last Stone Weight II](https://leetcode.com/problems/last-stone-weight-ii/)|[Python](./questions/last-stone-weight-ii/)|![Medium](https://img.shields.io/badge/-Medium-orange)| +|1050|[Actors and Directors Who Cooperated At Least Three Times](https://leetcode.com/problems/actors-and-directors-who-cooperated-at-least-three-times/)|[SQL](./questions/actors-and-directors-who-cooperated-at-least-three-times/)|![Easy](https://img.shields.io/badge/-Easy-green)| +|1051|[Height Checker](https://leetcode.com/problems/height-checker/)|[Python](./questions/height-checker/)|![Easy](https://img.shields.io/badge/-Easy-green)| |1055|[Shortest Way to Form String](https://leetcode.com/problems/shortest-way-to-form-string/)|[Python](./questions/shortest-way-to-form-string/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |1057|[Campus Bikes](https://leetcode.com/problems/campus-bikes/)|[Python](./questions/campus-bikes/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |1064|[Fixed Point](https://leetcode.com/problems/fixed-point/)|[Python](./questions/fixed-point/)|![Easy](https://img.shields.io/badge/-Easy-green)| |1066|[Campus Bikes II](https://leetcode.com/problems/campus-bikes-ii/)|[Python](./questions/campus-bikes-ii/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |1071|[Greatest Common Divisor of Strings](https://leetcode.com/problems/greatest-common-divisor-of-strings/)|[Python](./questions/greatest-common-divisor-of-strings/)|![Easy](https://img.shields.io/badge/-Easy-green)| |1074|[Number of Submatrices That Sum to Target](https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/)|[Python](./questions/number-of-submatrices-that-sum-to-target/)|![Hard](https://img.shields.io/badge/-Hard-red)| +|1078|[Occurrences After Bigram](https://leetcode.com/problems/occurrences-after-bigram/)|[Python](./questions/occurrences-after-bigram/)|![Easy](https://img.shields.io/badge/-Easy-green)| |1081|[Smallest Subsequence of Distinct Characters](https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/)|[Python](./questions/smallest-subsequence-of-distinct-characters/)|![Medium](https://img.shields.io/badge/-Medium-orange)| +|1084|[Sales Analysis III](https://leetcode.com/problems/sales-analysis-iii/)|[SQL](./questions/sales-analysis-iii/)|![Easy](https://img.shields.io/badge/-Easy-green)| +|1089|[Duplicate Zeros](https://leetcode.com/problems/duplicate-zeros/)|[Python](./questions/duplicate-zeros/)|![Easy](https://img.shields.io/badge/-Easy-green)| |1091|[Shortest Path in Binary Matrix](https://leetcode.com/problems/shortest-path-in-binary-matrix/)|[Python](./questions/shortest-path-in-binary-matrix/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |1094|[Car Pooling](https://leetcode.com/problems/car-pooling/)|[Python](./questions/car-pooling/)|![Medium](https://img.shields.io/badge/-Medium-orange)| +|1103|[Distribute Candies to People](https://leetcode.com/problems/distribute-candies-to-people/)|[Python](./questions/distribute-candies-to-people/)|![Easy](https://img.shields.io/badge/-Easy-green)| +|1108|[Defanging an IP Address](https://leetcode.com/problems/defanging-an-ip-address/)|[Python](./questions/defanging-an-ip-address/)|![Easy](https://img.shields.io/badge/-Easy-green)| +|1114|[Print in Order](https://leetcode.com/problems/print-in-order/)|[Python](./questions/print-in-order/)|![Easy](https://img.shields.io/badge/-Easy-green)| +|1122|[Relative Sort Array](https://leetcode.com/problems/relative-sort-array/)|[Python](./questions/relative-sort-array/)|![Easy](https://img.shields.io/badge/-Easy-green)| |1123|[Lowest Common Ancestor of Deepest Leaves](https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/)|[Python](./questions/lowest-common-ancestor-of-deepest-leaves/)|![Medium](https://img.shields.io/badge/-Medium-orange)| +|1128|[Number of Equivalent Domino Pairs](https://leetcode.com/problems/number-of-equivalent-domino-pairs/)|[Python](./questions/number-of-equivalent-domino-pairs/)|![Easy](https://img.shields.io/badge/-Easy-green)| +|1137|[N-th Tribonacci Number](https://leetcode.com/problems/n-th-tribonacci-number/)|[Python](./questions/n-th-tribonacci-number/)|![Easy](https://img.shields.io/badge/-Easy-green)| +|1141|[User Activity for the Past 30 Days I](https://leetcode.com/problems/user-activity-for-the-past-30-days-i/)|[SQL](./questions/user-activity-for-the-past-30-days-i/)|![Easy](https://img.shields.io/badge/-Easy-green)| |1143|[Longest Common Subsequence](https://leetcode.com/problems/longest-common-subsequence/)|[Python](./questions/longest-common-subsequence/)|![Medium](https://img.shields.io/badge/-Medium-orange)| +|1148|[Article Views I](https://leetcode.com/problems/article-views-i/)|[SQL](./questions/article-views-i/)|![Easy](https://img.shields.io/badge/-Easy-green)| +|1154|[Day of the Year](https://leetcode.com/problems/day-of-the-year/)|[Python](./questions/day-of-the-year/)|![Easy](https://img.shields.io/badge/-Easy-green)| |1155|[Number of Dice Rolls With Target Sum](https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/)|[Python](./questions/number-of-dice-rolls-with-target-sum/)|![Medium](https://img.shields.io/badge/-Medium-orange)| +|1160|[Find Words That Can Be Formed by Characters](https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/)|[Python](./questions/find-words-that-can-be-formed-by-characters/)|![Easy](https://img.shields.io/badge/-Easy-green)| |1178|[Number of Valid Words for Each Puzzle](https://leetcode.com/problems/number-of-valid-words-for-each-puzzle/)|[Python](./questions/number-of-valid-words-for-each-puzzle/)|![Hard](https://img.shields.io/badge/-Hard-red)| +|1179|[Reformat Department Table](https://leetcode.com/problems/reformat-department-table/)|[](./questions/reformat-department-table/)|![Easy](https://img.shields.io/badge/-Easy-green)| +|1184|[Distance Between Bus Stops](https://leetcode.com/problems/distance-between-bus-stops/)|[Python](./questions/distance-between-bus-stops/)|![Easy](https://img.shields.io/badge/-Easy-green)| +|1185|[Day of the Week](https://leetcode.com/problems/day-of-the-week/)|[Python](./questions/day-of-the-week/)|![Easy](https://img.shields.io/badge/-Easy-green)| +|1189|[Maximum Number of Balloons](https://leetcode.com/problems/maximum-number-of-balloons/)|[Python](./questions/maximum-number-of-balloons/)|![Easy](https://img.shields.io/badge/-Easy-green)| |1192|[Critical Connections in a Network](https://leetcode.com/problems/critical-connections-in-a-network/)|[Python](./questions/critical-connections-in-a-network/)|![Hard](https://img.shields.io/badge/-Hard-red)| +|1200|[Minimum Absolute Difference](https://leetcode.com/problems/minimum-absolute-difference/)|[Python](./questions/minimum-absolute-difference/)|![Easy](https://img.shields.io/badge/-Easy-green)| |1202|[Smallest String With Swaps](https://leetcode.com/problems/smallest-string-with-swaps/)|[Python](./questions/smallest-string-with-swaps/)|![Medium](https://img.shields.io/badge/-Medium-orange)| +|1207|[Unique Number of Occurrences](https://leetcode.com/problems/unique-number-of-occurrences/)|[Python](./questions/unique-number-of-occurrences/)|![Easy](https://img.shields.io/badge/-Easy-green)| |1209|[Remove All Adjacent Duplicates in String II](https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/)|[Python](./questions/remove-all-adjacent-duplicates-in-string-ii/)|![Medium](https://img.shields.io/badge/-Medium-orange)| +|1217|[Minimum Cost to Move Chips to The Same Position](https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/)|[Python](./questions/minimum-cost-to-move-chips-to-the-same-position/)|![Easy](https://img.shields.io/badge/-Easy-green)| |1220|[Count Vowels Permutation](https://leetcode.com/problems/count-vowels-permutation/)|[Python](./questions/count-vowels-permutation/)|![Hard](https://img.shields.io/badge/-Hard-red)| +|1221|[Split a String in Balanced Strings](https://leetcode.com/problems/split-a-string-in-balanced-strings/)|[Python](./questions/split-a-string-in-balanced-strings/)|![Easy](https://img.shields.io/badge/-Easy-green)| |1232|[Check If It Is a Straight Line](https://leetcode.com/problems/check-if-it-is-a-straight-line/)|[Python](./questions/check-if-it-is-a-straight-line/)|![Easy](https://img.shields.io/badge/-Easy-green)| +|1235|[Maximum Profit in Job Scheduling](https://leetcode.com/problems/maximum-profit-in-job-scheduling/)|[Python](./questions/maximum-profit-in-job-scheduling/)|![Hard](https://img.shields.io/badge/-Hard-red)| |1249|[Minimum Remove to Make Valid Parentheses](https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/)|[Python](./questions/minimum-remove-to-make-valid-parentheses/)|![Medium](https://img.shields.io/badge/-Medium-orange)| +|1252|[Cells with Odd Values in a Matrix](https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/)|[Python](./questions/cells-with-odd-values-in-a-matrix/)|![Easy](https://img.shields.io/badge/-Easy-green)| +|1260|[Shift 2D Grid](https://leetcode.com/problems/shift-2d-grid/)|[Python](./questions/shift-2d-grid/)|![Easy](https://img.shields.io/badge/-Easy-green)| +|1266|[Minimum Time Visiting All Points](https://leetcode.com/problems/minimum-time-visiting-all-points/)|[Python](./questions/minimum-time-visiting-all-points/)|![Easy](https://img.shields.io/badge/-Easy-green)| |1268|[Search Suggestions System](https://leetcode.com/problems/search-suggestions-system/)|[Python](./questions/search-suggestions-system/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |1277|[Count Square Submatrices with All Ones](https://leetcode.com/problems/count-square-submatrices-with-all-ones/)|[Python](./questions/count-square-submatrices-with-all-ones/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |1283|[Find the Smallest Divisor Given a Threshold](https://leetcode.com/problems/find-the-smallest-divisor-given-a-threshold/)|[Python](./questions/find-the-smallest-divisor-given-a-threshold/)|![Medium](https://img.shields.io/badge/-Medium-orange)| @@ -712,6 +760,7 @@ LeetCode is a very good website to sharpen your programming/problem-solving skil |1332|[Remove Palindromic Subsequences](https://leetcode.com/problems/remove-palindromic-subsequences/)|[Python](./questions/remove-palindromic-subsequences/)|![Easy](https://img.shields.io/badge/-Easy-green)| |1337|[The K Weakest Rows in a Matrix](https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/)|[Python](./questions/the-k-weakest-rows-in-a-matrix/)|![Easy](https://img.shields.io/badge/-Easy-green)| |1338|[Reduce Array Size to The Half](https://leetcode.com/problems/reduce-array-size-to-the-half/)|[Python](./questions/reduce-array-size-to-the-half/)|![Medium](https://img.shields.io/badge/-Medium-orange)| +|1339|[Maximum Product of Splitted Binary Tree](https://leetcode.com/problems/maximum-product-of-splitted-binary-tree/)|[Python](./questions/maximum-product-of-splitted-binary-tree/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |1342|[Number of Steps to Reduce a Number to Zero](https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/)|[Python](./questions/number-of-steps-to-reduce-a-number-to-zero/)|![Easy](https://img.shields.io/badge/-Easy-green)| |1344|[Angle Between Hands of a Clock](https://leetcode.com/problems/angle-between-hands-of-a-clock/)|[Python](./questions/angle-between-hands-of-a-clock/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |1345|[Jump Game IV](https://leetcode.com/problems/jump-game-iv/)|[Python](./questions/jump-game-iv/)|![Hard](https://img.shields.io/badge/-Hard-red)| @@ -743,6 +792,7 @@ LeetCode is a very good website to sharpen your programming/problem-solving skil |1640|[Check Array Formation Through Concatenation](https://leetcode.com/problems/check-array-formation-through-concatenation/)|[Python](./questions/check-array-formation-through-concatenation/)|![Easy](https://img.shields.io/badge/-Easy-green)| |1641|[Count Sorted Vowel Strings](https://leetcode.com/problems/count-sorted-vowel-strings/)|[Python](./questions/count-sorted-vowel-strings/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |1642|[Furthest Building You Can Reach](https://leetcode.com/problems/furthest-building-you-can-reach/)|[Python](./questions/furthest-building-you-can-reach/)|![Medium](https://img.shields.io/badge/-Medium-orange)| +|1657|[Determine if Two Strings Are Close](https://leetcode.com/problems/determine-if-two-strings-are-close/)|[Python](./questions/determine-if-two-strings-are-close/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |1662|[Check If Two String Arrays are Equivalent](https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/)|[Python](./questions/check-if-two-string-arrays-are-equivalent/)|![Easy](https://img.shields.io/badge/-Easy-green)| |1663|[Smallest String With A Given Numeric Value](https://leetcode.com/problems/smallest-string-with-a-given-numeric-value/)|[Python](./questions/smallest-string-with-a-given-numeric-value/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |1675|[Minimize Deviation in Array](https://leetcode.com/problems/minimize-deviation-in-array/)|[Python](./questions/minimize-deviation-in-array/)|![Hard](https://img.shields.io/badge/-Hard-red)| @@ -755,6 +805,10 @@ LeetCode is a very good website to sharpen your programming/problem-solving skil |1706|[Where Will the Ball Fall](https://leetcode.com/problems/where-will-the-ball-fall/)|[Python](./questions/where-will-the-ball-fall/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |1710|[Maximum Units on a Truck](https://leetcode.com/problems/maximum-units-on-a-truck/)|[Python](./questions/maximum-units-on-a-truck/)|![Easy](https://img.shields.io/badge/-Easy-green)| |1721|[Swapping Nodes in a Linked List](https://leetcode.com/problems/swapping-nodes-in-a-linked-list/)|[Python](./questions/swapping-nodes-in-a-linked-list/)|![Medium](https://img.shields.io/badge/-Medium-orange)| +|1834|[Single-Threaded CPU](https://leetcode.com/problems/single-threaded-cpu/)|[Python](./questions/single-threaded-cpu/)|![Medium](https://img.shields.io/badge/-Medium-orange)| +|1926|[Nearest Exit from Entrance in Maze](https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/)|[Python](./questions/nearest-exit-from-entrance-in-maze/)|![Medium](https://img.shields.io/badge/-Medium-orange)| +|1962|[Remove Stones to Minimize the Total](https://leetcode.com/problems/remove-stones-to-minimize-the-total/)|[Python](./questions/remove-stones-to-minimize-the-total/)|![Medium](https://img.shields.io/badge/-Medium-orange)| +|1971|[Find if Path Exists in Graph](https://leetcode.com/problems/find-if-path-exists-in-graph/)|[Python](./questions/find-if-path-exists-in-graph/)|![Easy](https://img.shields.io/badge/-Easy-green)| |1996|[The Number of Weak Characters in the Game](https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/)|[Python](./questions/the-number-of-weak-characters-in-the-game/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |2007|[Find Original Array From Doubled Array](https://leetcode.com/problems/find-original-array-from-doubled-array/)|[Python](./questions/find-original-array-from-doubled-array/)|![Medium](https://img.shields.io/badge/-Medium-orange)| |2154|[Keep Multiplying Found Values by Two](https://leetcode.com/problems/keep-multiplying-found-values-by-two/)|[Python](./questions/keep-multiplying-found-values-by-two/)|![Easy](https://img.shields.io/badge/-Easy-green)| @@ -764,6 +818,10 @@ LeetCode is a very good website to sharpen your programming/problem-solving skil |2176|[Count Equal and Divisible Pairs in an Array](https://leetcode.com/problems/count-equal-and-divisible-pairs-in-an-array/)|[Python](./questions/count-equal-and-divisible-pairs-in-an-array/)|![Easy](https://img.shields.io/badge/-Easy-green)| |2180|[Count Integers With Even Digit Sum](https://leetcode.com/problems/count-integers-with-even-digit-sum/)|[Python](./questions/count-integers-with-even-digit-sum/)|![Easy](https://img.shields.io/badge/-Easy-green)| |2185|[Counting Words With a Given Prefix](https://leetcode.com/problems/counting-words-with-a-given-prefix/)|[Python](./questions/counting-words-with-a-given-prefix/)|![Easy](https://img.shields.io/badge/-Easy-green)| +|2225|[Find Players With Zero or One Losses](https://leetcode.com/problems/find-players-with-zero-or-one-losses/)|[Python](./questions/find-players-with-zero-or-one-losses/)|![Medium](https://img.shields.io/badge/-Medium-orange)| +|2256|[Minimum Average Difference](https://leetcode.com/problems/minimum-average-difference/)|[Python](./questions/minimum-average-difference/)|![Medium](https://img.shields.io/badge/-Medium-orange)| +|2279|[Maximum Bags With Full Capacity of Rocks](https://leetcode.com/problems/maximum-bags-with-full-capacity-of-rocks/)|[Python](./questions/maximum-bags-with-full-capacity-of-rocks/)|![Medium](https://img.shields.io/badge/-Medium-orange)| +|2389|[Longest Subsequence With Limited Sum](https://leetcode.com/problems/longest-subsequence-with-limited-sum/)|[Python](./questions/longest-subsequence-with-limited-sum/)|![Easy](https://img.shields.io/badge/-Easy-green)| ### Features diff --git a/download_solutions.py b/download_solutions.py index db5041c..8c90eb5 100644 --- a/download_solutions.py +++ b/download_solutions.py @@ -16,6 +16,7 @@ 'python3': 'py', 'java': 'java', 'sql': 'sql', + 'mysql': 'sql', 'shell': 'sh', } lang_name_mapping = { @@ -23,6 +24,7 @@ 'py': 'Python', 'java': 'Java', 'sql': 'SQL', + 'mysql': 'SQL', 'sh': 'Shell', } comment_mapping = { @@ -31,6 +33,7 @@ 'python3': ['"""', '"""'], 'java': ['/*', '*/'], 'sql': ['/*', '*/'], + 'mysql': ['/*', '*/'], 'shell': [": '", "'"], } diff_mapping = { @@ -47,7 +50,6 @@ class ParseReadmeState(Enum): cookie = '' - def get_question_meta(session): res = session.get('https://leetcode.com/api/problems/all/') total = res.json()['stat_status_pairs'] @@ -70,16 +72,15 @@ def get_question(session, question_meta): def get_solution(session, question_meta): res = session.post('https://leetcode.com/graphql', json={ - "operationName": "Submissions", + "query": "\n query submissionList($offset: Int!, $limit: Int!, $lastKey: String, $questionSlug: String!, $lang: Int, $status: Int) {\n questionSubmissionList(\n offset: $offset\n limit: $limit\n lastKey: $lastKey\n questionSlug: $questionSlug\n lang: $lang\n status: $status\n ) {\n lastKey\n hasNext\n submissions {\n id\n title\n titleSlug\n status\n statusDisplay\n lang\n langName\n runtime\n timestamp\n url\n isPending\n memory\n hasNotes\n }\n }\n}\n ", "variables": { + "questionSlug": question_meta['stat']['question__title_slug'], "offset": 0, "limit": 20, "lastKey": None, - "questionSlug": question_meta['stat']['question__title_slug'] - }, - "query": "query Submissions($offset: Int!, $limit: Int!, $lastKey: String, $questionSlug: String!) {\n submissionList(offset: $offset, limit: $limit, lastKey: $lastKey, questionSlug: $questionSlug) {\n lastKey\n hasNext\n submissions {\n id\n statusDisplay\n lang\n runtime\n timestamp\n url\n isPending\n memory\n __typename\n }\n __typename\n }\n}\n" + } }) - submissions = res.json()['data']['submissionList']['submissions'] + submissions = res.json()['data']['questionSubmissionList']['submissions'] selected = None lang = None for submission in submissions: @@ -89,20 +90,16 @@ def get_solution(session, question_meta): selected = submission break if selected is None: + print('no AC solution found: ', question_meta['stat']['question__title']) return None - res = session.get('https://leetcode.com{}'.format(selected['url'])) - code_line = '' - for line in res.text.split('\n'): - if 'submissionCode:' in line: - code_line = line - break - match = re.search("submissionCode: '(.+)'", code_line) - if match is None: - print('cannot find solution: ', question_meta['stat']['question__title']) - return None, None - code_line = match.group(1) - code_line = code_line.encode('utf-8').decode('unicode-escape') - return code_line, lang + res = session.post('https://leetcode.com/graphql', json={ + "query": "\n query submissionDetails($submissionId: Int!) {\n submissionDetails(submissionId: $submissionId) {\n runtime\n runtimeDisplay\n runtimePercentile\n runtimeDistribution\n memory\n memoryDisplay\n memoryPercentile\n memoryDistribution\n code\n timestamp\n statusCode\n user {\n username\n profile {\n realName\n userAvatar\n }\n }\n lang {\n name\n verboseName\n }\n question {\n questionId\n }\n notes\n topicTags {\n tagId\n slug\n name\n }\n runtimeError\n compileError\n lastTestcase\n }\n}\n ", + "variables": { + "submissionId": selected['id'], + }, + }) + submission_details = res.json()['data']['submissionDetails'] + return submission_details['code'], lang def get_solution_dir(question_meta): diff --git a/questions/actors-and-directors-who-cooperated-at-least-three-times/Solution.sql b/questions/actors-and-directors-who-cooperated-at-least-three-times/Solution.sql new file mode 100644 index 0000000..fe81cde --- /dev/null +++ b/questions/actors-and-directors-who-cooperated-at-least-three-times/Solution.sql @@ -0,0 +1,47 @@ +/* + +Table: ActorDirector + ++-------------+---------+ +| Column Name | Type | ++-------------+---------+ +| actor_id | int | +| director_id | int | +| timestamp | int | ++-------------+---------+ +timestamp is the primary key column for this table. + +  +Write a SQL query for a report that provides the pairs (actor_id, director_id) where the actor has cooperated with the director at least three times. +Return the result table in any order. +The query result format is in the following example. +  +Example 1: + +Input: +ActorDirector table: ++-------------+-------------+-------------+ +| actor_id | director_id | timestamp | ++-------------+-------------+-------------+ +| 1 | 1 | 0 | +| 1 | 1 | 1 | +| 1 | 1 | 2 | +| 1 | 2 | 3 | +| 1 | 2 | 4 | +| 2 | 1 | 5 | +| 2 | 1 | 6 | ++-------------+-------------+-------------+ +Output: ++-------------+-------------+ +| actor_id | director_id | ++-------------+-------------+ +| 1 | 1 | ++-------------+-------------+ +Explanation: The only pair is (1, 1) where they cooperated exactly 3 times. + + +*/ + + +# Write your MySQL query statement below +select actor_id, director_id from ActorDirector group by actor_id, director_id having count(1) >= 3 \ No newline at end of file diff --git a/questions/add-to-array-form-of-integer/Solution.py b/questions/add-to-array-form-of-integer/Solution.py new file mode 100644 index 0000000..4605e05 --- /dev/null +++ b/questions/add-to-array-form-of-integer/Solution.py @@ -0,0 +1,58 @@ +""" + +The array-form of an integer num is an array representing its digits in left to right order. + +For example, for num = 1321, the array form is [1,3,2,1]. + +Given num, the array-form of an integer, and an integer k, return the array-form of the integer num + k. +  +Example 1: + +Input: num = [1,2,0,0], k = 34 +Output: [1,2,3,4] +Explanation: 1200 + 34 = 1234 + +Example 2: + +Input: num = [2,7,4], k = 181 +Output: [4,5,5] +Explanation: 274 + 181 = 455 + +Example 3: + +Input: num = [2,1,5], k = 806 +Output: [1,0,2,1] +Explanation: 215 + 806 = 1021 + +  +Constraints: + +1 <= num.length <= 104 +0 <= num[i] <= 9 +num does not contain any leading zeros except for the zero itself. +1 <= k <= 104 + + +""" + + +class Solution: + def addToArrayForm(self, num: List[int], k: int) -> List[int]: + def int_to_arr(val): + ret = [] + while val > 0: + val, c = divmod(val, 10) + ret.append(c) + return ret[::-1] + + def add_arrs(arr1, arr2): + ret = [] + carry = 0 + for a, b in itertools.zip_longest(reversed(arr1), reversed(arr2), fillvalue=0): + carry, c = divmod(a + b + carry, 10) + ret.append(c) + if carry != 0: + ret.append(carry) + return ret[::-1] + + return add_arrs(num, int_to_arr(k)) \ No newline at end of file diff --git a/questions/arithmetic-slices-ii-subsequence/Solution.py b/questions/arithmetic-slices-ii-subsequence/Solution.py new file mode 100644 index 0000000..e9d2b31 --- /dev/null +++ b/questions/arithmetic-slices-ii-subsequence/Solution.py @@ -0,0 +1,60 @@ +""" + +Given an integer array nums, return the number of all the arithmetic subsequences of nums. +A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. + +For example, [1, 3, 5, 7, 9], [7, 7, 7, 7], and [3, -1, -5, -9] are arithmetic sequences. +For example, [1, 1, 2, 5, 7] is not an arithmetic sequence. + +A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array. + +For example, [2,5,10] is a subsequence of [1,2,1,2,4,1,5,10]. + +The test cases are generated so that the answer fits in 32-bit integer. +  +Example 1: + +Input: nums = [2,4,6,8,10] +Output: 7 +Explanation: All arithmetic subsequence slices are: +[2,4,6] +[4,6,8] +[6,8,10] +[2,4,6,8] +[4,6,8,10] +[2,4,6,8,10] +[2,6,10] + +Example 2: + +Input: nums = [7,7,7,7,7] +Output: 16 +Explanation: Any subsequence of this array is arithmetic. + +  +Constraints: + +1  <= nums.length <= 1000 +-231 <= nums[i] <= 231 - 1 + + +""" + + +class Solution: + def numberOfArithmeticSlices(self, nums: List[int]) -> int: + # use defaultdict(int) to easily get the difference in arithmetic subsequences ending with ```j``` + dp = [defaultdict(int) for _ in range(len(nums))] + res = 0 + for i in range(len(nums)): + for j in range(i): + + # We are looking for the number of elements before j in the arithmetic subsequence that has nums[j]-nums[i] as difference. + dif = nums[j]-nums[i] + + # Simply add it to the result. + res += dp[j][dif] + + # Increase the number of elements in arithmetic subsequence at i with this dif. + dp[i][dif] += dp[j][dif]+1 + return res \ No newline at end of file diff --git a/questions/article-views-i/Solution.sql b/questions/article-views-i/Solution.sql new file mode 100644 index 0000000..e0c71c0 --- /dev/null +++ b/questions/article-views-i/Solution.sql @@ -0,0 +1,50 @@ +/* + +Table: Views + ++---------------+---------+ +| Column Name | Type | ++---------------+---------+ +| article_id | int | +| author_id | int | +| viewer_id | int | +| view_date | date | ++---------------+---------+ +There is no primary key for this table, it may have duplicate rows. +Each row of this table indicates that some viewer viewed an article (written by some author) on some date. +Note that equal author_id and viewer_id indicate the same person. + +  +Write an SQL query to find all the authors that viewed at least one of their own articles. +Return the result table sorted by id in ascending order. +The query result format is in the following example. +  +Example 1: + +Input: +Views table: ++------------+-----------+-----------+------------+ +| article_id | author_id | viewer_id | view_date | ++------------+-----------+-----------+------------+ +| 1 | 3 | 5 | 2019-08-01 | +| 1 | 3 | 6 | 2019-08-02 | +| 2 | 7 | 7 | 2019-08-01 | +| 2 | 7 | 6 | 2019-08-02 | +| 4 | 7 | 1 | 2019-07-22 | +| 3 | 4 | 4 | 2019-07-21 | +| 3 | 4 | 4 | 2019-07-21 | ++------------+-----------+-----------+------------+ +Output: ++------+ +| id | ++------+ +| 4 | +| 7 | ++------+ + + +*/ + + +# Write your MySQL query statement below +select distinct(author_id) as id from Views where author_id = viewer_id order by author_id asc; \ No newline at end of file diff --git a/questions/basic-calculator/Solution.py b/questions/basic-calculator/Solution.py new file mode 100644 index 0000000..b4f0856 --- /dev/null +++ b/questions/basic-calculator/Solution.py @@ -0,0 +1,90 @@ +""" + +Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation. +Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval(). +  +Example 1: + +Input: s = "1 + 1" +Output: 2 + +Example 2: + +Input: s = " 2-1 + 2 " +Output: 3 + +Example 3: + +Input: s = "(1+(4+5+2)-3)+(6+8)" +Output: 23 + +  +Constraints: + +1 <= s.length <= 3 * 105 +s consists of digits, '+', '-', '(', ')', and ' '. +s represents a valid expression. +'+' is not used as a unary operation (i.e., "+1" and "+(2 + 3)" is invalid). +'-' could be used as a unary operation (i.e., "-1" and "-(2 + 3)" is valid). +There will be no two consecutive operators in the input. +Every number and running calculation will fit in a signed 32-bit integer. + + +""" + + +class Solution: + def calculate(self, s: str) -> int: + + ### num is the current number we are constructing + + ### sign is the '+' or '-' before the current number we are constructing/holding + ### Note that we initialize sign with 1 to represent '+' + + ### The last element in the stack will be the number we are updating during the + ### process, so put a 0 in it. + num, sign, stack = 0, 1, [0] + + for c in s: + + ### Constructing the number. + if c.isdigit(): + num = num*10 + int(c) + + ### Skip the space + elif c==' ': + continue + + ### When we see '+', we need to multiply the current number we are holding with the + ### sign before this number, and update the last element in the stack. + ### We also need to reset num to 0 and sign to 1 + elif c == '+': + stack[-1] += num * sign + sign = 1 + num = 0 + + ### Doing the same thing as '+', but reset sign to -1 + elif c == '-': + stack[-1] += num * sign + sign = -1 + num = 0 + + ### We add sign to stack which represent the sign of this () + ### We also add a 0 so we can keep update while evaluating the expression inside this () + ### Reset num and sign again + elif c == '(': + stack.extend([sign,0]) + sign = 1 + num = 0 + + ### pop the last element and combine it with the current num and sign we are holding (the last element inside this '()' ). + ### pop the last element again which is the sign for this '()' and muitiply them together. + ### add everything we get inside this '()' to the last element in the stack. + elif c == ')': + lastNum = (stack.pop() + num*sign) * stack.pop() + stack[-1] += lastNum + sign = 1 + num = 0 + + ### stack should only contain one element representing everything except the last number if the expression ended with a number, so add the current num we are holding to the result. + return stack[-1]+num*sign \ No newline at end of file diff --git a/questions/binary-prefix-divisible-by-5/Solution.py b/questions/binary-prefix-divisible-by-5/Solution.py new file mode 100644 index 0000000..ec9bc49 --- /dev/null +++ b/questions/binary-prefix-divisible-by-5/Solution.py @@ -0,0 +1,41 @@ +""" + +You are given a binary array nums (0-indexed). +We define xi as the number whose binary representation is the subarray nums[0..i] (from most-significant-bit to least-significant-bit). + +For example, if nums = [1,0,1], then x0 = 1, x1 = 2, and x2 = 5. + +Return an array of booleans answer where answer[i] is true if xi is divisible by 5. +  +Example 1: + +Input: nums = [0,1,1] +Output: [true,false,false] +Explanation: The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10. +Only the first number is divisible by 5, so answer[0] is true. + +Example 2: + +Input: nums = [1,1,1] +Output: [false,false,false] + +  +Constraints: + +1 <= nums.length <= 105 +nums[i] is either 0 or 1. + + +""" + + +class Solution: + def prefixesDivBy5(self, nums: List[int]) -> List[bool]: + remainder = 0 + ret = [] + for n in nums: + c = remainder * 2 + n + _, remainder = divmod(c, 5) + ret.append(remainder == 0) + return ret + \ No newline at end of file diff --git a/questions/cells-with-odd-values-in-a-matrix/Solution.py b/questions/cells-with-odd-values-in-a-matrix/Solution.py new file mode 100644 index 0000000..de78f39 --- /dev/null +++ b/questions/cells-with-odd-values-in-a-matrix/Solution.py @@ -0,0 +1,55 @@ +""" + +There is an m x n matrix that is initialized to all 0's. There is also a 2D array indices where each indices[i] = [ri, ci] represents a 0-indexed location to perform some increment operations on the matrix. +For each location indices[i], do both of the following: + +Increment all the cells on row ri. +Increment all the cells on column ci. + +Given m, n, and indices, return the number of odd-valued cells in the matrix after applying the increment to all locations in indices. +  +Example 1: + + +Input: m = 2, n = 3, indices = [[0,1],[1,1]] +Output: 6 +Explanation: Initial matrix = [[0,0,0],[0,0,0]]. +After applying first increment it becomes [[1,2,1],[0,1,0]]. +The final matrix is [[1,3,1],[1,3,1]], which contains 6 odd numbers. + +Example 2: + + +Input: m = 2, n = 2, indices = [[1,1],[0,0]] +Output: 0 +Explanation: Final matrix = [[2,2],[2,2]]. There are no odd numbers in the final matrix. + +  +Constraints: + +1 <= m, n <= 50 +1 <= indices.length <= 100 +0 <= ri < m +0 <= ci < n + +  +Follow up: Could you solve this in O(n + m + indices.length) time with only O(n + m) extra space? + +""" + + +class Solution: + def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int: + matrix = [[0 for _ in range(n)] for _ in range(m)] + for ri, ci in indices: + for idx in range(n): + matrix[ri][idx] += 1 + for idx in range(m): + matrix[idx][ci] += 1 + ret = 0 + for row in matrix: + for elem in row: + if elem & 1 != 0: + ret += 1 + return ret + \ No newline at end of file diff --git a/questions/customer-placing-the-largest-number-of-orders/Solution.sql b/questions/customer-placing-the-largest-number-of-orders/Solution.sql new file mode 100644 index 0000000..69190b5 --- /dev/null +++ b/questions/customer-placing-the-largest-number-of-orders/Solution.sql @@ -0,0 +1,52 @@ +/* + +Table: Orders + ++-----------------+----------+ +| Column Name | Type | ++-----------------+----------+ +| order_number | int | +| customer_number | int | ++-----------------+----------+ +order_number is the primary key for this table. +This table contains information about the order ID and the customer ID. + +  +Write an SQL query to find the customer_number for the customer who has placed the largest number of orders. +The test cases are generated so that exactly one customer will have placed more orders than any other customer. +The query result format is in the following example. +  +Example 1: + +Input: +Orders table: ++--------------+-----------------+ +| order_number | customer_number | ++--------------+-----------------+ +| 1 | 1 | +| 2 | 2 | +| 3 | 3 | +| 4 | 3 | ++--------------+-----------------+ +Output: ++-----------------+ +| customer_number | ++-----------------+ +| 3 | ++-----------------+ +Explanation: +The customer with number 3 has two orders, which is greater than either customer 1 or 2 because each of them only has one order. +So the result is customer_number 3. + +  +Follow up: What if more than one customer has the largest number of orders, can you find all the customer_number in this case? + +*/ + + +# Write your MySQL query statement below +select customer_number from Orders group by customer_number having count(order_number) = ( + select max(cnt) from ( + select count(order_number) as cnt from Orders group by customer_number + ) as cnts +); diff --git a/questions/day-of-the-week/Solution.py b/questions/day-of-the-week/Solution.py new file mode 100644 index 0000000..ada2a7e --- /dev/null +++ b/questions/day-of-the-week/Solution.py @@ -0,0 +1,34 @@ +""" + +Given a date, return the corresponding day of the week for that date. +The input is given as three integers representing the day, month and year respectively. +Return the answer as one of the following values {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}. +  +Example 1: + +Input: day = 31, month = 8, year = 2019 +Output: "Saturday" + +Example 2: + +Input: day = 18, month = 7, year = 1999 +Output: "Sunday" + +Example 3: + +Input: day = 15, month = 8, year = 1993 +Output: "Sunday" + +  +Constraints: + +The given dates are valid dates between the years 1971 and 2100. + + +""" + + +class Solution: + def dayOfTheWeek(self, day: int, month: int, year: int) -> str: + return datetime.datetime(year, month, day).strftime('%A') + \ No newline at end of file diff --git a/questions/day-of-the-year/Solution.py b/questions/day-of-the-year/Solution.py new file mode 100644 index 0000000..4eb57f0 --- /dev/null +++ b/questions/day-of-the-year/Solution.py @@ -0,0 +1,32 @@ +""" + +Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year. +  +Example 1: + +Input: date = "2019-01-09" +Output: 9 +Explanation: Given date is the 9th day of the year in 2019. + +Example 2: + +Input: date = "2019-02-10" +Output: 41 + +  +Constraints: + +date.length == 10 +date[4] == date[7] == '-', and all other date[i]'s are digits +date represents a calendar date between Jan 1st, 1900 and Dec 31th, 2019. + + +""" + + +from datetime import datetime + +class Solution: + def dayOfYear(self, date: str) -> int: + dt = datetime.strptime(date, '%Y-%m-%d') + return dt.timetuple().tm_yday diff --git a/questions/defanging-an-ip-address/Solution.py b/questions/defanging-an-ip-address/Solution.py new file mode 100644 index 0000000..282a741 --- /dev/null +++ b/questions/defanging-an-ip-address/Solution.py @@ -0,0 +1,23 @@ +""" + +Given a valid (IPv4) IP address, return a defanged version of that IP address. +A defanged IP address replaces every period "." with "[.]". +  +Example 1: +Input: address = "1.1.1.1" +Output: "1[.]1[.]1[.]1" +Example 2: +Input: address = "255.100.50.0" +Output: "255[.]100[.]50[.]0" + +  +Constraints: + +The given address is a valid IPv4 address. + +""" + + +class Solution: + def defangIPaddr(self, address: str) -> str: + return '[.]'.join(address.split('.')) \ No newline at end of file diff --git a/questions/delete-columns-to-make-sorted/Solution.py b/questions/delete-columns-to-make-sorted/Solution.py new file mode 100644 index 0000000..94c710d --- /dev/null +++ b/questions/delete-columns-to-make-sorted/Solution.py @@ -0,0 +1,66 @@ +""" + +You are given an array of n strings strs, all of the same length. +The strings can be arranged such that there is one on each line, making a grid. For example, strs = ["abc", "bce", "cae"] can be arranged as: + +abc +bce +cae + +You want to delete the columns that are not sorted lexicographically. In the above example (0-indexed), columns 0 ('a', 'b', 'c') and 2 ('c', 'e', 'e') are sorted while column 1 ('b', 'c', 'a') is not, so you would delete column 1. +Return the number of columns that you will delete. +  +Example 1: + +Input: strs = ["cba","daf","ghi"] +Output: 1 +Explanation: The grid looks as follows: + cba + daf + ghi +Columns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column. + +Example 2: + +Input: strs = ["a","b"] +Output: 0 +Explanation: The grid looks as follows: + a + b +Column 0 is the only column and is sorted, so you will not delete any columns. + +Example 3: + +Input: strs = ["zyx","wvu","tsr"] +Output: 3 +Explanation: The grid looks as follows: + zyx + wvu + tsr +All 3 columns are not sorted, so you will delete all 3. + +  +Constraints: + +n == strs.length +1 <= n <= 100 +1 <= strs[i].length <= 1000 +strs[i] consists of lowercase English letters. + + +""" + + +class Solution: + def minDeletionSize(self, strs: List[str]) -> int: + if not strs: + return 0 + ret = 0 + for i in range(len(strs[0])): + for j in range(len(strs)): + if j == 0: + continue + if strs[j][i] < strs[j - 1][i]: + ret += 1 + break + return ret \ No newline at end of file diff --git a/questions/determine-if-two-strings-are-close/Solution.py b/questions/determine-if-two-strings-are-close/Solution.py new file mode 100644 index 0000000..14e13b3 --- /dev/null +++ b/questions/determine-if-two-strings-are-close/Solution.py @@ -0,0 +1,56 @@ +""" + +Two strings are considered close if you can attain one from the other using the following operations: + +Operation 1: Swap any two existing characters. + + +For example, abcde -> aecdb + + +Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character. + +For example, aacabb -> bbcbaa (all a's turn into b's, and all b's turn into a's) + + + +You can use the operations on either string as many times as necessary. +Given two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise. +  +Example 1: + +Input: word1 = "abc", word2 = "bca" +Output: true +Explanation: You can attain word2 from word1 in 2 operations. +Apply Operation 1: "abc" -> "acb" +Apply Operation 1: "acb" -> "bca" + +Example 2: + +Input: word1 = "a", word2 = "aa" +Output: false +Explanation: It is impossible to attain word2 from word1, or vice versa, in any number of operations. + +Example 3: + +Input: word1 = "cabbba", word2 = "abbccc" +Output: true +Explanation: You can attain word2 from word1 in 3 operations. +Apply Operation 1: "cabbba" -> "caabbb" +Apply Operation 2: "caabbb" -> "baaccc" +Apply Operation 2: "baaccc" -> "abbccc" + +  +Constraints: + +1 <= word1.length, word2.length <= 105 +word1 and word2 contain only lowercase English letters. + + +""" + + +class Solution: + def closeStrings(self, w1: str, w2: str) -> bool: + return sorted(Counter(w1).values()) == sorted(Counter(w2).values()) \ + and set(w1) == set(w2) \ No newline at end of file diff --git a/questions/di-string-match/Solution.py b/questions/di-string-match/Solution.py new file mode 100644 index 0000000..78ed81b --- /dev/null +++ b/questions/di-string-match/Solution.py @@ -0,0 +1,44 @@ +""" + +A permutation perm of n + 1 integers of all the integers in the range [0, n] can be represented as a string s of length n where: + +s[i] == 'I' if perm[i] < perm[i + 1], and +s[i] == 'D' if perm[i] > perm[i + 1]. + +Given a string s, reconstruct the permutation perm and return it. If there are multiple valid permutations perm, return any of them. +  +Example 1: +Input: s = "IDID" +Output: [0,4,1,3,2] +Example 2: +Input: s = "III" +Output: [0,1,2,3] +Example 3: +Input: s = "DDI" +Output: [3,2,0,1] + +  +Constraints: + +1 <= s.length <= 105 +s[i] is either 'I' or 'D'. + + +""" + + +class Solution: + def diStringMatch(self, s: str) -> List[int]: + res = [] + start = 0 + end = len(s) + perm = list(range(len(s) + 1)) + for i in s: + if i == 'I': + res.append(perm[start]) + start += 1 + elif i == 'D': + res.append(perm[end]) + end -= 1 + res.append(perm[start]) + return res \ No newline at end of file diff --git a/questions/distance-between-bus-stops/Solution.py b/questions/distance-between-bus-stops/Solution.py new file mode 100644 index 0000000..a215929 --- /dev/null +++ b/questions/distance-between-bus-stops/Solution.py @@ -0,0 +1,49 @@ +""" + +A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between all pairs of neighboring stops where distance[i] is the distance between the stops number i and (i + 1) % n. +The bus goes along both directions i.e. clockwise and counterclockwise. +Return the shortest distance between the given start and destination stops. +  +Example 1: + + +Input: distance = [1,2,3,4], start = 0, destination = 1 +Output: 1 +Explanation: Distance between 0 and 1 is 1 or 9, minimum is 1. +  +Example 2: + + +Input: distance = [1,2,3,4], start = 0, destination = 2 +Output: 3 +Explanation: Distance between 0 and 2 is 3 or 7, minimum is 3. + +  +Example 3: + + +Input: distance = [1,2,3,4], start = 0, destination = 3 +Output: 4 +Explanation: Distance between 0 and 3 is 6 or 4, minimum is 4. + +  +Constraints: + +1 <= n <= 10^4 +distance.length == n +0 <= start, destination < n +0 <= distance[i] <= 10^4 + +""" + + +class Solution: + def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int: + def cal_distance(arr, start, end): + d = 0 + while start != end: + d += arr[start] + start = (start + 1) % len(arr) + return d + + return min(cal_distance(distance, start, destination), cal_distance(distance, destination, start)) \ No newline at end of file diff --git a/questions/distribute-candies-to-people/Solution.py b/questions/distribute-candies-to-people/Solution.py new file mode 100644 index 0000000..3390bb3 --- /dev/null +++ b/questions/distribute-candies-to-people/Solution.py @@ -0,0 +1,53 @@ +""" + +We distribute some number of candies, to a row of n = num_people people in the following way: +We then give 1 candy to the first person, 2 candies to the second person, and so on until we give n candies to the last person. +Then, we go back to the start of the row, giving n + 1 candies to the first person, n + 2 candies to the second person, and so on until we give 2 * n candies to the last person. +This process repeats (with us giving one more candy each time, and moving to the start of the row after we reach the end) until we run out of candies.  The last person will receive all of our remaining candies (not necessarily one more than the previous gift). +Return an array (of length num_people and sum candies) that represents the final distribution of candies. +  +Example 1: + +Input: candies = 7, num_people = 4 +Output: [1,2,3,1] +Explanation: +On the first turn, ans[0] += 1, and the array is [1,0,0,0]. +On the second turn, ans[1] += 2, and the array is [1,2,0,0]. +On the third turn, ans[2] += 3, and the array is [1,2,3,0]. +On the fourth turn, ans[3] += 1 (because there is only one candy left), and the final array is [1,2,3,1]. + +Example 2: + +Input: candies = 10, num_people = 3 +Output: [5,2,3] +Explanation: +On the first turn, ans[0] += 1, and the array is [1,0,0]. +On the second turn, ans[1] += 2, and the array is [1,2,0]. +On the third turn, ans[2] += 3, and the array is [1,2,3]. +On the fourth turn, ans[0] += 4, and the final array is [5,2,3]. + +  +Constraints: + +1 <= candies <= 10^9 +1 <= num_people <= 1000 + + +""" + + +class Solution: + def distributeCandies(self, candies: int, n: int) -> List[int]: + ret = [0] * n + idx, row = 0, 0 + while candies > 0: + expected = idx + 1 + n * row + curr = min(candies, expected) + ret[idx] += curr + candies -= curr + idx += 1 + if idx == n: + row += 1 + idx = 0 + return ret + \ No newline at end of file diff --git a/questions/divisor-game/Solution.py b/questions/divisor-game/Solution.py new file mode 100644 index 0000000..1aab7c5 --- /dev/null +++ b/questions/divisor-game/Solution.py @@ -0,0 +1,50 @@ +""" + +Alice and Bob take turns playing a game, with Alice starting first. +Initially, there is a number n on the chalkboard. On each player's turn, that player makes a move consisting of: + +Choosing any x with 0 < x < n and n % x == 0. +Replacing the number n on the chalkboard with n - x. + +Also, if a player cannot make a move, they lose the game. +Return true if and only if Alice wins the game, assuming both players play optimally. +  +Example 1: + +Input: n = 2 +Output: true +Explanation: Alice chooses 1, and Bob has no more moves. + +Example 2: + +Input: n = 3 +Output: false +Explanation: Alice chooses 1, Bob chooses 1, and Alice has no more moves. + +  +Constraints: + +1 <= n <= 1000 + + +""" + + +class Solution: + def divisorGame(self, n: int) -> bool: + def can_win(n, cache): + if cache[n] is not None: + return cache[n] + for i in range(1, n): + if n % i == 0: + ret = can_win(n - i, cache) + if not ret: + cache[n] = True + return True + cache[n] = False + return False + + cache = [None for _ in range(n + 1)] + cache[0] = True + cache[1] = False + return can_win(n, cache) \ No newline at end of file diff --git a/questions/duplicate-zeros/Solution.py b/questions/duplicate-zeros/Solution.py new file mode 100644 index 0000000..57ea96a --- /dev/null +++ b/questions/duplicate-zeros/Solution.py @@ -0,0 +1,57 @@ +""" + +Given a fixed-length integer array arr, duplicate each occurrence of zero, shifting the remaining elements to the right. +Note that elements beyond the length of the original array are not written. Do the above modifications to the input array in place and do not return anything. +  +Example 1: + +Input: arr = [1,0,2,3,0,4,5,0] +Output: [1,0,0,2,3,0,0,4] +Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4] + +Example 2: + +Input: arr = [1,2,3] +Output: [1,2,3] +Explanation: After calling your function, the input array is modified to: [1,2,3] + +  +Constraints: + +1 <= arr.length <= 104 +0 <= arr[i] <= 9 + + +""" + + +class Solution: + def duplicateZeros(self, arr: List[int]) -> None: + """ + Do not return anything, modify arr in-place instead. + """ + idx, cnt = 0, 0 + while cnt < len(arr): + elem = arr[idx] + if elem == 0: + cnt += 2 + else: + cnt += 1 + idx += 1 + cnt -= 1 + idx -= 1 + if cnt == len(arr): + cnt -= 1 + arr[cnt] = arr[idx] + idx -= 1 + cnt -= 1 + while idx >= 0: + if idx == cnt: + break + elem = arr[idx] + idx -= 1 + arr[cnt] = elem + cnt -= 1 + if elem == 0: + arr[cnt] = elem + cnt -= 1 \ No newline at end of file diff --git a/questions/find-common-characters/Solution.py b/questions/find-common-characters/Solution.py new file mode 100644 index 0000000..da4e670 --- /dev/null +++ b/questions/find-common-characters/Solution.py @@ -0,0 +1,40 @@ +""" + +Given a string array words, return an array of all characters that show up in all strings within the words (including duplicates). You may return the answer in any order. +  +Example 1: +Input: words = ["bella","label","roller"] +Output: ["e","l","l"] +Example 2: +Input: words = ["cool","lock","cook"] +Output: ["c","o"] + +  +Constraints: + +1 <= words.length <= 100 +1 <= words[i].length <= 100 +words[i] consists of lowercase English letters. + + +""" + + +class Solution: + def commonChars(self, words: List[str]) -> List[str]: + tr = Counter(words[0]) + for word in words: + counter = Counter(word) + new_tr = {} + for c in tr: + if c not in counter: + continue + new_tr[c] = min(tr[c], counter[c]) + tr = new_tr + ret = [] + for c, l in tr.items(): + if l <= 0: + continue + for _ in range(l): + ret.append(c) + return ret \ No newline at end of file diff --git a/questions/find-customer-referee/Solution.sql b/questions/find-customer-referee/Solution.sql new file mode 100644 index 0000000..7f5e40d --- /dev/null +++ b/questions/find-customer-referee/Solution.sql @@ -0,0 +1,49 @@ +/* + +Table: Customer + ++-------------+---------+ +| Column Name | Type | ++-------------+---------+ +| id | int | +| name | varchar | +| referee_id | int | ++-------------+---------+ +id is the primary key column for this table. +Each row of this table indicates the id of a customer, their name, and the id of the customer who referred them. + +  +Write an SQL query to report the names of the customer that are not referred by the customer with id = 2. +Return the result table in any order. +The query result format is in the following example. +  +Example 1: + +Input: +Customer table: ++----+------+------------+ +| id | name | referee_id | ++----+------+------------+ +| 1 | Will | null | +| 2 | Jane | null | +| 3 | Alex | 2 | +| 4 | Bill | null | +| 5 | Zack | 1 | +| 6 | Mark | 2 | ++----+------+------------+ +Output: ++------+ +| name | ++------+ +| Will | +| Jane | +| Bill | +| Zack | ++------+ + + +*/ + + +# Write your MySQL query statement below +select name from Customer where referee_id <> 2 or referee_id is null; diff --git a/questions/find-if-path-exists-in-graph/Solution.py b/questions/find-if-path-exists-in-graph/Solution.py new file mode 100644 index 0000000..ccae32b --- /dev/null +++ b/questions/find-if-path-exists-in-graph/Solution.py @@ -0,0 +1,63 @@ +""" + +There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1 (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself. +You want to determine if there is a valid path that exists from vertex source to vertex destination. +Given edges and the integers n, source, and destination, return true if there is a valid path from source to destination, or false otherwise. +  +Example 1: + + +Input: n = 3, edges = [[0,1],[1,2],[2,0]], source = 0, destination = 2 +Output: true +Explanation: There are two paths from vertex 0 to vertex 2: +- 0 → 1 → 2 +- 0 → 2 + +Example 2: + + +Input: n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0, destination = 5 +Output: false +Explanation: There is no path from vertex 0 to vertex 5. + +  +Constraints: + +1 <= n <= 2 * 105 +0 <= edges.length <= 2 * 105 +edges[i].length == 2 +0 <= ui, vi <= n - 1 +ui != vi +0 <= source, destination <= n - 1 +There are no duplicate edges. +There are no self edges. + + +""" + + +class Solution: + def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool: + def build_graph(n, edges): + graph = [set() for _ in range(n)] + for edge in edges: + graph[edge[0]].add(edge[1]) + graph[edge[1]].add(edge[0]) + return graph + + def has_path(graph, src, dest): + stk = [src] + visited = set() + while stk: + curr = stk.pop() + if curr == dest: + return True + if curr in visited: + continue + visited.add(curr) + for ne in graph[curr]: + stk.append(ne) + return False + + graph = build_graph(n, edges) + return has_path(graph, source, destination) \ No newline at end of file diff --git a/questions/find-players-with-zero-or-one-losses/Solution.py b/questions/find-players-with-zero-or-one-losses/Solution.py new file mode 100644 index 0000000..263842e --- /dev/null +++ b/questions/find-players-with-zero-or-one-losses/Solution.py @@ -0,0 +1,66 @@ +""" + +You are given an integer array matches where matches[i] = [winneri, loseri] indicates that the player winneri defeated player loseri in a match. +Return a list answer of size 2 where: + +answer[0] is a list of all players that have not lost any matches. +answer[1] is a list of all players that have lost exactly one match. + +The values in the two lists should be returned in increasing order. +Note: + +You should only consider the players that have played at least one match. +The testcases will be generated such that no two matches will have the same outcome. + +  +Example 1: + +Input: matches = [[1,3],[2,3],[3,6],[5,6],[5,7],[4,5],[4,8],[4,9],[10,4],[10,9]] +Output: [[1,2,10],[4,5,7,8]] +Explanation: +Players 1, 2, and 10 have not lost any matches. +Players 4, 5, 7, and 8 each have lost one match. +Players 3, 6, and 9 each have lost two matches. +Thus, answer[0] = [1,2,10] and answer[1] = [4,5,7,8]. + +Example 2: + +Input: matches = [[2,3],[1,3],[5,4],[6,4]] +Output: [[1,2,5,6],[]] +Explanation: +Players 1, 2, 5, and 6 have not lost any matches. +Players 3 and 4 each have lost two matches. +Thus, answer[0] = [1,2,5,6] and answer[1] = []. + +  +Constraints: + +1 <= matches.length <= 105 +matches[i].length == 2 +1 <= winneri, loseri <= 105 +winneri != loseri +All matches[i] are unique. + + +""" + + +class Solution: + def findWinners(self, matches: List[List[int]]) -> List[List[int]]: + tr = {} + loses = [set(), set()] + for w, l in matches: + if w not in tr: + tr[w] = (0, 0) + if l not in tr: + tr[l] = (0, 0) + tr[w] = (tr[w][0] + 1, tr[w][1]) + tr[l] = (tr[l][0], tr[l][1] + 1) + if w not in loses[tr[w][1]]: + loses[tr[w][1]].add(w) + if l in loses[tr[l][1] - 1]: + loses[tr[l][1] - 1].remove(l) + if len(loses) <= l: + loses.append(set()) + loses[tr[l][1]].add(l) + return list(sorted(loses[0])), list(sorted(loses[1])) \ No newline at end of file diff --git a/questions/find-words-that-can-be-formed-by-characters/Solution.py b/questions/find-words-that-can-be-formed-by-characters/Solution.py new file mode 100644 index 0000000..9b53a0d --- /dev/null +++ b/questions/find-words-that-can-be-formed-by-characters/Solution.py @@ -0,0 +1,41 @@ +""" + +You are given an array of strings words and a string chars. +A string is good if it can be formed by characters from chars (each character can only be used once). +Return the sum of lengths of all good strings in words. +  +Example 1: + +Input: words = ["cat","bt","hat","tree"], chars = "atach" +Output: 6 +Explanation: The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6. + +Example 2: + +Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr" +Output: 10 +Explanation: The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10. + +  +Constraints: + +1 <= words.length <= 1000 +1 <= words[i].length, chars.length <= 100 +words[i] and chars consist of lowercase English letters. + + +""" + + +class Solution: + def countCharacters(self, words: List[str], chars: str) -> int: + ref = Counter(chars) + ret = 0 + for word in words: + w = Counter(word) + for c, v in w.items(): + if v > ref.get(c, 0): + break + else: + ret += len(word) + return ret diff --git a/questions/game-play-analysis-i/Solution.sql b/questions/game-play-analysis-i/Solution.sql new file mode 100644 index 0000000..c79a7f0 --- /dev/null +++ b/questions/game-play-analysis-i/Solution.sql @@ -0,0 +1,49 @@ +/* + +Table: Activity + ++--------------+---------+ +| Column Name | Type | ++--------------+---------+ +| player_id | int | +| device_id | int | +| event_date | date | +| games_played | int | ++--------------+---------+ +(player_id, event_date) is the primary key of this table. +This table shows the activity of players of some games. +Each row is a record of a player who logged in and played a number of games (possibly 0) before logging out on someday using some device. + +  +Write an SQL query to report the first login date for each player. +Return the result table in any order. +The query result format is in the following example. +  +Example 1: + +Input: +Activity table: ++-----------+-----------+------------+--------------+ +| player_id | device_id | event_date | games_played | ++-----------+-----------+------------+--------------+ +| 1 | 2 | 2016-03-01 | 5 | +| 1 | 2 | 2016-05-02 | 6 | +| 2 | 3 | 2017-06-25 | 1 | +| 3 | 1 | 2016-03-02 | 0 | +| 3 | 4 | 2018-07-03 | 5 | ++-----------+-----------+------------+--------------+ +Output: ++-----------+-------------+ +| player_id | first_login | ++-----------+-------------+ +| 1 | 2016-03-01 | +| 2 | 2017-06-25 | +| 3 | 2016-03-02 | ++-----------+-------------+ + + +*/ + + +# Write your MySQL query statement below +select player_id, min(event_date) as first_login from activity group by player_id; diff --git a/questions/height-checker/Solution.py b/questions/height-checker/Solution.py new file mode 100644 index 0000000..327ab6d --- /dev/null +++ b/questions/height-checker/Solution.py @@ -0,0 +1,46 @@ +""" + +A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in non-decreasing order by height. Let this ordering be represented by the integer array expected where expected[i] is the expected height of the ith student in line. +You are given an integer array heights representing the current order that the students are standing in. Each heights[i] is the height of the ith student in line (0-indexed). +Return the number of indices where heights[i] != expected[i]. +  +Example 1: + +Input: heights = [1,1,4,2,1,3] +Output: 3 +Explanation: +heights: [1,1,4,2,1,3] +expected: [1,1,1,2,3,4] +Indices 2, 4, and 5 do not match. + +Example 2: + +Input: heights = [5,1,2,3,4] +Output: 5 +Explanation: +heights: [5,1,2,3,4] +expected: [1,2,3,4,5] +All indices do not match. + +Example 3: + +Input: heights = [1,2,3,4,5] +Output: 0 +Explanation: +heights: [1,2,3,4,5] +expected: [1,2,3,4,5] +All indices match. + +  +Constraints: + +1 <= heights.length <= 100 +1 <= heights[i] <= 100 + + +""" + + +class Solution: + def heightChecker(self, heights: List[int]) -> int: + return sum((1 for a, b in zip(heights, sorted(heights)) if a != b)) \ No newline at end of file diff --git a/questions/largest-perimeter-triangle/Solution.py b/questions/largest-perimeter-triangle/Solution.py new file mode 100644 index 0000000..0269e6e --- /dev/null +++ b/questions/largest-perimeter-triangle/Solution.py @@ -0,0 +1,43 @@ +""" + +Given an integer array nums, return the largest perimeter of a triangle with a non-zero area, formed from three of these lengths. If it is impossible to form any triangle of a non-zero area, return 0. +  +Example 1: + +Input: nums = [2,1,2] +Output: 5 +Explanation: You can form a triangle with three side lengths: 1, 2, and 2. + +Example 2: + +Input: nums = [1,2,1,10] +Output: 0 +Explanation: +You cannot use the side lengths 1, 1, and 2 to form a triangle. +You cannot use the side lengths 1, 1, and 10 to form a triangle. +You cannot use the side lengths 1, 2, and 10 to form a triangle. +As we cannot use any three side lengths to form a triangle of non-zero area, we return 0. + +  +Constraints: + +3 <= nums.length <= 104 +1 <= nums[i] <= 106 + + +""" + + +class Solution: + def largestPerimeter(self, nums: List[int]) -> int: + nums.sort() + s = 0 + for i in range(len(nums) - 1, -1, -1): + if i > len(nums) - 3: + continue + elif i == len(nums) - 3: + p1, p2 = nums[-1], nums[-2] + if p1 < p2 + nums[i]: + return nums[i] + p2 + p1 + p1, p2 = p2, nums[i] + return s \ No newline at end of file diff --git a/questions/long-pressed-name/Solution.py b/questions/long-pressed-name/Solution.py new file mode 100644 index 0000000..009972a --- /dev/null +++ b/questions/long-pressed-name/Solution.py @@ -0,0 +1,53 @@ +""" + +Your friend is typing his name into a keyboard. Sometimes, when typing a character c, the key might get long pressed, and the character will be typed 1 or more times. +You examine the typed characters of the keyboard. Return True if it is possible that it was your friends name, with some characters (possibly none) being long pressed. +  +Example 1: + +Input: name = "alex", typed = "aaleex" +Output: true +Explanation: 'a' and 'e' in 'alex' were long pressed. + +Example 2: + +Input: name = "saeed", typed = "ssaaedd" +Output: false +Explanation: 'e' must have been pressed twice, but it was not in the typed output. + +  +Constraints: + +1 <= name.length, typed.length <= 1000 +name and typed consist of only lowercase English letters. + + +""" + + +class Solution: + def isLongPressedName(self, name: str, typed: str) -> bool: + if len(typed) < len(name): + return False + i, j = 0, 0 + while i < len(name) and j < len(typed): + n, c = name[i], typed[j] + if n != c: + if i > 0 and c == name[i - 1]: + j += 1 + continue + else: + return False + else: + i += 1 + j += 1 + if i != len(name): + return False + while j < len(typed): + c = typed[j] + if name[-1] != c: + return False + j += 1 + return True + + \ No newline at end of file diff --git a/questions/longest-subsequence-with-limited-sum/Solution.py b/questions/longest-subsequence-with-limited-sum/Solution.py new file mode 100644 index 0000000..0966623 --- /dev/null +++ b/questions/longest-subsequence-with-limited-sum/Solution.py @@ -0,0 +1,39 @@ +""" + +You are given an integer array nums of length n, and an integer array queries of length m. +Return an array answer of length m where answer[i] is the maximum size of a subsequence that you can take from nums such that the sum of its elements is less than or equal to queries[i]. +A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. +  +Example 1: + +Input: nums = [4,5,2,1], queries = [3,10,21] +Output: [2,3,4] +Explanation: We answer the queries as follows: +- The subsequence [2,1] has a sum less than or equal to 3. It can be proven that 2 is the maximum size of such a subsequence, so answer[0] = 2. +- The subsequence [4,5,1] has a sum less than or equal to 10. It can be proven that 3 is the maximum size of such a subsequence, so answer[1] = 3. +- The subsequence [4,5,2,1] has a sum less than or equal to 21. It can be proven that 4 is the maximum size of such a subsequence, so answer[2] = 4. + +Example 2: + +Input: nums = [2,3,4,5], queries = [1] +Output: [0] +Explanation: The empty subsequence is the only subsequence that has a sum less than or equal to 1, so answer[0] = 0. +  +Constraints: + +n == nums.length +m == queries.length +1 <= n, m <= 1000 +1 <= nums[i], queries[i] <= 106 + + +""" + + +class Solution: + def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]: + nums.sort() + sums = [0] + for n in nums: + sums.append(sums[-1] + n) + return (bisect.bisect(sums, q) - 1 for q in queries) \ No newline at end of file diff --git a/questions/matrix-cells-in-distance-order/Solution.py b/questions/matrix-cells-in-distance-order/Solution.py new file mode 100644 index 0000000..19d81ff --- /dev/null +++ b/questions/matrix-cells-in-distance-order/Solution.py @@ -0,0 +1,41 @@ +""" + +You are given four integers row, cols, rCenter, and cCenter. There is a rows x cols matrix and you are on the cell with the coordinates (rCenter, cCenter). +Return the coordinates of all cells in the matrix, sorted by their distance from (rCenter, cCenter) from the smallest distance to the largest distance. You may return the answer in any order that satisfies this condition. +The distance between two cells (r1, c1) and (r2, c2) is |r1 - r2| + |c1 - c2|. +  +Example 1: + +Input: rows = 1, cols = 2, rCenter = 0, cCenter = 0 +Output: [[0,0],[0,1]] +Explanation: The distances from (0, 0) to other cells are: [0,1] + +Example 2: + +Input: rows = 2, cols = 2, rCenter = 0, cCenter = 1 +Output: [[0,1],[0,0],[1,1],[1,0]] +Explanation: The distances from (0, 1) to other cells are: [0,1,1,2] +The answer [[0,1],[1,1],[0,0],[1,0]] would also be accepted as correct. + +Example 3: + +Input: rows = 2, cols = 3, rCenter = 1, cCenter = 2 +Output: [[1,2],[0,2],[1,1],[0,1],[1,0],[0,0]] +Explanation: The distances from (1, 2) to other cells are: [0,1,1,2,2,3] +There are other answers that would also be accepted as correct, such as [[1,2],[1,1],[0,2],[1,0],[0,1],[0,0]]. + +  +Constraints: + +1 <= rows, cols <= 100 +0 <= rCenter < rows +0 <= cCenter < cols + + +""" + + +class Solution: + def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]: + cells = [[row, col] for row in range(rows) for col in range(cols)] + return list(sorted(cells, key=lambda cell: abs(cell[0] - rCenter) + abs(cell[1] - cCenter))) \ No newline at end of file diff --git a/questions/maximum-bags-with-full-capacity-of-rocks/Solution.py b/questions/maximum-bags-with-full-capacity-of-rocks/Solution.py new file mode 100644 index 0000000..de5a726 --- /dev/null +++ b/questions/maximum-bags-with-full-capacity-of-rocks/Solution.py @@ -0,0 +1,56 @@ +""" + +You have n bags numbered from 0 to n - 1. You are given two 0-indexed integer arrays capacity and rocks. The ith bag can hold a maximum of capacity[i] rocks and currently contains rocks[i] rocks. You are also given an integer additionalRocks, the number of additional rocks you can place in any of the bags. +Return the maximum number of bags that could have full capacity after placing the additional rocks in some bags. +  +Example 1: + +Input: capacity = [2,3,4,5], rocks = [1,2,4,4], additionalRocks = 2 +Output: 3 +Explanation: +Place 1 rock in bag 0 and 1 rock in bag 1. +The number of rocks in each bag are now [2,3,4,4]. +Bags 0, 1, and 2 have full capacity. +There are 3 bags at full capacity, so we return 3. +It can be shown that it is not possible to have more than 3 bags at full capacity. +Note that there may be other ways of placing the rocks that result in an answer of 3. + +Example 2: + +Input: capacity = [10,2,2], rocks = [2,2,0], additionalRocks = 100 +Output: 3 +Explanation: +Place 8 rocks in bag 0 and 2 rocks in bag 2. +The number of rocks in each bag are now [10,2,2]. +Bags 0, 1, and 2 have full capacity. +There are 3 bags at full capacity, so we return 3. +It can be shown that it is not possible to have more than 3 bags at full capacity. +Note that we did not use all of the additional rocks. + +  +Constraints: + +n == capacity.length == rocks.length +1 <= n <= 5 * 104 +1 <= capacity[i] <= 109 +0 <= rocks[i] <= capacity[i] +1 <= additionalRocks <= 109 + + +""" + + +class Solution: + def maximumBags(self, capacity: List[int], rocks: List[int], additionalRocks: int) -> int: + ret = 0 + tt = list(sorted([c - r for c, r in zip(capacity, rocks)])) + for a in tt: + if a == 0: + ret += 1 + continue + if additionalRocks >= a: + ret += 1 + additionalRocks -= a + else: + break + return ret diff --git a/questions/maximum-number-of-balloons/Solution.py b/questions/maximum-number-of-balloons/Solution.py new file mode 100644 index 0000000..dfa7b69 --- /dev/null +++ b/questions/maximum-number-of-balloons/Solution.py @@ -0,0 +1,46 @@ +""" + +Given a string text, you want to use the characters of text to form as many instances of the word "balloon" as possible. +You can use each character in text at most once. Return the maximum number of instances that can be formed. +  +Example 1: + + +Input: text = "nlaebolko" +Output: 1 + +Example 2: + + +Input: text = "loonbalxballpoon" +Output: 2 + +Example 3: + +Input: text = "leetcode" +Output: 0 + +  +Constraints: + +1 <= text.length <= 104 +text consists of lower case English letters only. + + +""" + + +class Solution: + def maxNumberOfBalloons(self, text: str) -> int: + base = Counter('balloon') + tr = {} + for a in text: + if a not in base: + continue + tr[a] = tr.get(a, 0) + 1 + multiple = len(text) + for k in base.keys(): + if k not in tr: + return 0 + multiple = min(multiple, tr[k] // base[k]) + return multiple diff --git a/questions/maximum-product-of-splitted-binary-tree/Solution.py b/questions/maximum-product-of-splitted-binary-tree/Solution.py new file mode 100644 index 0000000..e5f2761 --- /dev/null +++ b/questions/maximum-product-of-splitted-binary-tree/Solution.py @@ -0,0 +1,53 @@ +""" + +Given the root of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized. +Return the maximum product of the sums of the two subtrees. Since the answer may be too large, return it modulo 109 + 7. +Note that you need to maximize the answer before taking the mod and not after taking it. +  +Example 1: + + +Input: root = [1,2,3,4,5,6] +Output: 110 +Explanation: Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11*10) + +Example 2: + + +Input: root = [1,null,2,3,4,null,null,5,6] +Output: 90 +Explanation: Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15*6) + +  +Constraints: + +The number of nodes in the tree is in the range [2, 5 * 104]. +1 <= Node.val <= 104 + + +""" + + +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def maxProduct(self, root: Optional[TreeNode]) -> int: + def sub_tree_sums(node, ss): + ls = rs = 0 + if node.left is not None: + ls = sub_tree_sums(node.left, ss) + if node.right is not None: + rs = sub_tree_sums(node.right, ss) + ss.append(ls + rs + node.val) + return ss[-1] + + ls = [] + ss = sub_tree_sums(root, ls) + ms = 0 + for a in ls: + ms = max(ms, (ss - a) * a) + return ms % (1000_000_007) \ No newline at end of file diff --git a/questions/maximum-profit-in-job-scheduling/Solution.py b/questions/maximum-profit-in-job-scheduling/Solution.py new file mode 100644 index 0000000..59d209c --- /dev/null +++ b/questions/maximum-profit-in-job-scheduling/Solution.py @@ -0,0 +1,50 @@ +""" + +We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i]. +You're given the startTime, endTime and profit arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range. +If you choose a job that ends at time X you will be able to start another job that starts at time X. +  +Example 1: + + +Input: startTime = [1,2,3,3], endTime = [3,4,5,6], profit = [50,10,40,70] +Output: 120 +Explanation: The subset chosen is the first and fourth job. +Time range [1-3]+[3-6] , we get profit of 120 = 50 + 70. + +Example 2: + + +Input: startTime = [1,2,3,4,6], endTime = [3,5,10,6,9], profit = [20,20,100,70,60] +Output: 150 +Explanation: The subset chosen is the first, fourth and fifth job. +Profit obtained 150 = 20 + 70 + 60. + +Example 3: + + +Input: startTime = [1,1,1], endTime = [2,3,4], profit = [5,6,4] +Output: 6 + +  +Constraints: + +1 <= startTime.length == endTime.length == profit.length <= 5 * 104 +1 <= startTime[i] < endTime[i] <= 109 +1 <= profit[i] <= 104 + + +""" + + +class Solution: + def jobScheduling(self, s, e, p): + + jobs, n = sorted(zip(s, e, p)), len(s) # [1] prepare jobs for binary search + dp = [0] * (n + 1) # by sorting them by start time + + for i in reversed(range(n)): # [2] knapsack: either try next job or + k = bisect_left(jobs, jobs[i][1], key=lambda j: j[0]) # take this one together with trying + dp[i] = max(jobs[i][2] + dp[k], dp[i+1]) # the next valid one + + return dp[0] \ No newline at end of file diff --git a/questions/minimum-absolute-difference/Solution.py b/questions/minimum-absolute-difference/Solution.py new file mode 100644 index 0000000..681cbf3 --- /dev/null +++ b/questions/minimum-absolute-difference/Solution.py @@ -0,0 +1,48 @@ +""" + +Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements. +Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows + +a, b are from arr +a < b +b - a equals to the minimum absolute difference of any two elements in arr + +  +Example 1: + +Input: arr = [4,2,1,3] +Output: [[1,2],[2,3],[3,4]] +Explanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order. +Example 2: + +Input: arr = [1,3,6,10,15] +Output: [[1,3]] + +Example 3: + +Input: arr = [3,8,-10,23,19,-4,-14,27] +Output: [[-14,-10],[19,23],[23,27]] + +  +Constraints: + +2 <= arr.length <= 105 +-106 <= arr[i] <= 106 + + +""" + + +class Solution: + def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: + arr.sort() + m = arr[-1] - arr[0] + for i in range(1, len(arr)): + prev, curr = arr[i - 1], arr[i] + m = min(curr - prev, m) + ret = [] + for i in range(1, len(arr)): + prev, curr = arr[i - 1], arr[i] + if curr - prev == m: + ret.append([prev, curr]) + return ret \ No newline at end of file diff --git a/questions/minimum-average-difference/Solution.py b/questions/minimum-average-difference/Solution.py new file mode 100644 index 0000000..b122b0d --- /dev/null +++ b/questions/minimum-average-difference/Solution.py @@ -0,0 +1,64 @@ +""" + +You are given a 0-indexed integer array nums of length n. +The average difference of the index i is the absolute difference between the average of the first i + 1 elements of nums and the average of the last n - i - 1 elements. Both averages should be rounded down to the nearest integer. +Return the index with the minimum average difference. If there are multiple such indices, return the smallest one. +Note: + +The absolute difference of two numbers is the absolute value of their difference. +The average of n elements is the sum of the n elements divided (integer division) by n. +The average of 0 elements is considered to be 0. + +  +Example 1: + +Input: nums = [2,5,3,9,5,3] +Output: 3 +Explanation: +- The average difference of index 0 is: |2 / 1 - (5 + 3 + 9 + 5 + 3) / 5| = |2 / 1 - 25 / 5| = |2 - 5| = 3. +- The average difference of index 1 is: |(2 + 5) / 2 - (3 + 9 + 5 + 3) / 4| = |7 / 2 - 20 / 4| = |3 - 5| = 2. +- The average difference of index 2 is: |(2 + 5 + 3) / 3 - (9 + 5 + 3) / 3| = |10 / 3 - 17 / 3| = |3 - 5| = 2. +- The average difference of index 3 is: |(2 + 5 + 3 + 9) / 4 - (5 + 3) / 2| = |19 / 4 - 8 / 2| = |4 - 4| = 0. +- The average difference of index 4 is: |(2 + 5 + 3 + 9 + 5) / 5 - 3 / 1| = |24 / 5 - 3 / 1| = |4 - 3| = 1. +- The average difference of index 5 is: |(2 + 5 + 3 + 9 + 5 + 3) / 6 - 0| = |27 / 6 - 0| = |4 - 0| = 4. +The average difference of index 3 is the minimum average difference so return 3. + +Example 2: + +Input: nums = [0] +Output: 0 +Explanation: +The only index is 0 so return 0. +The average difference of index 0 is: |0 / 1 - 0| = |0 - 0| = 0. + +  +Constraints: + +1 <= nums.length <= 105 +0 <= nums[i] <= 105 + + +""" + + +class Solution: + def minimumAverageDifference(self, nums: List[int]) -> int: + # leftSum represents the sum of the first i + 1 elements at index i + n, totalSum, leftSum = len(nums), sum(nums), 0 + + # res[0] is the minimum absolute difference, and res[1] is the index. + res = [inf,inf] + + for i,v in enumerate(nums): + leftSum += v + + leftAvg = leftSum//(i+1) + # when we are at the last index, the right hand side sum is 0. (To aviod divide by zero error) + rightAvg = (totalSum-leftSum)//(n-i-1) if n-i-1!=0 else 0 + absDif = abs(leftAvg-rightAvg) + + # min will take care of "If there are multiple such indices, return the smallest one." + res = min(res,[absDif,i]) + + # return the index + return res[1] \ No newline at end of file diff --git a/questions/minimum-cost-to-move-chips-to-the-same-position/Solution.py b/questions/minimum-cost-to-move-chips-to-the-same-position/Solution.py new file mode 100644 index 0000000..2a201ea --- /dev/null +++ b/questions/minimum-cost-to-move-chips-to-the-same-position/Solution.py @@ -0,0 +1,50 @@ +""" + +We have n chips, where the position of the ith chip is position[i]. +We need to move all the chips to the same position. In one step, we can change the position of the ith chip from position[i] to: + +position[i] + 2 or position[i] - 2 with cost = 0. +position[i] + 1 or position[i] - 1 with cost = 1. + +Return the minimum cost needed to move all the chips to the same position. +  +Example 1: + + +Input: position = [1,2,3] +Output: 1 +Explanation: First step: Move the chip at position 3 to position 1 with cost = 0. +Second step: Move the chip at position 2 to position 1 with cost = 1. +Total cost is 1. + +Example 2: + + +Input: position = [2,2,2,3,3] +Output: 2 +Explanation: We can move the two chips at position 3 to position 2. Each move has cost = 1. The total cost = 2. + +Example 3: + +Input: position = [1,1000000000] +Output: 1 + +  +Constraints: + +1 <= position.length <= 100 +1 <= position[i] <= 10^9 + + +""" + + +class Solution: + def minCostToMoveChips(self, position: List[int]) -> int: + even_count, odd_count = 0, 0 + for p in position: + if p & 1 == 1: + odd_count += 1 + else: + even_count += 1 + return min(odd_count, even_count) \ No newline at end of file diff --git a/questions/minimum-falling-path-sum/Solution.py b/questions/minimum-falling-path-sum/Solution.py new file mode 100644 index 0000000..123ca64 --- /dev/null +++ b/questions/minimum-falling-path-sum/Solution.py @@ -0,0 +1,47 @@ +""" + +Given an n x n array of integers matrix, return the minimum sum of any falling path through matrix. +A falling path starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position (row, col) will be (row + 1, col - 1), (row + 1, col), or (row + 1, col + 1). +  +Example 1: + + +Input: matrix = [[2,1,3],[6,5,4],[7,8,9]] +Output: 13 +Explanation: There are two falling paths with a minimum sum as shown. + +Example 2: + + +Input: matrix = [[-19,57],[-40,-5]] +Output: -59 +Explanation: The falling path with a minimum sum is shown. + +  +Constraints: + +n == matrix.length == matrix[i].length +1 <= n <= 100 +-100 <= matrix[i][j] <= 100 + + +""" + + +class Solution: + def minFallingPathSum(self, matrix: List[List[int]]) -> int: + if not matrix: + return 0 + dp = [a for a in matrix[0]] + for i in range(1, len(matrix)): + row = matrix[i] + nt = [] + for j, elem in enumerate(row): + if 0 == j: + nt.append(elem + min(dp[j], dp[j + 1])) + elif len(row) - 1 == j: + nt.append(elem + min(dp[j], dp[j - 1])) + else: + nt.append(elem + min(dp[j], dp[j - 1], dp[j + 1])) + dp = nt + return min(dp) diff --git a/questions/minimum-time-visiting-all-points/Solution.py b/questions/minimum-time-visiting-all-points/Solution.py new file mode 100644 index 0000000..4a424e6 --- /dev/null +++ b/questions/minimum-time-visiting-all-points/Solution.py @@ -0,0 +1,50 @@ +""" + +On a 2D plane, there are n points with integer coordinates points[i] = [xi, yi]. Return the minimum time in seconds to visit all the points in the order given by points. +You can move according to these rules: + +In 1 second, you can either: + + +move vertically by one unit, +move horizontally by one unit, or +move diagonally sqrt(2) units (in other words, move one unit vertically then one unit horizontally in 1 second). + + +You have to visit the points in the same order as they appear in the array. +You are allowed to pass through points that appear later in the order, but these do not count as visits. + +  +Example 1: + + +Input: points = [[1,1],[3,4],[-1,0]] +Output: 7 +Explanation: One optimal path is [1,1] -> [2,2] -> [3,3] -> [3,4] -> [2,3] -> [1,2] -> [0,1] -> [-1,0] +Time from [1,1] to [3,4] = 3 seconds +Time from [3,4] to [-1,0] = 4 seconds +Total time = 7 seconds +Example 2: + +Input: points = [[3,2],[-2,2]] +Output: 5 + +  +Constraints: + +points.length == n +1 <= n <= 100 +points[i].length == 2 +-1000 <= points[i][0], points[i][1] <= 1000 + + +""" + + +class Solution: + def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int: + ret = 0 + for i in range(1, len(points)): + prev, curr = points[i - 1], points[i] + ret += max(abs(curr[0] - prev[0]), abs(curr[1] - prev[1])) + return ret diff --git a/questions/n-th-tribonacci-number/Solution.py b/questions/n-th-tribonacci-number/Solution.py new file mode 100644 index 0000000..0455687 --- /dev/null +++ b/questions/n-th-tribonacci-number/Solution.py @@ -0,0 +1,38 @@ +""" + +The Tribonacci sequence Tn is defined as follows:  +T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0. +Given n, return the value of Tn. +  +Example 1: + +Input: n = 4 +Output: 4 +Explanation: +T_3 = 0 + 1 + 1 = 2 +T_4 = 1 + 1 + 2 = 4 + +Example 2: + +Input: n = 25 +Output: 1389537 + +  +Constraints: + +0 <= n <= 37 +The answer is guaranteed to fit within a 32-bit integer, ie. answer <= 2^31 - 1. + +""" + + +class Solution: + def tribonacci(self, n: int) -> int: + arr = [0, 1, 1] + if n <= 2: + return arr[n] + n -= 2 + while n > 0: + arr[0], arr[1], arr[2] = arr[1], arr[2], arr[0] + arr[1] + arr[2] + n -= 1 + return arr[2] \ No newline at end of file diff --git a/questions/nearest-exit-from-entrance-in-maze/Solution.py b/questions/nearest-exit-from-entrance-in-maze/Solution.py new file mode 100644 index 0000000..96144b0 --- /dev/null +++ b/questions/nearest-exit-from-entrance-in-maze/Solution.py @@ -0,0 +1,82 @@ +""" + +You are given an m x n matrix maze (0-indexed) with empty cells (represented as '.') and walls (represented as '+'). You are also given the entrance of the maze, where entrance = [entrancerow, entrancecol] denotes the row and column of the cell you are initially standing at. +In one step, you can move one cell up, down, left, or right. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the nearest exit from the entrance. An exit is defined as an empty cell that is at the border of the maze. The entrance does not count as an exit. +Return the number of steps in the shortest path from the entrance to the nearest exit, or -1 if no such path exists. +  +Example 1: + + +Input: maze = [["+","+",".","+"],[".",".",".","+"],["+","+","+","."]], entrance = [1,2] +Output: 1 +Explanation: There are 3 exits in this maze at [1,0], [0,2], and [2,3]. +Initially, you are at the entrance cell [1,2]. +- You can reach [1,0] by moving 2 steps left. +- You can reach [0,2] by moving 1 step up. +It is impossible to reach [2,3] from the entrance. +Thus, the nearest exit is [0,2], which is 1 step away. + +Example 2: + + +Input: maze = [["+","+","+"],[".",".","."],["+","+","+"]], entrance = [1,0] +Output: 2 +Explanation: There is 1 exit in this maze at [1,2]. +[1,0] does not count as an exit since it is the entrance cell. +Initially, you are at the entrance cell [1,0]. +- You can reach [1,2] by moving 2 steps right. +Thus, the nearest exit is [1,2], which is 2 steps away. + +Example 3: + + +Input: maze = [[".","+"]], entrance = [0,0] +Output: -1 +Explanation: There are no exits in this maze. + +  +Constraints: + +maze.length == m +maze[i].length == n +1 <= m, n <= 100 +maze[i][j] is either '.' or '+'. +entrance.length == 2 +0 <= entrancerow < m +0 <= entrancecol < n +entrance will always be an empty cell. + + +""" + + +class Solution: + def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: + + m,n = len(maze),len(maze[0]) + directions = [[0,1],[1,0],[0,-1],[-1,0]] + q = deque([entrance]) + + ### Using extra space to keep track of the visited positions. + visited = {tuple(entrance)} + + ### Use steps to keep track of the level of the BFS. + steps = 0 + while q: + + ### Since we are tracking the steps using a variable, + ### we need to pop all elements at each level, then increase the steps. + for _ in range(len(q)): + xo,yo = q.popleft() + if (0 in [xo,yo] or xo==m-1 or yo==n-1) and [xo,yo]!=entrance: + return steps + for xn,yn in directions: + x,y = xo+xn,yo+yn + ### Check if the new position has been visited or not., and only go into the unvisited ones. + if 0<=x List[List[int]]: + def generate(nums, idx, curr, ret): + if len(curr) >= 2: + ret.append(tuple(curr)) + if idx > len(nums): + return + ss = set() + for i in range(idx, len(nums)): + if curr and curr[-1] > nums[i]: + continue + if nums[i] in ss: + continue + ss.add(nums[i]) + curr.append(nums[i]) + generate(nums, i + 1, curr, ret) + curr.pop() + + ret = [] + generate(nums, 0, [], ret) + return [list(e) for e in ret] \ No newline at end of file diff --git a/questions/number-of-equivalent-domino-pairs/Solution.py b/questions/number-of-equivalent-domino-pairs/Solution.py new file mode 100644 index 0000000..c9dfba6 --- /dev/null +++ b/questions/number-of-equivalent-domino-pairs/Solution.py @@ -0,0 +1,38 @@ +""" + +Given a list of dominoes, dominoes[i] = [a, b] is equivalent to dominoes[j] = [c, d] if and only if either (a == c and b == d), or (a == d and b == c) - that is, one domino can be rotated to be equal to another domino. +Return the number of pairs (i, j) for which 0 <= i < j < dominoes.length, and dominoes[i] is equivalent to dominoes[j]. +  +Example 1: + +Input: dominoes = [[1,2],[2,1],[3,4],[5,6]] +Output: 1 + +Example 2: + +Input: dominoes = [[1,2],[1,2],[1,1],[1,2],[2,2]] +Output: 3 + +  +Constraints: + +1 <= dominoes.length <= 4 * 104 +dominoes[i].length == 2 +1 <= dominoes[i][j] <= 9 + + +""" + + +class Solution: + def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int: + tr = {} + for a, b in dominoes: + if a > b: + a, b = b, a + key = (a, b) + tr[key] = tr.get(key, 0) + 1 + ret = 0 + for v in tr.values(): + ret += max((v - 1) * v // 2, 0) + return ret \ No newline at end of file diff --git a/questions/occurrences-after-bigram/Solution.py b/questions/occurrences-after-bigram/Solution.py new file mode 100644 index 0000000..5708ef3 --- /dev/null +++ b/questions/occurrences-after-bigram/Solution.py @@ -0,0 +1,35 @@ +""" + +Given two strings first and second, consider occurrences in some text of the form "first second third", where second comes immediately after first, and third comes immediately after second. +Return an array of all the words third for each occurrence of "first second third". +  +Example 1: +Input: text = "alice is a good girl she is a good student", first = "a", second = "good" +Output: ["girl","student"] +Example 2: +Input: text = "we will we will rock you", first = "we", second = "will" +Output: ["we","rock"] + +  +Constraints: + +1 <= text.length <= 1000 +text consists of lowercase English letters and spaces. +All the words in text a separated by a single space. +1 <= first.length, second.length <= 10 +first and second consist of lowercase English letters. + + +""" + + +class Solution: + def findOcurrences(self, text: str, first: str, second: str) -> List[str]: + words = text.split(' ') + ret = [] + for i in range(len(words)): + if i < 2: + continue + if words[i - 2] == first and words[i - 1] == second: + ret.append(words[i]) + return ret \ No newline at end of file diff --git a/questions/partition-array-into-three-parts-with-equal-sum/Solution.py b/questions/partition-array-into-three-parts-with-equal-sum/Solution.py new file mode 100644 index 0000000..eb20425 --- /dev/null +++ b/questions/partition-array-into-three-parts-with-equal-sum/Solution.py @@ -0,0 +1,56 @@ +""" + +Given an array of integers arr, return true if we can partition the array into three non-empty parts with equal sums. +Formally, we can partition the array if we can find indexes i + 1 < j with (arr[0] + arr[1] + ... + arr[i] == arr[i + 1] + arr[i + 2] + ... + arr[j - 1] == arr[j] + arr[j + 1] + ... + arr[arr.length - 1]) +  +Example 1: + +Input: arr = [0,2,1,-6,6,-7,9,1,2,0,1] +Output: true +Explanation: 0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1 + +Example 2: + +Input: arr = [0,2,1,-6,6,7,9,-1,2,0,1] +Output: false + +Example 3: + +Input: arr = [3,3,6,5,-2,2,5,1,-9,4] +Output: true +Explanation: 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4 + +  +Constraints: + +3 <= arr.length <= 5 * 104 +-104 <= arr[i] <= 104 + + +""" + + +class Solution: + def canThreePartsEqualSum(self, arr: List[int]) -> bool: + s = sum(arr) + if s % 3 != 0: + return False + s3 = s // 3 + ss = [0] + tr = {} + for i, a in enumerate(arr): + ss.append(ss[-1] + a) + tr[ss[-1]] = tr.get(ss[-1], []) + [i] + if s3 not in tr or s3 + s3 not in tr: + return False + part1 = tr[s3] + part2 = tr[s3 + s3] + part3 = tr[s] + for p in part2: + if p > part1[0]: + for j in part3: + if j > p: + return True + else: + return False + return False \ No newline at end of file diff --git a/questions/print-in-order/Solution.py b/questions/print-in-order/Solution.py new file mode 100644 index 0000000..da47459 --- /dev/null +++ b/questions/print-in-order/Solution.py @@ -0,0 +1,60 @@ +""" + +Suppose we have a class: + +public class Foo { + public void first() { print("first"); } + public void second() { print("second"); } + public void third() { print("third"); } +} + +The same instance of Foo will be passed to three different threads. Thread A will call first(), thread B will call second(), and thread C will call third(). Design a mechanism and modify the program to ensure that second() is executed after first(), and third() is executed after second(). +Note: +We do not know how the threads will be scheduled in the operating system, even though the numbers in the input seem to imply the ordering. The input format you see is mainly to ensure our tests' comprehensiveness. +  +Example 1: + +Input: nums = [1,2,3] +Output: "firstsecondthird" +Explanation: There are three threads being fired asynchronously. The input [1,2,3] means thread A calls first(), thread B calls second(), and thread C calls third(). "firstsecondthird" is the correct output. + +Example 2: + +Input: nums = [1,3,2] +Output: "firstsecondthird" +Explanation: The input [1,3,2] means thread A calls first(), thread B calls third(), and thread C calls second(). "firstsecondthird" is the correct output. + +  +Constraints: + +nums is a permutation of [1, 2, 3]. + + +""" + + +from threading import Event + +class Foo: + def __init__(self): + self.signal1 = Event() + self.signal2 = Event() + + + def first(self, printFirst: 'Callable[[], None]') -> None: + # printFirst() outputs "first". Do not change or remove this line. + printFirst() + self.signal1.set() + + + def second(self, printSecond: 'Callable[[], None]') -> None: + self.signal1.wait() + # printSecond() outputs "second". Do not change or remove this line. + printSecond() + self.signal2.set() + + + def third(self, printThird: 'Callable[[], None]') -> None: + self.signal2.wait() + # printThird() outputs "third". Do not change or remove this line. + printThird() \ No newline at end of file diff --git a/questions/rectangle-area/Solution.py b/questions/rectangle-area/Solution.py new file mode 100644 index 0000000..09c454c --- /dev/null +++ b/questions/rectangle-area/Solution.py @@ -0,0 +1,32 @@ +""" + +Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles. +The first rectangle is defined by its bottom-left corner (ax1, ay1) and its top-right corner (ax2, ay2). +The second rectangle is defined by its bottom-left corner (bx1, by1) and its top-right corner (bx2, by2). +  +Example 1: + + +Input: ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2 +Output: 45 + +Example 2: + +Input: ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2 +Output: 16 + +  +Constraints: + +-104 <= ax1 <= ax2 <= 104 +-104 <= ay1 <= ay2 <= 104 +-104 <= bx1 <= bx2 <= 104 +-104 <= by1 <= by2 <= 104 + + +""" + + +class Solution: + def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int: + return (ax2-ax1)*(ay2-ay1) + (bx2-bx1)*(by2-by1) - max(min(ax2,bx2)-max(ax1,bx1), 0) * max(min(ay2,by2)-max(ay1,by1), 0) \ No newline at end of file diff --git a/questions/relative-sort-array/Solution.py b/questions/relative-sort-array/Solution.py new file mode 100644 index 0000000..17ed630 --- /dev/null +++ b/questions/relative-sort-array/Solution.py @@ -0,0 +1,41 @@ +""" + +Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1. +Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that do not appear in arr2 should be placed at the end of arr1 in ascending order. +  +Example 1: + +Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6] +Output: [2,2,2,1,4,3,3,9,6,7,19] + +Example 2: + +Input: arr1 = [28,6,22,8,44,17], arr2 = [22,28,8,6] +Output: [22,28,8,6,17,44] + +  +Constraints: + +1 <= arr1.length, arr2.length <= 1000 +0 <= arr1[i], arr2[i] <= 1000 +All the elements of arr2 are distinct. +Each arr2[i] is in arr1. + + +""" + + +class Solution: + def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]: + ss = set(arr2) + tr = {} + ret = [] + for a in arr1: + if a not in ss: + ret.append(a) + continue + tr[a] = tr.get(a, 0) + 1 + ret.sort(key=lambda x: -x) + for b in reversed(arr2): + ret.extend([b] * tr.get(b, 0)) + return ret[::-1] \ No newline at end of file diff --git a/questions/remove-stones-to-minimize-the-total/Solution.py b/questions/remove-stones-to-minimize-the-total/Solution.py new file mode 100644 index 0000000..100f44f --- /dev/null +++ b/questions/remove-stones-to-minimize-the-total/Solution.py @@ -0,0 +1,50 @@ +""" + +You are given a 0-indexed integer array piles, where piles[i] represents the number of stones in the ith pile, and an integer k. You should apply the following operation exactly k times: + +Choose any piles[i] and remove floor(piles[i] / 2) stones from it. + +Notice that you can apply the operation on the same pile more than once. +Return the minimum possible total number of stones remaining after applying the k operations. +floor(x) is the greatest integer that is smaller than or equal to x (i.e., rounds x down). +  +Example 1: + +Input: piles = [5,4,9], k = 2 +Output: 12 +Explanation: Steps of a possible scenario are: +- Apply the operation on pile 2. The resulting piles are [5,4,5]. +- Apply the operation on pile 0. The resulting piles are [3,4,5]. +The total number of stones in [3,4,5] is 12. + +Example 2: + +Input: piles = [4,3,6,7], k = 3 +Output: 12 +Explanation: Steps of a possible scenario are: +- Apply the operation on pile 2. The resulting piles are [4,3,3,7]. +- Apply the operation on pile 3. The resulting piles are [4,3,3,4]. +- Apply the operation on pile 0. The resulting piles are [2,3,3,4]. +The total number of stones in [2,3,3,4] is 12. + +  +Constraints: + +1 <= piles.length <= 105 +1 <= piles[i] <= 104 +1 <= k <= 105 + + +""" + + +class Solution: + def minStoneSum(self, piles: List[int], k: int) -> int: + ps = [-a for a in piles] + heapq.heapify(ps) + while k > 0: + curr = -heapq.heappop(ps) + curr = curr - curr // 2 + heapq.heappush(ps, -curr) + k -= 1 + return sum([-a for a in ps]) \ No newline at end of file diff --git a/questions/sales-analysis-iii/Solution.sql b/questions/sales-analysis-iii/Solution.sql new file mode 100644 index 0000000..17ab9ca --- /dev/null +++ b/questions/sales-analysis-iii/Solution.sql @@ -0,0 +1,108 @@ +/* + +Table: Product + ++--------------+---------+ +| Column Name | Type | ++--------------+---------+ +| product_id | int | +| product_name | varchar | +| unit_price | int | ++--------------+---------+ +product_id is the primary key of this table. +Each row of this table indicates the name and the price of each product. + +Table: Sales + ++-------------+---------+ +| Column Name | Type | ++-------------+---------+ +| seller_id | int | +| product_id | int | +| buyer_id | int | +| sale_date | date | +| quantity | int | +| price | int | ++-------------+---------+ +This table has no primary key, it can have repeated rows. +product_id is a foreign key to the Product table. +Each row of this table contains some information about one sale. + +  +Write an SQL query that reports the products that were only sold in the first quarter of 2019. That is, between 2019-01-01 and 2019-03-31 inclusive. +Return the result table in any order. +The query result format is in the following example. +  +Example 1: + +Input: +Product table: ++------------+--------------+------------+ +| product_id | product_name | unit_price | ++------------+--------------+------------+ +| 1 | S8 | 1000 | +| 2 | G4 | 800 | +| 3 | iPhone | 1400 | ++------------+--------------+------------+ +Sales table: ++-----------+------------+----------+------------+----------+-------+ +| seller_id | product_id | buyer_id | sale_date | quantity | price | ++-----------+------------+----------+------------+----------+-------+ +| 1 | 1 | 1 | 2019-01-21 | 2 | 2000 | +| 1 | 2 | 2 | 2019-02-17 | 1 | 800 | +| 2 | 2 | 3 | 2019-06-02 | 1 | 800 | +| 3 | 3 | 4 | 2019-05-13 | 2 | 2800 | ++-----------+------------+----------+------------+----------+-------+ +Output: ++-------------+--------------+ +| product_id | product_name | ++-------------+--------------+ +| 1 | S8 | ++-------------+--------------+ +Explanation: +The product with id 1 was only sold in the spring of 2019. +The product with id 2 was sold in the spring of 2019 but was also sold after the spring of 2019. +The product with id 3 was sold after spring 2019. +We return only product 1 as it is the product that was only sold in the spring of 2019. + + +*/ + + +# Write your MySQL query statement below +select + product.product_id, + product.product_name +from + ( + select + sales1.product_id + from + ( + select + product_id, + count(1) as cnt + from + sales + where + sale_date >= '2019-01-01' + and sale_date <= '2019-03-31' + group by + product_id + ) as sales1, + ( + select + product_id, + count(1) as cnt + from + sales + group by + product_id + ) as sales2 + where + sales1.product_id = sales2.product_id + and sales1.cnt = sales2.cnt + ) as ss, + product +where + product.product_id = ss.product_id; diff --git a/questions/sales-person/Solution.sql b/questions/sales-person/Solution.sql new file mode 100644 index 0000000..0457ddf --- /dev/null +++ b/questions/sales-person/Solution.sql @@ -0,0 +1,102 @@ +/* + +Table: SalesPerson + ++-----------------+---------+ +| Column Name | Type | ++-----------------+---------+ +| sales_id | int | +| name | varchar | +| salary | int | +| commission_rate | int | +| hire_date | date | ++-----------------+---------+ +sales_id is the primary key column for this table. +Each row of this table indicates the name and the ID of a salesperson alongside their salary, commission rate, and hire date. + +  +Table: Company + ++-------------+---------+ +| Column Name | Type | ++-------------+---------+ +| com_id | int | +| name | varchar | +| city | varchar | ++-------------+---------+ +com_id is the primary key column for this table. +Each row of this table indicates the name and the ID of a company and the city in which the company is located. + +  +Table: Orders + ++-------------+------+ +| Column Name | Type | ++-------------+------+ +| order_id | int | +| order_date | date | +| com_id | int | +| sales_id | int | +| amount | int | ++-------------+------+ +order_id is the primary key column for this table. +com_id is a foreign key to com_id from the Company table. +sales_id is a foreign key to sales_id from the SalesPerson table. +Each row of this table contains information about one order. This includes the ID of the company, the ID of the salesperson, the date of the order, and the amount paid. + +  +Write an SQL query to report the names of all the salespersons who did not have any orders related to the company with the name "RED". +Return the result table in any order. +The query result format is in the following example. +  +Example 1: + +Input: +SalesPerson table: ++----------+------+--------+-----------------+------------+ +| sales_id | name | salary | commission_rate | hire_date | ++----------+------+--------+-----------------+------------+ +| 1 | John | 100000 | 6 | 4/1/2006 | +| 2 | Amy | 12000 | 5 | 5/1/2010 | +| 3 | Mark | 65000 | 12 | 12/25/2008 | +| 4 | Pam | 25000 | 25 | 1/1/2005 | +| 5 | Alex | 5000 | 10 | 2/3/2007 | ++----------+------+--------+-----------------+------------+ +Company table: ++--------+--------+----------+ +| com_id | name | city | ++--------+--------+----------+ +| 1 | RED | Boston | +| 2 | ORANGE | New York | +| 3 | YELLOW | Boston | +| 4 | GREEN | Austin | ++--------+--------+----------+ +Orders table: ++----------+------------+--------+----------+--------+ +| order_id | order_date | com_id | sales_id | amount | ++----------+------------+--------+----------+--------+ +| 1 | 1/1/2014 | 3 | 4 | 10000 | +| 2 | 2/1/2014 | 4 | 5 | 5000 | +| 3 | 3/1/2014 | 1 | 1 | 50000 | +| 4 | 4/1/2014 | 1 | 4 | 25000 | ++----------+------------+--------+----------+--------+ +Output: ++------+ +| name | ++------+ +| Amy | +| Mark | +| Alex | ++------+ +Explanation: +According to orders 3 and 4 in the Orders table, it is easy to tell that only salesperson John and Pam have sales to company RED, so we report all the other names in the table salesperson. + + +*/ + + +# Write your MySQL query statement below +select sp.name from salesperson sp where sp.sales_id not in +( + select orders.sales_id from orders, company where orders.com_id = company.com_id and company.name = 'RED' +); diff --git a/questions/shift-2d-grid/Solution.py b/questions/shift-2d-grid/Solution.py new file mode 100644 index 0000000..bfceb5f --- /dev/null +++ b/questions/shift-2d-grid/Solution.py @@ -0,0 +1,51 @@ +""" + +Given a 2D grid of size m x n and an integer k. You need to shift the grid k times. +In one shift operation: + +Element at grid[i][j] moves to grid[i][j + 1]. +Element at grid[i][n - 1] moves to grid[i + 1][0]. +Element at grid[m - 1][n - 1] moves to grid[0][0]. + +Return the 2D grid after applying shift operation k times. +  +Example 1: + + +Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1 +Output: [[9,1,2],[3,4,5],[6,7,8]] + +Example 2: + + +Input: grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4 +Output: [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]] + +Example 3: + +Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 9 +Output: [[1,2,3],[4,5,6],[7,8,9]] + +  +Constraints: + +m == grid.length +n == grid[i].length +1 <= m <= 50 +1 <= n <= 50 +-1000 <= grid[i][j] <= 1000 +0 <= k <= 100 + + +""" + + +class Solution: + def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]: + ret = [[None for _ in grid[0]] for _ in grid] + for i, row in enumerate(grid): + for j, elem in enumerate(row): + r, c = divmod(i * len(row) + j + k, len(row)) + r = r % len(grid) + ret[r][c] = elem + return ret diff --git a/questions/shortest-completing-word/Solution.py b/questions/shortest-completing-word/Solution.py new file mode 100644 index 0000000..350fb32 --- /dev/null +++ b/questions/shortest-completing-word/Solution.py @@ -0,0 +1,58 @@ +""" + +Given a string licensePlate and an array of strings words, find the shortest completing word in words. +A completing word is a word that contains all the letters in licensePlate. Ignore numbers and spaces in licensePlate, and treat letters as case insensitive. If a letter appears more than once in licensePlate, then it must appear in the word the same number of times or more. +For example, if licensePlate = "aBc 12c", then it contains letters 'a', 'b' (ignoring case), and 'c' twice. Possible completing words are "abccdef", "caaacab", and "cbca". +Return the shortest completing word in words. It is guaranteed an answer exists. If there are multiple shortest completing words, return the first one that occurs in words. +  +Example 1: + +Input: licensePlate = "1s3 PSt", words = ["step","steps","stripe","stepple"] +Output: "steps" +Explanation: licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'. +"step" contains 't' and 'p', but only contains 1 's'. +"steps" contains 't', 'p', and both 's' characters. +"stripe" is missing an 's'. +"stepple" is missing an 's'. +Since "steps" is the only word containing all the letters, that is the answer. + +Example 2: + +Input: licensePlate = "1s3 456", words = ["looks","pest","stew","show"] +Output: "pest" +Explanation: licensePlate only contains the letter 's'. All the words contain 's', but among these "pest", "stew", and "show" are shortest. The answer is "pest" because it is the word that appears earliest of the 3. + +  +Constraints: + +1 <= licensePlate.length <= 7 +licensePlate contains digits, letters (uppercase or lowercase), or space ' '. +1 <= words.length <= 1000 +1 <= words[i].length <= 15 +words[i] consists of lower case English letters. + + +""" + + +class Solution: + def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str: + tr = {} + for c in licensePlate: + if not c.isalpha(): + continue + c = c.lower() + tr[c] = tr.get(c, 0) + 1 + ret, l = None, None + for word in words: + dr = dict(tr) + for c in word: + if c in dr: + dr[c] -= 1 + if dr[c] == 0: + del dr[c] + if not dr: + if l is None or l > len(word): + ret = word + l = len(word) + return ret diff --git a/questions/single-threaded-cpu/Solution.py b/questions/single-threaded-cpu/Solution.py new file mode 100644 index 0000000..0dc6fdd --- /dev/null +++ b/questions/single-threaded-cpu/Solution.py @@ -0,0 +1,72 @@ +""" + +You are given n​​​​​​ tasks labeled from 0 to n - 1 represented by a 2D integer array tasks, where tasks[i] = [enqueueTimei, processingTimei] means that the i​​​​​​th​​​​ task will be available to process at enqueueTimei and will take processingTimei to finish processing. +You have a single-threaded CPU that can process at most one task at a time and will act in the following way: + +If the CPU is idle and there are no available tasks to process, the CPU remains idle. +If the CPU is idle and there are available tasks, the CPU will choose the one with the shortest processing time. If multiple tasks have the same shortest processing time, it will choose the task with the smallest index. +Once a task is started, the CPU will process the entire task without stopping. +The CPU can finish a task then start a new one instantly. + +Return the order in which the CPU will process the tasks. +  +Example 1: + +Input: tasks = [[1,2],[2,4],[3,2],[4,1]] +Output: [0,2,3,1] +Explanation: The events go as follows: +- At time = 1, task 0 is available to process. Available tasks = {0}. +- Also at time = 1, the idle CPU starts processing task 0. Available tasks = {}. +- At time = 2, task 1 is available to process. Available tasks = {1}. +- At time = 3, task 2 is available to process. Available tasks = {1, 2}. +- Also at time = 3, the CPU finishes task 0 and starts processing task 2 as it is the shortest. Available tasks = {1}. +- At time = 4, task 3 is available to process. Available tasks = {1, 3}. +- At time = 5, the CPU finishes task 2 and starts processing task 3 as it is the shortest. Available tasks = {1}. +- At time = 6, the CPU finishes task 3 and starts processing task 1. Available tasks = {}. +- At time = 10, the CPU finishes task 1 and becomes idle. + +Example 2: + +Input: tasks = [[7,10],[7,12],[7,5],[7,4],[7,2]] +Output: [4,3,2,0,1] +Explanation: The events go as follows: +- At time = 7, all the tasks become available. Available tasks = {0,1,2,3,4}. +- Also at time = 7, the idle CPU starts processing task 4. Available tasks = {0,1,2,3}. +- At time = 9, the CPU finishes task 4 and starts processing task 3. Available tasks = {0,1,2}. +- At time = 13, the CPU finishes task 3 and starts processing task 2. Available tasks = {0,1}. +- At time = 18, the CPU finishes task 2 and starts processing task 0. Available tasks = {1}. +- At time = 28, the CPU finishes task 0 and starts processing task 1. Available tasks = {}. +- At time = 40, the CPU finishes task 1 and becomes idle. + +  +Constraints: + +tasks.length == n +1 <= n <= 105 +1 <= enqueueTimei, processingTimei <= 109 + + +""" + + +class Solution: + def getOrder(self, tasks: List[List[int]]) -> List[int]: + ts = [] + available = [] + for i, t in enumerate(tasks): + ts.append((t[0], t[1], i)) + ts = deque(sorted(ts)) + ret = [] + curr = ts[0][0] + while ts or available: + while ts and ts[0][0] <= curr: + et, pt, idx = ts.popleft() + heapq.heappush(available, (pt, idx)) + if not available and ts: + et, pt, idx = ts.popleft() + curr = et + available.append((pt, idx)) + pt, idx = heapq.heappop(available) + curr += pt + ret.append(idx) + return ret diff --git a/questions/split-a-string-in-balanced-strings/Solution.py b/questions/split-a-string-in-balanced-strings/Solution.py new file mode 100644 index 0000000..733884b --- /dev/null +++ b/questions/split-a-string-in-balanced-strings/Solution.py @@ -0,0 +1,49 @@ +""" + +Balanced strings are those that have an equal quantity of 'L' and 'R' characters. +Given a balanced string s, split it into some number of substrings such that: + +Each substring is balanced. + +Return the maximum number of balanced strings you can obtain. +  +Example 1: + +Input: s = "RLRRLLRLRL" +Output: 4 +Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'. + +Example 2: + +Input: s = "RLRRRLLRLL" +Output: 2 +Explanation: s can be split into "RL", "RRRLLRLL", each substring contains same number of 'L' and 'R'. +Note that s cannot be split into "RL", "RR", "RL", "LR", "LL", because the 2nd and 5th substrings are not balanced. +Example 3: + +Input: s = "LLLLRRRR" +Output: 1 +Explanation: s can be split into "LLLLRRRR". + +  +Constraints: + +2 <= s.length <= 1000 +s[i] is either 'L' or 'R'. +s is a balanced string. + + +""" + + +class Solution: + def balancedStringSplit(self, s: str) -> int: + ret, count = 0, 0 + for a in s: + if a == 'L': + count += 1 + else: + count -= 1 + if count == 0: + ret += 1 + return ret diff --git a/questions/unique-number-of-occurrences/Solution.py b/questions/unique-number-of-occurrences/Solution.py new file mode 100644 index 0000000..064d0e5 --- /dev/null +++ b/questions/unique-number-of-occurrences/Solution.py @@ -0,0 +1,34 @@ +""" + +Given an array of integers arr, return true if the number of occurrences of each value in the array is unique or false otherwise. +  +Example 1: + +Input: arr = [1,2,2,1,1,3] +Output: true +Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences. +Example 2: + +Input: arr = [1,2] +Output: false + +Example 3: + +Input: arr = [-3,0,1,-3,1,1,1,-3,10,0] +Output: true + +  +Constraints: + +1 <= arr.length <= 1000 +-1000 <= arr[i] <= 1000 + + +""" + + +class Solution: + def uniqueOccurrences(self, arr: List[int]) -> bool: + counter = Counter(arr) + freqs = list(counter.values()) + return len(freqs) == len(set(freqs)) \ No newline at end of file diff --git a/questions/unique-paths-iii/Solution.py b/questions/unique-paths-iii/Solution.py new file mode 100644 index 0000000..548ee2c --- /dev/null +++ b/questions/unique-paths-iii/Solution.py @@ -0,0 +1,89 @@ +""" + +You are given an m x n integer array grid where grid[i][j] could be: + +1 representing the starting square. There is exactly one starting square. +2 representing the ending square. There is exactly one ending square. +0 representing empty squares we can walk over. +-1 representing obstacles that we cannot walk over. + +Return the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once. +  +Example 1: + + +Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,2,-1]] +Output: 2 +Explanation: We have the following two paths: +1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2) +2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2) + +Example 2: + + +Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,0,2]] +Output: 4 +Explanation: We have the following four paths: +1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3) +2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3) +3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3) +4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3) + +Example 3: + + +Input: grid = [[0,1],[2,0]] +Output: 0 +Explanation: There is no path that walks over every empty square exactly once. +Note that the starting and ending square can be anywhere in the grid. + +  +Constraints: + +m == grid.length +n == grid[i].length +1 <= m, n <= 20 +1 <= m * n <= 20 +-1 <= grid[i][j] <= 2 +There is exactly one starting cell and one ending cell. + + +""" + + +class Solution: + def uniquePathsIII(self, grid: List[List[int]]) -> int: + state = 0 + state_len = 0 + total_len = len(grid) * len(grid[0]) + start = None + for i, row in enumerate(grid): + for j, elem in enumerate(row): + if elem == -1: + state = state | (1 << (i * len(row) + j)) + state_len += 1 + elif elem == 1: + start = (i, j) + stk = [(start, state, state_len)] + ret = 0 + while stk: + curr, curr_state, curr_len = stk.pop() + mask = (1 << (curr[0] * len(grid[0]) + curr[1])) + if curr_state & mask != 0: + continue + curr_state = curr_state | mask + curr_len += 1 + if grid[curr[0]][curr[1]] == 2: + if curr_len == total_len: + ret += 1 + continue + elif grid[curr[0]][curr[1]] == -1: + continue + for dy, dx in ((-1, 0), (1, 0), (0, -1), (0, 1)): + ny, nx = curr[0] + dy, curr[1] + dx + if not (0 <= ny < len(grid)): + continue + if not (0 <= nx < len(grid[0])): + continue + stk.append(((ny, nx), curr_state, curr_len)) + return ret diff --git a/questions/user-activity-for-the-past-30-days-i/Solution.sql b/questions/user-activity-for-the-past-30-days-i/Solution.sql new file mode 100644 index 0000000..2937ce5 --- /dev/null +++ b/questions/user-activity-for-the-past-30-days-i/Solution.sql @@ -0,0 +1,58 @@ +/* + +Table: Activity + ++---------------+---------+ +| Column Name | Type | ++---------------+---------+ +| user_id | int | +| session_id | int | +| activity_date | date | +| activity_type | enum | ++---------------+---------+ +There is no primary key for this table, it may have duplicate rows. +The activity_type column is an ENUM of type ('open_session', 'end_session', 'scroll_down', 'send_message'). +The table shows the user activities for a social media website. +Note that each session belongs to exactly one user. + +  +Write an SQL query to find the daily active user count for a period of 30 days ending 2019-07-27 inclusively. A user was active on someday if they made at least one activity on that day. +Return the result table in any order. +The query result format is in the following example. +  +Example 1: + +Input: +Activity table: ++---------+------------+---------------+---------------+ +| user_id | session_id | activity_date | activity_type | ++---------+------------+---------------+---------------+ +| 1 | 1 | 2019-07-20 | open_session | +| 1 | 1 | 2019-07-20 | scroll_down | +| 1 | 1 | 2019-07-20 | end_session | +| 2 | 4 | 2019-07-20 | open_session | +| 2 | 4 | 2019-07-21 | send_message | +| 2 | 4 | 2019-07-21 | end_session | +| 3 | 2 | 2019-07-21 | open_session | +| 3 | 2 | 2019-07-21 | send_message | +| 3 | 2 | 2019-07-21 | end_session | +| 4 | 3 | 2019-06-25 | open_session | +| 4 | 3 | 2019-06-25 | end_session | ++---------+------------+---------------+---------------+ +Output: ++------------+--------------+ +| day | active_users | ++------------+--------------+ +| 2019-07-20 | 2 | +| 2019-07-21 | 2 | ++------------+--------------+ +Explanation: Note that we do not care about days with zero active users. + + +*/ + + +# Write your MySQL query statement below +select activity_date as day, count(user_id) as active_users from ( + select activity_date, user_id from Activity where activity_date > DATE_ADD('2019-07-27', INTERVAL - 30 DAY) and activity_date <= '2019-07-27' group by activity_date, user_id +) filtered group by activity_date order by activity_date; \ No newline at end of file diff --git a/questions/valid-boomerang/Solution.py b/questions/valid-boomerang/Solution.py new file mode 100644 index 0000000..7063012 --- /dev/null +++ b/questions/valid-boomerang/Solution.py @@ -0,0 +1,30 @@ +""" + +Given an array points where points[i] = [xi, yi] represents a point on the X-Y plane, return true if these points are a boomerang. +A boomerang is a set of three points that are all distinct and not in a straight line. +  +Example 1: +Input: points = [[1,1],[2,3],[3,2]] +Output: true +Example 2: +Input: points = [[1,1],[2,2],[3,3]] +Output: false + +  +Constraints: + +points.length == 3 +points[i].length == 2 +0 <= xi, yi <= 100 + + +""" + + +class Solution: + def isBoomerang(self, points: List[List[int]]) -> bool: + p1, p2, p3 = points + if p1 == p2 or p1 == p3 or p2 == p3: + return False + return (p2[1] - p1[1]) * (p3[0] - p1[0]) != (p3[1] - p1[1]) * (p2[0] - p1[0]) + \ No newline at end of file