diff --git a/README.md b/README.md index 8b2a506b9..36b180d26 100644 --- a/README.md +++ b/README.md @@ -24,47 +24,47 @@ If you would like to have collaborator permissions on the repo to merge your own Problem | C | C++ | C# | GO | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- -[217 - Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
+[217 - Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
[242 - Valid Anagram](https://leetcode.com/problems/valid-anagram/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
[1 - Two Sum](https://leetcode.com/problems/two-sum/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
[49 - Group Anagrams](https://leetcode.com/problems/group-anagrams/) |
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
[347 - Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) |
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
[238 - Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
-[36 - Valid Sudoku](https://leetcode.com/problems/valid-sudoku/) |
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
✔️
+[36 - Valid Sudoku](https://leetcode.com/problems/valid-sudoku/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
✔️
[271 - Encode and Decode Strings](https://leetcode.com/problems/encode-and-decode-strings/) |
|
✔️
|
✔️
|
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
|
✔️
|
[128 - Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/) |
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
[125 - Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
[167 - Two Sum II](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
[15 - 3Sum](https://leetcode.com/problems/3sum/) |
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
[11 - Container with Most Water](https://leetcode.com/problems/container-with-most-water/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
-[42 - Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/) |
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
✔️
|
✔️
+[42 - Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
✔️
|
✔️
[121 - Best Time to Buy & Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
[3 - Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
-[424 - Longest Repeating Character Replacement](https://leetcode.com/problems/longest-repeating-character-replacement/) |
|
✔️
|
✔️
|
|
✔️
|
✔️
|
|
✔️
|
✔️
|
|
|
|
✔️
-[567 - Permutation in String](https://leetcode.com/problems/permutation-in-string/) |
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
|
✔️
+[424 - Longest Repeating Character Replacement](https://leetcode.com/problems/longest-repeating-character-replacement/) |
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
|
|
✔️
|
✔️
|
|
|
|
✔️
+[567 - Permutation in String](https://leetcode.com/problems/permutation-in-string/) |
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
|
✔️
[76 - Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/) |
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
|
✔️
[239 - Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/) |
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
|
[20 - Valid Parentheses](https://leetcode.com/problems/valid-parentheses/) |
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
✔️
|
✔️
[155 - Min Stack](https://leetcode.com/problems/min-stack/) |
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
✔️
-[150 - Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/) |
|
✔️
|
|
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
✔️
|
✔️
+[150 - Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/) |
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
✔️
|
✔️
[22 - Generate Parentheses](https://leetcode.com/problems/generate-parentheses/) |
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
|
✔️
[739 - Daily Temperatures](https://leetcode.com/problems/daily-temperatures/) |
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
|
✔️
[853 - Car Fleet](https://leetcode.com/problems/car-fleet/) |
|
✔️
|
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
✔️
[84 - Largest Rectangle in Histogram](https://leetcode.com/problems/largest-rectangle-in-histogram/) |
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
|
✔️
[704 - Binary Search](https://leetcode.com/problems/binary-search/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
✔️
|
✔️
[74 - Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
✔️
|
✔️
-[875 - Koko Eating Bananas](https://leetcode.com/problems/koko-eating-bananas/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
|
✔️
-[33 - Search Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/) |
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
✔️
|
✔️
+[875 - Koko Eating Bananas](https://leetcode.com/problems/koko-eating-bananas/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
✔️
|
✔️
+[33 - Search Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
✔️
|
✔️
[153 - Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/) |
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
✔️
|
✔️
[981 - Time Based Key-Value Store](https://leetcode.com/problems/time-based-key-value-store/) |
|
✔️
|
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
✔️
[4 - Find Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) |
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
|
✔️
[206 - Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
✔️
[21 - Merge Two Linked Lists](https://leetcode.com/problems/merge-two-sorted-lists/) |
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
✔️
|
✔️
-[143 - Reorder List](https://leetcode.com/problems/reorder-list/) |
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
|
✔️
+[143 - Reorder List](https://leetcode.com/problems/reorder-list/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
|
✔️
[19 - Remove Nth Node from End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/) |
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
|
✔️
[138 - Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/) |
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
✔️
|
✔️
[2 - Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) |
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
✔️
|
|
✔️
-[141 - Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
✔️
+[141 - Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
✔️
|
|
✔️
[287 - Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/) |
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
✔️
|
✔️
[146 - LRU Cache](https://leetcode.com/problems/lru-cache/) |
|
✔️
|
|
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
|
[23 - Merge K Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) |
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
|
✔️
@@ -80,9 +80,9 @@ If you would like to have collaborator permissions on the repo to merge your own [199 - Binary Tree Right Side View](https://leetcode.com/problems/binary-tree-right-side-view/) |
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
✔️
|
✔️
[1448 - Count Good Nodes in a Binary Tree](https://leetcode.com/problems/count-good-nodes-in-binary-tree/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
✔️
|
✔️
[98 - Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/) |
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
✔️
|
✔️
-[230 - Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/) |
|
✔️
|
✔️
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
✔️
+[230 - Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/) |
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
|
✔️
[105 - Construct Tree from Preorder and Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/) |
|
✔️
|
|
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
|
✔️
-[124 - Binary Tree Max Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/) |
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
|
✔️
+[124 - Binary Tree Max Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
|
✔️
[297 - Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/) |
|
✔️
|
|
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
|
[208 - Implement Trie](https://leetcode.com/problems/implement-trie-prefix-tree/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
✔️
[211 - Design Add and Search Word Data Structure](https://leetcode.com/problems/design-add-and-search-words-data-structure/) |
|
✔️
|
|
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
✔️
@@ -93,7 +93,7 @@ If you would like to have collaborator permissions on the repo to merge your own [215 - Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) |
|
✔️
|
✔️
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
✔️
[621 - Task Scheduler](https://leetcode.com/problems/task-scheduler/) |
|
✔️
|
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
✔️
[355 - Design Twitter](https://leetcode.com/problems/design-twitter/) |
|
✔️
|
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
-[295 - Find Median from Data Stream](https://leetcode.com/problems/find-median-from-data-stream/) |
|
✔️
|
|
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
|
+[295 - Find Median from Data Stream](https://leetcode.com/problems/find-median-from-data-stream/) |
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
|
[78 - Subsets](https://leetcode.com/problems/subsets/) |
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
✔️
|
✔️
[39 - Combination Sum](https://leetcode.com/problems/combination-sum/) |
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
✔️
[46 - Permutations](https://leetcode.com/problems/permutations/) |
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
|
✔️
@@ -107,8 +107,8 @@ If you would like to have collaborator permissions on the repo to merge your own [133 - Clone Graph](https://leetcode.com/problems/clone-graph/) |
|
✔️
|
✔️
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
✔️
|
✔️
[695 - Max Area of Island](https://leetcode.com/problems/max-area-of-island/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
|
✔️
[417 - Pacific Atlantic Waterflow](https://leetcode.com/problems/pacific-atlantic-water-flow/) |
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
|
-[130 - Surrounded Regions](https://leetcode.com/problems/surrounded-regions/) |
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
✔️
|
-[994 - Rotting Oranges](https://leetcode.com/problems/rotting-oranges/) |
|
✔️
|
✔️
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
✔️
+[130 - Surrounded Regions](https://leetcode.com/problems/surrounded-regions/) |
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
✔️
|
✔️
+[994 - Rotting Oranges](https://leetcode.com/problems/rotting-oranges/) |
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
✔️
[286 - Walls and Gates](https://leetcode.com/problems/walls-and-gates/) |
|
✔️
|
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
[207 - Course Schedule](https://leetcode.com/problems/course-schedule/) |
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
✔️
|
✔️
[210 - Course Schedule II](https://leetcode.com/problems/course-schedule-ii/) |
|
✔️
|
✔️
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
✔️
@@ -129,14 +129,14 @@ If you would like to have collaborator permissions on the repo to merge your own [5 - Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/) |
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
✔️
[647 - Palindromic Substrings](https://leetcode.com/problems/palindromic-substrings/) |
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
✔️
[91 - Decode Ways](https://leetcode.com/problems/decode-ways/) |
|
✔️
|
✔️
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
✔️
-[322 - Coin Change](https://leetcode.com/problems/coin-change/) |
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
|
✔️
+[322 - Coin Change](https://leetcode.com/problems/coin-change/) |
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
|
✔️
[152 - Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray/) |
|
✔️
|
✔️
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
✔️
[139 - Word Break](https://leetcode.com/problems/word-break/) |
|
✔️
|
✔️
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
✔️
[300 - Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence/) |
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
✔️
[416 - Partition Equal Subset Sum](https://leetcode.com/problems/partition-equal-subset-sum/) |
|
✔️
|
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
[62 - Unique Paths](https://leetcode.com/problems/unique-paths/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
|
✔️
[1143 - Longest Common Subsequence](https://leetcode.com/problems/longest-common-subsequence/) |
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
✔️
|
✔️
-[309 - Best Time to Buy/Sell Stock With Cooldown](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/) |
|
✔️
|
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
+[309 - Best Time to Buy/Sell Stock With Cooldown](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/) |
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
✔️
|
✔️
[518 - Coin Change II](https://leetcode.com/problems/coin-change-2/) |
|
✔️
|
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
✔️
[494 - Target Sum](https://leetcode.com/problems/target-sum/) |
|
✔️
|
|
✔️
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
✔️
[97 - Interleaving String](https://leetcode.com/problems/interleaving-string/) |
|
✔️
|
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
✔️
@@ -145,34 +145,34 @@ If you would like to have collaborator permissions on the repo to merge your own [72 - Edit Distance](https://leetcode.com/problems/edit-distance/) |
|
✔️
|
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
[312 - Burst Balloons](https://leetcode.com/problems/burst-balloons/) |
|
✔️
|
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
✔️
[10 - Regular Expression Matching](https://leetcode.com/problems/regular-expression-matching/) |
|
✔️
|
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
✔️
-[53 - Maximum Subarray](https://leetcode.com/problems/maximum-subarray/) |
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
✔️
|
✔️
-[55 - Jump Game](https://leetcode.com/problems/jump-game/) |
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
✔️
|
✔️
-[45 - Jump Game II](https://leetcode.com/problems/jump-game-ii/) |
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
✔️
|
✔️
-[134 - Gas Station](https://leetcode.com/problems/gas-station/) |
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
✔️
|
✔️
+[53 - Maximum Subarray](https://leetcode.com/problems/maximum-subarray/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
✔️
|
✔️
+[55 - Jump Game](https://leetcode.com/problems/jump-game/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
✔️
|
✔️
+[45 - Jump Game II](https://leetcode.com/problems/jump-game-ii/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
✔️
|
✔️
+[134 - Gas Station](https://leetcode.com/problems/gas-station/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
✔️
|
✔️
[846 - Hand of Straights](https://leetcode.com/problems/hand-of-straights/) |
|
✔️
|
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
✔️
[1899 - Merge Triplets to Form Target Triplet](https://leetcode.com/problems/merge-triplets-to-form-target-triplet/) |
|
✔️
|
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
✔️
[763 - Partition Labels](https://leetcode.com/problems/partition-labels/) |
|
✔️
|
|
✔️
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
[678 - Valid Parenthesis String](https://leetcode.com/problems/valid-parenthesis-string/) |
✔️
|
✔️
|
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
✔️
-[57 - Insert Interval](https://leetcode.com/problems/insert-interval/) |
|
✔️
|
✔️
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
-[56 - Merge Intervals](https://leetcode.com/problems/merge-intervals/) |
|
✔️
|
|
✔️
|
✔️
|
✔️
|
|
✔️
|
|
|
✔️
|
|
-[435 - Non-Overlapping Intervals](https://leetcode.com/problems/non-overlapping-intervals/) |
|
✔️
|
|
✔️
|
✔️
|
✔️
|
|
✔️
|
|
|
✔️
|
|
+[57 - Insert Interval](https://leetcode.com/problems/insert-interval/) |
|
✔️
|
✔️
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
✔️
+[56 - Merge Intervals](https://leetcode.com/problems/merge-intervals/) |
|
✔️
|
|
✔️
|
✔️
|
✔️
|
|
✔️
|
|
|
✔️
|
|
✔️
+[435 - Non-Overlapping Intervals](https://leetcode.com/problems/non-overlapping-intervals/) |
|
✔️
|
|
✔️
|
✔️
|
✔️
|
|
✔️
|
|
|
✔️
|
|
✔️
[252 - Meeting Rooms](https://leetcode.com/problems/meeting-rooms/) |
|
✔️
|
✔️
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
[253 - Meeting Rooms II](https://leetcode.com/problems/meeting-rooms-ii/) |
|
✔️
|
✔️
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
[1851 - Minimum Interval to Include Each Query](https://leetcode.com/problems/minimum-interval-to-include-each-query/) |
|
✔️
|
|
|
✔️
|
|
|
✔️
|
|
|
|
|
-[48 - Rotate Image](https://leetcode.com/problems/rotate-image/) |
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
✔️
|
✔️
-[54 - Spiral Matrix](https://leetcode.com/problems/spiral-matrix/) |
|
✔️
|
|
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
|
✔️
-[73 - Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/) |
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
-[202 - Happy Number](https://leetcode.com/problems/happy-number/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
✔️
|
|
|
|
✔️
|
✔️
-[66 - Plus One](https://leetcode.com/problems/plus-one/) |
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
|
✔️
+[48 - Rotate Image](https://leetcode.com/problems/rotate-image/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
✔️
|
|
|
|
✔️
|
✔️
+[54 - Spiral Matrix](https://leetcode.com/problems/spiral-matrix/) |
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
|
✔️
+[73 - Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
✔️
+[202 - Happy Number](https://leetcode.com/problems/happy-number/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
✔️
|
✔️
+[66 - Plus One](https://leetcode.com/problems/plus-one/) |
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
|
✔️
|
✔️
[50 - Pow(x, n)](https://leetcode.com/problems/powx-n/) |
✔️
|
✔️
|
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
✔️
|
✔️
[43 - Multiply Strings](https://leetcode.com/problems/multiply-strings/) |
|
✔️
|
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
✔️
|
✔️
[2013 - Detect Squares](https://leetcode.com/problems/detect-squares/) |
|
✔️
|
|
|
✔️
|
✔️
|
|
✔️
|
|
|
|
|
[136 - Single Number](https://leetcode.com/problems/single-number/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
✔️
|
✔️
-[191 - Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/) |
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
✔️
|
✔️
-[338 - Counting Bits](https://leetcode.com/problems/counting-bits/) |
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
✔️
|
✔️
-[190 - Reverse Bits](https://leetcode.com/problems/reverse-bits/) |
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
✔️
|
✔️
-[268 - Missing Number](https://leetcode.com/problems/missing-number/) |
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
✔️
|
✔️
-[371 - Sum of Two Integers](https://leetcode.com/problems/sum-of-two-integers/) |
✔️
|
✔️
|
✔️
|
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
✔️
|
✔️
+[191 - Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
✔️
|
✔️
+[338 - Counting Bits](https://leetcode.com/problems/counting-bits/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
✔️
|
✔️
+[190 - Reverse Bits](https://leetcode.com/problems/reverse-bits/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
✔️
|
✔️
+[268 - Missing Number](https://leetcode.com/problems/missing-number/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
✔️
|
✔️
+[371 - Sum of Two Integers](https://leetcode.com/problems/sum-of-two-integers/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
✔️
|
✔️
[7 - Reverse Integer](https://leetcode.com/problems/reverse-integer/) |
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
✔️
|
|
|
✔️
|
✔️
--- diff --git a/c/143-Reorder-List.c b/c/143-Reorder-List.c new file mode 100644 index 000000000..219bca75e --- /dev/null +++ b/c/143-Reorder-List.c @@ -0,0 +1,61 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * struct ListNode *next; + * }; + */ + +struct ListNode* reverse(struct ListNode* head) { + struct ListNode* prev = NULL; + struct ListNode* curr = head; + struct ListNode* next = curr->next; + + while (curr != NULL) { + next = curr->next; + curr->next = prev; + prev = curr; + curr = next; + } + + return prev; +} + +void merge(struct ListNode* l1, struct ListNode* l2) { + while (l1 != NULL) { + struct ListNode* p1 = l1->next; + struct ListNode* p2 = l2->next; + + l1->next = l2; + if (p1 == NULL) { + break; + } + l2->next = p1; + + l1 = p1; + l2 = p2; + } +} + +void reorderList(struct ListNode* head){ + if (head->next == NULL) { + return; + } + + struct ListNode* prev = NULL; + struct ListNode* slow = head; + struct ListNode* fast = head; + + while (fast != NULL && fast->next != NULL) { + prev = slow; + slow = slow->next; + fast = fast->next->next; + } + + prev->next = NULL; + + struct ListNode* l1 = head; + struct ListNode* l2 = reverse(slow); + + merge(l1, l2); +} \ No newline at end of file diff --git a/c/309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.c b/c/309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.c new file mode 100644 index 000000000..2e9eb7b2f --- /dev/null +++ b/c/309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.c @@ -0,0 +1,18 @@ +int maxProfit(int* prices, int pricesSize){ + int sold = 0; + int hold = INT_MIN; + int rest = 0; + + for (int i = 0; i < pricesSize; i++) { + int prevSold = sold; + sold = hold + prices[i]; + hold = max(hold, rest - prices[i]); + rest = max(rest, prevSold); + } + return max(sold, rest); +} + +// C doesn't have a built-in max function +int max(int a, int b) { + return (a > b) ? a : b; +} \ No newline at end of file diff --git a/c/322-Coin-Change.c b/c/322-Coin-Change.c new file mode 100644 index 000000000..c3a1ef107 --- /dev/null +++ b/c/322-Coin-Change.c @@ -0,0 +1,28 @@ +/* +Return the fewest number of coins that you need to make up that amount. +Time; O(nm) where n is the amount desired and m the number of coins +Space: O(n) +*/ + +int min(unsigned int a, int b) { + return a=coins[j] && cpt>dp[i-coins[j]]) + cpt = dp[i-coins[j]]; + } + if (cpt!=UINT_MAX) + dp[i] = cpt+1; + } + return dp[amount]==UINT_MAX?-1:dp[amount]; +} diff --git a/c/36-Valid-Sudoku.c b/c/36-Valid-Sudoku.c new file mode 100644 index 000000000..7b62c669e --- /dev/null +++ b/c/36-Valid-Sudoku.c @@ -0,0 +1,38 @@ +bool isValidSudoku(char** board, int boardSize, int* boardColSize){ + const int cnt = boardSize; + bool row[cnt][cnt]; + bool col[cnt][cnt]; + bool sub[cnt][cnt]; + + // initialize all the rows, cols, and sub-boxes to false + for (int r = 0; r < cnt; r++) { + for (int c = 0; c < cnt; c++) { + row[r][c] = false; + col[r][c] = false; + sub[r][c] = false; + } + } + + for (int r = 0; r < cnt; r++) { + for (int c = 0; c < cnt; c++) { + // pass if not a number + if (board[r][c] == '.') { + continue; + } + + // gets numerical index + int boardIndex = board[r][c] - '0' - 1; + int area = (r / 3) * 3 + (c / 3); + + // if number exists + if (row[r][boardIndex] || col[c][boardIndex] || sub[area][boardIndex]) { + return false; + } + + row[r][boardIndex] = true; + col[c][boardIndex] = true; + sub[area][boardIndex] = true; + } + } + return true; +} \ No newline at end of file diff --git a/c/424-Longest-Repeating-Character-Replacement.c b/c/424-Longest-Repeating-Character-Replacement.c new file mode 100644 index 000000000..5b6ea100b --- /dev/null +++ b/c/424-Longest-Repeating-Character-Replacement.c @@ -0,0 +1,20 @@ +int characterReplacement(char * s, int k){ + int count[26] = {0}; + int left = 0, right = 0, maxCount = 0; + + while (right < strlen(s)) { + count[s[right] - 'A']++; + maxCount = max(maxCount, count[s[right] - 'A']); + right++; + if (right - left - maxCount > k) { + count[s[left] - 'A']--; + left++; + } + } + return right - left; +} + +// C doesn't have a built-in max function +int max(int a, int b) { + return (a > b) ? a : b; +} diff --git a/c/567-Permutation-in-String.c b/c/567-Permutation-in-String.c new file mode 100644 index 000000000..62362caf5 --- /dev/null +++ b/c/567-Permutation-in-String.c @@ -0,0 +1,36 @@ +bool isPermutation(int *count) { + for (int i = 0; i < 26; i++) { + if (count[i] != 0) { + return false; + } + } + return true; +} + +bool checkInclusion(char * s1, char * s2){ + const int m = strlen(s1); + const int n = strlen(s2); + + if (m > n) { + return false; + } + + int count[26] = {0}; + for (int i = 0; i < m; i++) { + count[s1[i] - 'a']++; + count[s2[i] - 'a']--; + } + + if (isPermutation(count)) { + return true; + } + + for (int i = m; i < n; i++) { + count[s2[i] - 'a']--; + count[s2[i - m] - 'a']++; + if (isPermutation(count)) { + return true; + } + } + return false; +} \ No newline at end of file diff --git a/c/994-Rotting-Oranges.c b/c/994-Rotting-Oranges.c new file mode 100644 index 000000000..7286b5040 --- /dev/null +++ b/c/994-Rotting-Oranges.c @@ -0,0 +1,43 @@ + +int directions[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; + +bool rotting_process(int** grid, int rows, int cols, int timestamp) { + bool continue_process = false; + for (int row = 0; row < rows; row++) { + for (int col = 0; col < cols; col++) { + if (grid[row][col] == timestamp) { + for (int i = 0; i < 4; i++) { + int r = row + directions[i][0]; + int c = col + directions[i][1]; + if (rows > r && r >= 0 && cols > c && c >= 0) { + if (grid[r][c] == 1) { + grid[r][c] = timestamp + 1; + continue_process = true; + } + } + } + } + } + } + return continue_process; +} + +int orangesRotting(int** grid, int gridSize, int* gridColSize){ + + int rows = gridSize; + int cols = gridColSize[0]; + + int timestamp = 2; + while (rotting_process(grid, rows, cols, timestamp)) { + timestamp += 1; + } + + for (int row = 0; row < rows; row++) { + for (int col = 0; col < cols; col++) { + if (grid[row][col] == 1) { + return -1; + } + } + } + return timestamp - 2; +} \ No newline at end of file diff --git a/csharp/115-Distinct-Subsequences.cs b/csharp/115-Distinct-Subsequences.cs new file mode 100644 index 000000000..17bb0111b --- /dev/null +++ b/csharp/115-Distinct-Subsequences.cs @@ -0,0 +1,28 @@ +public class Solution { + public int NumDistinct(string s, string t) { + var nS = s.Length; + var nT = t.Length; + + if (nS < nT) return 0; + + var dp = new int[nS + 1, nT + 1]; + + for (int i = 0; i <= nS; i++) { + dp[i, 0] = 1; + } + + for (int i = 1; i <= nS; i++) { + var sIndex = i - 1; + for (int j = 1; j <= nT; j++) { + var tIndex = j - 1; + if (s[sIndex] == t[tIndex]) { + dp[i, j] = dp[i - 1, j - 1] + dp[i - 1, j]; + } else { + dp[i, j] = dp[i - 1, j]; + } + } + } + + return dp[nS, nT]; + } +} diff --git a/csharp/124-Binary-Tree-Maximum-Path-Sum.cs b/csharp/124-Binary-Tree-Maximum-Path-Sum.cs new file mode 100644 index 000000000..1c869a6b9 --- /dev/null +++ b/csharp/124-Binary-Tree-Maximum-Path-Sum.cs @@ -0,0 +1,25 @@ +public class Solution { + +int maxPathSum = Int32.MinValue; + + public int MaxPathSum(TreeNode root) + { + DfsMaxPathSum(root); + return maxPathSum; + } + + private int DfsMaxPathSum(TreeNode root) + { + if (root == null) + return 0; + + int leftMax = DfsMaxPathSum(root.left), + rightMax = DfsMaxPathSum(root.right), + currentMax = 0; + + currentMax = Math.Max(currentMax, Math.Max(leftMax + root.val, rightMax + root.val)); + maxPathSum = Math.Max(maxPathSum, leftMax + root.val + rightMax); + + return currentMax; + } +} diff --git a/csharp/134-Gas-Station.cs b/csharp/134-Gas-Station.cs new file mode 100644 index 000000000..3e582e2b6 --- /dev/null +++ b/csharp/134-Gas-Station.cs @@ -0,0 +1,18 @@ +public class Solution { + public int CanCompleteCircuit(int[] gas, int[] cost) { + if (gas.Sum() < cost.Sum()) { + return -1; + } + + int res = 0, total = 0; + + for (int i = 0; i < gas.Length; i++) { + total += gas[i] - cost[i]; + if (total < 0) { + total = 0; + res = i + 1; + } + } + return res; + } +} \ No newline at end of file diff --git a/csharp/1383-Maximum-Performance-Of-A-Team.cs b/csharp/1383-Maximum-Performance-Of-A-Team.cs new file mode 100644 index 000000000..9295535d5 --- /dev/null +++ b/csharp/1383-Maximum-Performance-Of-A-Team.cs @@ -0,0 +1,36 @@ +public class Solution { +public class Engineer + { + public int speed; + public int efficiency; + public Engineer(int speed, int efficiency) + { + this.speed = speed; + this.efficiency = efficiency; + } + + } + + public int MaxPerformance(int n, int[] speed, int[] efficiency, int k) + { + List engineers = new(); + for (int i = 0; i < n; i++) + { + engineers.Add(new Engineer(speed[i], efficiency[i])); + } + + engineers = engineers.OrderByDescending(x => x.efficiency).ToList(); + var queue = new PriorityQueue(); + long speedTotal = 0, result = 0; + foreach (var engineer in engineers) + { + if (queue.Count > k - 1) + speedTotal -= queue.Dequeue(); + queue.Enqueue(engineer.speed, engineer.speed); + speedTotal += engineer.speed; + result = Math.Max(result, speedTotal * engineer.efficiency); + } + + return (int)(result % 1000000007); + } +} diff --git a/csharp/150-Evaluate-Reverse-Polish-Notation.cs b/csharp/150-Evaluate-Reverse-Polish-Notation.cs new file mode 100644 index 000000000..dbf80b5bc --- /dev/null +++ b/csharp/150-Evaluate-Reverse-Polish-Notation.cs @@ -0,0 +1,27 @@ +public class Solution { + private static int evaluate(int b, int a, string op) => op switch{ + "+" => a + b, + "-" => a - b, + "*" => a * b, + "/" => a / b, + _ => throw new Exception() + }; + public int EvalRPN(string[] tokens) { + var stack = new Stack(); + var result = 0; + + foreach(var token in tokens) { + int number = 0; + var isNumber = int.TryParse(token, out number); + if(isNumber) + stack.Push(number); + else { + result = evaluate(stack.Pop(), stack.Pop(), token); + stack.Push(result); + } + + } + + return stack.Pop(); + } +} \ No newline at end of file diff --git a/csharp/17-Letter-Combinations-Of-A-Phone-Number.cs b/csharp/17-Letter-Combinations-Of-A-Phone-Number.cs new file mode 100644 index 000000000..50827f31e --- /dev/null +++ b/csharp/17-Letter-Combinations-Of-A-Phone-Number.cs @@ -0,0 +1,34 @@ +public class Solution { + public IList LetterCombinations(string digits) + { + var lettersMap = new Dictionary + { + {'2', "abc"}, + {'3', "def"}, + {'4', "ghi"}, + {'5', "jkl"}, + {'6', "mno"}, + {'7', "pqrs"}, + {'8', "tuv"}, + {'9', "wxyz"} + }; + + var result = new List(); + + if (!string.IsNullOrEmpty(digits)) + Backtrack(result, digits, lettersMap, "", 0); + + return result; + } + + void Backtrack(List result, string digits, Dictionary lettersMap, string curString, int start) + { + if (curString.Length == digits.Length) + { result.Add(curString); return; } + + foreach (var c in lettersMap[digits[start]]) + { + Backtrack(result, digits, lettersMap, curString + c, start + 1); + } + } +} diff --git a/csharp/295-Find-Median-From-Data-Stream.cs b/csharp/295-Find-Median-From-Data-Stream.cs new file mode 100644 index 000000000..e71840f6e --- /dev/null +++ b/csharp/295-Find-Median-From-Data-Stream.cs @@ -0,0 +1,84 @@ +public class MedianFinder { + + List Nums; + public MedianFinder() { + + Nums = new List(); + } + + public void AddNum(int num) { + int index = Nums.BinarySearch(num); + if (index < 0) + { + index = ~index; + } + Nums.Insert(index, num); + } + + public double FindMedian() { + int count = Nums.Count; + return count % 2 == 0 ? (double)((Nums[count / 2 - 1] + Nums[count / 2]) * 0.5) : Nums[count / 2]; + } +} + +/** + * Your MedianFinder object will be instantiated and called as such: + * MedianFinder obj = new MedianFinder(); + * obj.AddNum(num); + * double param_2 = obj.FindMedian(); + + // ***IMP : Not passing for few test cases + class MedianFinder + { + + private PriorityQueue smallHeap; //small elements - maxHeap + private PriorityQueue largeHeap; //large elements - minHeap + + public MedianFinder() + { + smallHeap = new PriorityQueue(); + largeHeap = new PriorityQueue(); + } + + public void addNum(int num) + { + smallHeap.Enqueue(num, num); + if ( + smallHeap.Count - largeHeap.Count > 1 || + !(largeHeap.Count <= 0) && + smallHeap.Peek() > largeHeap.Peek() + ) + { + if (smallHeap.Count > 0) + { + int ele = smallHeap.Dequeue(); + largeHeap.Enqueue(ele, ele); + } + } + if (largeHeap.Count - smallHeap.Count > 1) + { + if (largeHeap.Count > 0) + { + int ele = largeHeap.Dequeue(); + smallHeap.Enqueue(ele, ele); + } + } + } + + public double findMedian() + { + if (smallHeap.Count == largeHeap.Count) + { + return (double)(largeHeap.Peek() + smallHeap.Peek()) / 2; + } + else if (smallHeap.Count > largeHeap.Count) + { + return (double)smallHeap.Peek(); + } + else + { + return (double)largeHeap.Peek(); + } + } + } + */ diff --git a/csharp/45-Jump-Game-II.cs b/csharp/45-Jump-Game-II.cs new file mode 100644 index 000000000..5b317b3f1 --- /dev/null +++ b/csharp/45-Jump-Game-II.cs @@ -0,0 +1,16 @@ +public class Solution { + public int Jump(int[] nums) { + int left = 0, right = 0, res = 0; + + while (right < nums.Length - 1) { + int maxJump = 0; + for (int i = left; i <= right; i++) { + maxJump = Math.Max(maxJump, i + nums[i]); + } + left = right + 1; + right = maxJump; + res++; + } + return res; + } +} \ No newline at end of file diff --git a/csharp/54-Spiral-Matrix.cs b/csharp/54-Spiral-Matrix.cs new file mode 100644 index 000000000..f5b5bb2eb --- /dev/null +++ b/csharp/54-Spiral-Matrix.cs @@ -0,0 +1,45 @@ +public class Solution { + public IList SpiralOrder(int[][] matrix) { + List result = new List(); + int top = 0; + int left = 0; + int right = matrix[0].Length - 1; + int bottom = matrix.Length - 1; + + while (true) + { + //Left to Right + for (int i = left; i <= right; i++) + { + result.Add(matrix[top][i]); + } + top++; + if (left > right || top > bottom) break; + + //Top to Bottom + for (int i = top; i <= bottom; i++) + { + result.Add(matrix[i][right]); + } + right--; + if (left > right || top > bottom) break; + + //Right to Left + for (int i = right; i >= left; i--) + { + result.Add(matrix[bottom][i]); + } + bottom--; + if (left > right || top > bottom) break; + + //Bottom to Top + for (int i = bottom; i >= top; i--) + { + result.Add(matrix[i][left]); + } + left++; + if (left > right || top > bottom) break; + }//Repeat + return result; + } +} diff --git a/csharp/73-Set-Matrix-Zeroes.cs b/csharp/73-Set-Matrix-Zeroes.cs new file mode 100644 index 000000000..a737681c9 --- /dev/null +++ b/csharp/73-Set-Matrix-Zeroes.cs @@ -0,0 +1,23 @@ +public class Solution { + public void SetZeroes(int[][] matrix) { + int m = matrix.Length, n = matrix[0].Length; + bool firstRowHasZeros = matrix[0].Contains(0); + + for (int i = 1; i < m; i++) + for (int j = 0; j < n; j++) + if (matrix[i][j] == 0) + matrix[i][0] = matrix[0][j] = 0; + + for (int i = 1; i < m; i++) + if (matrix[i][0] == 0) + Array.Fill(matrix[i], 0); + + for (int j = 0; j < n; j++) + if (matrix[0][j] == 0) + for (int i = 0; i < m; i++) + matrix[i][j] = 0; + + if (firstRowHasZeros) + Array.Fill(matrix[0], 0); + } +} diff --git a/go/190-Reverse-Bits.go b/go/190-Reverse-Bits.go new file mode 100644 index 000000000..8a6d2500a --- /dev/null +++ b/go/190-Reverse-Bits.go @@ -0,0 +1,8 @@ +func reverseBits(num uint32) uint32 { + var res uint32 = 0 + for i := 0; i < 32; i++ { + bit := (num >> i) & 1 + res = res | (bit << (31 - i)) + } + return res +} \ No newline at end of file diff --git a/go/191-Number-of-1-Bits.go b/go/191-Number-of-1-Bits.go new file mode 100644 index 000000000..1e5f036eb --- /dev/null +++ b/go/191-Number-of-1-Bits.go @@ -0,0 +1,8 @@ +func hammingWeight(num uint32) int { + res := 0 + for num > 0 { + num &= num - 1 + res += 1 + } + return res +} \ No newline at end of file diff --git a/go/268-Missing-Number.go b/go/268-Missing-Number.go new file mode 100644 index 000000000..c77b7e46b --- /dev/null +++ b/go/268-Missing-Number.go @@ -0,0 +1,8 @@ +func missingNumber(nums []int) int { + res := len(nums) + + for i := 0; i < len(nums); i++ { + res += i - nums[i] + } + return res +} \ No newline at end of file diff --git a/go/287-Find-the-Duplicate-Number.go b/go/287-Find-the-Duplicate-Number.go new file mode 100644 index 000000000..759104305 --- /dev/null +++ b/go/287-Find-the-Duplicate-Number.go @@ -0,0 +1,15 @@ +func findDuplicate(nums []int) int { + slow, fast := nums[0], nums[nums[0]] + + for slow != fast { + slow = nums[slow] + fast = nums[nums[fast]] + } + + slow = 0 + for slow != fast { + slow = nums[slow] + fast = nums[fast] + } + return slow +} \ No newline at end of file diff --git a/go/309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.go b/go/309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.go new file mode 100644 index 000000000..975bbe3e9 --- /dev/null +++ b/go/309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.go @@ -0,0 +1,19 @@ +func maxProfit(prices []int) int { + sold, hold, rest := 0, math.MinInt32, 0 + + for i := 0; i < len(prices); i++ { + prevSold := sold + sold = hold + prices[i] + hold = max(hold, rest - prices[i]) + rest = max(rest, prevSold) + } + return max(sold, rest) +} + +// Golang does not have a built-in max for integers +func max(a int, b int) int { + if (a > b) { + return a + } + return b +} \ No newline at end of file diff --git a/go/33-Search-in-Rotated-Sorted-Array.go b/go/33-Search-in-Rotated-Sorted-Array.go new file mode 100644 index 000000000..dace26e5c --- /dev/null +++ b/go/33-Search-in-Rotated-Sorted-Array.go @@ -0,0 +1,27 @@ +func search(nums []int, target int) int { + left, right := 0, len(nums) - 1 + + for left <= right { + mid := (left + right) / 2 + if target == nums[mid] { + return mid + } + + // left sorted portion + if nums[left] <= nums[mid] { + if target > nums[mid] || target < nums[left] { + left = mid + 1 + } else { + right = mid - 1 + } + // Right sorted portion + } else { + if target < nums[mid] || target > nums[right] { + right = mid - 1 + } else { + left = mid + 1 + } + } + } + return -1 +} \ No newline at end of file diff --git a/go/338-Counting-Bits.go b/go/338-Counting-Bits.go new file mode 100644 index 000000000..19d014359 --- /dev/null +++ b/go/338-Counting-Bits.go @@ -0,0 +1,12 @@ +func countBits(n int) []int { + dp := make([]int, n + 1) + offset := 1 + + for i := 1; i <= n; i++ { + if offset * 2 == i { + offset = i + } + dp[i] = 1 + dp[i - offset] + } + return dp +} \ No newline at end of file diff --git a/go/371-Sum-of-Two-Integers.go b/go/371-Sum-of-Two-Integers.go new file mode 100644 index 000000000..3c14b508b --- /dev/null +++ b/go/371-Sum-of-Two-Integers.go @@ -0,0 +1,8 @@ +func getSum(a int, b int) int { + for b != 0 { + temp := (a & b) << 1 + a = (a ^ b) + b = temp + } + return a +} \ No newline at end of file diff --git a/go/42-Trapping-Rain-Water.go b/go/42-Trapping-Rain-Water.go new file mode 100644 index 000000000..8b22b112d --- /dev/null +++ b/go/42-Trapping-Rain-Water.go @@ -0,0 +1,30 @@ +func trap(height []int) int { + if height == nil { + return 0 + } + + left, right := 0, len(height) - 1 + leftMax, rightMax := height[left], height[right] + res := 0 + + for left < right { + if leftMax < rightMax { + left += 1 + leftMax = max(leftMax, height[left]) + res += leftMax - height[left] + } else { + right -= 1 + rightMax = max(rightMax, height[right]) + res += rightMax - height[right] + } + } + return res +} + +// Golang does not have a built-in max for integers +func max(a int, b int) int { + if a > b { + return a; + } + return b; +} \ No newline at end of file diff --git a/go/424-Longest-Repeating-Character-Replacement.go b/go/424-Longest-Repeating-Character-Replacement.go new file mode 100644 index 000000000..8c29468d5 --- /dev/null +++ b/go/424-Longest-Repeating-Character-Replacement.go @@ -0,0 +1,25 @@ +func characterReplacement(s string, k int) int { + count := make(map[byte]int) + res := 0 + + l := 0 + maxf := 0 + for r, _ := range s { + count[s[r]] = 1 + count[s[r]] + maxf = max(maxf, count[s[r]]) + + if (r - l + 1) - maxf > k{ + count[s[l]] -= 1 + l++ + } + res = max(res, r - l + 1) + } + return res +} + +func max(a,b int) int { + if a > b { + return a + } + return b +} diff --git a/go/48-Rotate-Image.go b/go/48-Rotate-Image.go new file mode 100644 index 000000000..0662b0f4a --- /dev/null +++ b/go/48-Rotate-Image.go @@ -0,0 +1,25 @@ +func rotate(matrix [][]int) { + left, right := 0, len(matrix) - 1 + for left < right { + for i := 0; i < right - left; i++ { + top, bottom := left, right + + // save the topleft + topLeft := matrix[top][left + i] + + // move bottom left into top left + matrix[top][left + i] = matrix[bottom - i][left] + + // move bottom right into bottom left + matrix[bottom - i][left] = matrix[bottom][right - i] + + // move top right into bottom right + matrix[bottom][right - i] = matrix[top + i][right] + + // move top left into top right + matrix[top + i][right] = topLeft + } + right -= 1 + left += 1 + } +} \ No newline at end of file diff --git a/go/53-Maximum-Subarray.go b/go/53-Maximum-Subarray.go new file mode 100644 index 000000000..2a2669bc4 --- /dev/null +++ b/go/53-Maximum-Subarray.go @@ -0,0 +1,20 @@ +func maxSubArray(nums []int) int { + result, total := nums[0], 0 + + for i := 0; i < len(nums); i++ { + total += nums[i] + result = max(result, total) + if total < 0 { + total = 0 + } + } + return result +} + +// Golang does not have a built-in max for integers +func max(a int, b int) int { + if a > b { + return a + } + return b +} \ No newline at end of file diff --git a/go/55-Jump-Game.go b/go/55-Jump-Game.go new file mode 100644 index 000000000..47a7bfb5f --- /dev/null +++ b/go/55-Jump-Game.go @@ -0,0 +1,10 @@ +func canJump(nums []int) bool { + goal := len(nums) - 1 + + for i := len(nums) - 2; i >= 0; i-- { + if i + nums[i] >= goal { + goal = i + } + } + return goal == 0 +} \ No newline at end of file diff --git a/go/567-Permutation-In-String.go b/go/567-Permutation-In-String.go new file mode 100644 index 000000000..7e9b97439 --- /dev/null +++ b/go/567-Permutation-In-String.go @@ -0,0 +1,44 @@ +func checkInclusion(s1 string, s2 string) bool { + if len(s1) > len(s2){ + return false + } + + s1Count, s2Count := [26]int{}, [26]int{} + for i, _ := range s1 { + s1Count[s1[i] - 'a']++ + s2Count[s2[i] - 'a']++ + } + matches := 0 + for i:=0;i<26;i++ { + if s1Count[i] == s2Count[i] { + matches += 1 + } else { + matches += 0 + } + } + + l := 0 + for r:=len(s1);r): Int { + val set = wordList.toMutableSet() + if (!set.contains(endWord)) + return 0 + + val queue = LinkedList() + queue.add(beginWord) + set.remove(beginWord) + var step = 0 + + while(queue.size != 0) { + val size = queue.size + step++; + + for (i in 0..size-1) { + val curr = queue.poll() + + if (endWord.equals(curr)) + return step + + val neighbors = getNeighbors(curr, set) + for (neig in neighbors) { + queue.add(neig) + set.remove(neig) + } + } + } + + return 0 + } + + fun getNeighbors(str: String, set: Set): List { + val res = ArrayList() + val chars = str.toCharArray() + + for (i in 0..chars.size-1) { + val temp = chars[i]; + + for (j in 'a'..'z') { + chars[i] = j + val newStr = String(chars) + if (set.contains(newStr)) + res.add(newStr) + } + + chars[i] = temp + } + + return res + } +} \ No newline at end of file diff --git a/kotlin/202-Happy-Number.kt b/kotlin/202-Happy-Number.kt new file mode 100644 index 000000000..0fe3b7ec8 --- /dev/null +++ b/kotlin/202-Happy-Number.kt @@ -0,0 +1,23 @@ +class Solution { + fun isHappy(n: Int): Boolean { + var slow = n + var fast = sumSquareDigits(n) + + while (slow != fast) { + fast = sumSquareDigits(sumSquareDigits(fast)) + slow = sumSquareDigits(slow) + } + return fast == 1 + } + + fun sumSquareDigits(n: Int): Int { + var result = 0 + var num = n + while (num != 0) { + val digit = num % 10 + result += digit * digit + num /= 10 + } + return result + } +} \ No newline at end of file diff --git a/kotlin/230-Kth-Smallest-Element-In-A-BST.kt b/kotlin/230-Kth-Smallest-Element-In-A-BST.kt new file mode 100644 index 000000000..a498d7b89 --- /dev/null +++ b/kotlin/230-Kth-Smallest-Element-In-A-BST.kt @@ -0,0 +1,22 @@ +package kotlin + +import TreeNode +import java.util.* + +class Solution { + fun kthSmallest(root: TreeNode, k: Int): Int { + var n = 0 + val callStack = Stack() + var currentNode: TreeNode? = root + var tempNode: TreeNode? + while (true) { + while (currentNode != null) { + callStack.push(currentNode) + currentNode = currentNode.left + } + tempNode = callStack.pop() + if (++n == k) return tempNode.`val` + currentNode = tempNode.right + } + } +} diff --git a/kotlin/309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.kt b/kotlin/309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.kt new file mode 100644 index 000000000..edb1e3bd1 --- /dev/null +++ b/kotlin/309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.kt @@ -0,0 +1,15 @@ +class Solution { + fun maxProfit(prices: IntArray): Int { + var sold = 0 + var hold = Int.MIN_VALUE + var rest = 0 + + for (i in 0..prices.size-1) { + val prevSold = sold + sold = hold + prices[i] + hold = maxOf(hold, rest - prices[i]) + rest = maxOf(rest, prevSold) + } + return maxOf(sold, rest) + } +} \ No newline at end of file diff --git a/kotlin/994-Rotting-Oranges.kt b/kotlin/994-Rotting-Oranges.kt new file mode 100644 index 000000000..78f377771 --- /dev/null +++ b/kotlin/994-Rotting-Oranges.kt @@ -0,0 +1,52 @@ +class Solution { + fun orangesRotting(grid: Array): Int { + val m = grid.size + val n = grid[0].size + var fresh = 0 + var minute = -1 + var queue = LinkedList() + val dirs = arrayOf(intArrayOf(-1,0),intArrayOf(1,0),intArrayOf(0,1),intArrayOf(0,-1)) + + for (i in 0..m-1) { + for (j in 0..n-1) { + val curr = grid[i][j] + + if (curr == 2) + queue.add(intArrayOf(i, j)) + else if (curr == 1) + fresh++ + } + } + + var temp = LinkedList() + + while (queue.size != 0) { + val curr = queue.poll() + + for (dir in dirs) { + val x = curr[0] + dir[0] + val y = curr[1] + dir[1] + + if (x < 0 || x >= m || y < 0 || y >= n) + continue + + if (grid[x][y] == 1) { + temp.add(intArrayOf(x, y)) + fresh-- + grid[x][y] = 2 + } + } + + if (queue.size == 0) { + minute++ + queue = temp + temp = LinkedList() + } + } + + if (fresh != 0) + return -1 + + return if (minute == -1) 0 else minute + } +} \ No newline at end of file diff --git a/python/215-Kth-Largest-Element-in-an-Array.py b/python/215-Kth-Largest-Element-in-an-Array.py index 1c936dee3..4f3a36dcb 100644 --- a/python/215-Kth-Largest-Element-in-an-Array.py +++ b/python/215-Kth-Largest-Element-in-an-Array.py @@ -9,8 +9,6 @@ def findKthLargest(self, nums: List[int], k: int) -> int: nums.sort() return nums[len(nums) - k] - k = len(nums) - k - # Solution: QuickSelect # Time Complexity: diff --git a/python/40-Combination-Sum-II.py b/python/40-Combination-Sum-II.py index 6c7708fd1..eb9790e3b 100644 --- a/python/40-Combination-Sum-II.py +++ b/python/40-Combination-Sum-II.py @@ -7,6 +7,7 @@ def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]] def backtrack(cur, pos, target): if target == 0: res.append(cur.copy()) + return if target <= 0: return diff --git a/scala/141-Linked-List-Cycle.scala b/scala/141-Linked-List-Cycle.scala new file mode 100644 index 000000000..04d895985 --- /dev/null +++ b/scala/141-Linked-List-Cycle.scala @@ -0,0 +1,24 @@ +/** + * Definition for singly-linked list. + * class ListNode(var _x: Int = 0) { + * var next: ListNode = null + * var x: Int = _x + * } + */ + +object Solution { + def hasCycle(head: ListNode): Boolean = { + var (slowPtr, fastPtr) = (head, head) + + while (fastPtr != null && fastPtr.next != null) { + slowPtr = slowPtr.next + fastPtr = fastPtr.next.next + + if (slowPtr eq fastPtr) { + return true + } + } + + return false + } +} \ No newline at end of file diff --git a/scala/206-Reverse-Linked-List.scala b/scala/206-Reverse-Linked-List.scala new file mode 100644 index 000000000..b53ce3d1a --- /dev/null +++ b/scala/206-Reverse-Linked-List.scala @@ -0,0 +1,20 @@ +/** + * Definition for singly-linked list. + * class ListNode(_x: Int = 0, _next: ListNode = null) { + * var next: ListNode = _next + * var x: Int = _x + * } + */ +object Solution { + def reverseList(head: ListNode): ListNode = { + if (head == null || head.next == null) { + return head + } + + val reversedListHead = reverseList(head.next) + head.next.next = head + head.next = null + + return reversedListHead + } +} \ No newline at end of file diff --git a/scala/217-Contains-Duplicate.scala b/scala/217-Contains-Duplicate.scala new file mode 100644 index 000000000..91f04d82a --- /dev/null +++ b/scala/217-Contains-Duplicate.scala @@ -0,0 +1,12 @@ +import scala.collection.mutable.HashSet + +object Solution { + def containsDuplicate(nums: Array[Int]): Boolean = { + var seen: HashSet[Int] = HashSet() + for (num <- nums) { + if (seen.contains(num)) return true + seen.add(num) + } + return false + } +} \ No newline at end of file diff --git a/swift/124-Binary-Tree-Maximum-Path-Sum.swift b/swift/124-Binary-Tree-Maximum-Path-Sum.swift new file mode 100644 index 000000000..a5f7458bc --- /dev/null +++ b/swift/124-Binary-Tree-Maximum-Path-Sum.swift @@ -0,0 +1,40 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * public var val: Int + * public var left: TreeNode? + * public var right: TreeNode? + * public init() { self.val = 0; self.left = nil; self.right = nil; } + * public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; } + * public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) { + * self.val = val + * self.left = left + * self.right = right + * } + * } + */ +class Solution { + var globalMax: Int = Int.min + + // Return max path that '''ends at''' a particular node + private func ends(at node: TreeNode?) -> Int { + // Base case + guard let node = node else { return 0 } + + // Recursive cases + // MAX with 0, to shorten negative paths + let leftMaxPath = max(ends(at: node.left), 0) + let rightMaxPath = max(ends(at: node.right), 0) + + let pathIncludingNode = leftMaxPath + node.val + rightMaxPath + globalMax = max(globalMax, pathIncludingNode) + + let pathEndingAtNode = max(leftMaxPath, rightMaxPath) + node.val + return pathEndingAtNode + } + + func maxPathSum(_ root: TreeNode?) -> Int { + ends(at: root) + return globalMax + } +} \ No newline at end of file diff --git a/swift/1584-Min-Cost-to-Connect-All-Points.swift b/swift/1584-Min-Cost-to-Connect-All-Points.swift new file mode 100644 index 000000000..43d6fb811 --- /dev/null +++ b/swift/1584-Min-Cost-to-Connect-All-Points.swift @@ -0,0 +1,95 @@ +class DisjointSet { + var roots: [Int] + var ranks: [Int] + + init(n: Int) { + roots = [Int](repeating: 0, count: n) + ranks = [Int](repeating: 0, count: n) + + for i in 0.. Int { + guard u != roots[u] else { return u } + roots[u] = find(roots[u]) + return roots[u] + } + + public func union(_ x: Int, _ y: Int) { + let rootX = roots[x] + let rootY = roots[y] + guard rootX != rootY else { return } + + // assign to the bigger one + if ranks[rootX] > ranks[rootY] { + roots[rootY] = rootX + } else if ranks[rootY] > ranks[rootX] { + roots[rootX] = rootY + } else { + // default: assign to root X + roots[rootY] = rootX + ranks[rootX] += 1 + } + } + + public func areDisjoint(u: Int, v: Int) -> Bool { + find(u) != find(v) + } +} + +struct Edge { + let source: Int + let destination: Int + let weight: Int + + init(u: Int, v: Int, w: Int) { + source = u + destination = v + weight = w + } +} + +class Solution { + func minCostConnectPoints(_ points: [[Int]]) -> Int { + let edges: [Edge] = getEdges(from: points) + // images.sorted(by: { $0.fileID > $1.fileID }) + // sort by ascending order + let sortedEdges = edges.sorted { $0.weight < $1.weight } + var disjointSet = DisjointSet(n: points.count) + var total = 0 + + sortedEdges.forEach { edge in + let u = edge.source + let v = edge.destination + let w = edge.weight + + guard disjointSet.areDisjoint(u: u, v: v) else { return } + disjointSet.union(u, v) + total += w + } + + return total + } +} + +private extension Solution { + func distance(from point1: [Int], to point2: [Int]) -> Int { + abs(point1[0] - point2[0]) + abs(point1[1] - point2[1]) + } + + func getEdges(from points: [[Int]]) -> [Edge] { + var edges: [Edge] = [] + let n = points.count + for i in 0.. Bool { + var itr = head + for char in word { + guard let child = itr.children[char] else { return false } + itr = child + } + return isPrefixCheck ? true : itr.isWord + } + + func search(_ word: String) -> Bool { + search(word: word, isPrefixCheck: false) + } + + func startsWith(_ prefix: String) -> Bool { + search(word: prefix, isPrefixCheck: true) + } +} + +/** + * Your Trie object will be instantiated and called as such: + * let obj = Trie() + * obj.insert(word) + * let ret_2: Bool = obj.search(word) + * let ret_3: Bool = obj.startsWith(prefix) + */ \ No newline at end of file diff --git a/swift/309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.swift b/swift/309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.swift new file mode 100644 index 000000000..9bdf24b26 --- /dev/null +++ b/swift/309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.swift @@ -0,0 +1,13 @@ +class Solution { + func maxProfit(_ prices: [Int]) -> Int { + var sold = 0, hold = -1000, rest = 0 + + for i in 0...prices.count-1 { + let prevSold = sold + sold = hold + prices[i] + hold = max(hold, rest - prices[i]) + rest = max(rest, prevSold) + } + return max(sold, rest) + } +} \ No newline at end of file diff --git a/swift/35-Valid-Sudoku.swift b/swift/35-Valid-Sudoku.swift new file mode 100644 index 000000000..bde960827 --- /dev/null +++ b/swift/35-Valid-Sudoku.swift @@ -0,0 +1,34 @@ +class Solution { + func isValidSudoku(_ board: [[Character]]) -> Bool { + var rows: [Set] = [] + var cols: [Set] = [] + var subBoxes: [[Set]] = [] + for i in 1...9 { + rows.append(Set()) + cols.append(Set()) + } + for i in 1...3 { + var row: [Set] = [] + for j in 1...3 { + row.append(Set()) + } + subBoxes.append(row) + + } + for i in 0...8 { + for j in 0...8 { + let val: Character = board[i][j] + if (val == ".") { + continue + } + if (rows[i].contains(val) || cols[j].contains(val) || subBoxes[i/3][j/3].contains(val)){ + return false + } + rows[i].insert(val) + cols[j].insert(val) + subBoxes[i/3][j/3].insert(val) + } + } + return true + } +} diff --git a/swift/46-Permutations.swift b/swift/46-Permutations.swift new file mode 100644 index 000000000..0a413d9b7 --- /dev/null +++ b/swift/46-Permutations.swift @@ -0,0 +1,42 @@ +class Solution { + var ans: [[Int]] = [] + + func permute(_ nums: [Int]) -> [[Int]] { + var referenceNums = nums + dfs(start: 0, currentOrder: &referenceNums) + return ans + } +} + +private extension Solution { + private func swap(_ arr: inout [Int], at i1: Int, with i2: Int) { + guard + i1 < arr.count, + i2 < arr.count + else { return } + + let temp = arr[i1] + arr[i1] = arr[i2] + arr[i2] = temp + } + + func dfs(start: Int, currentOrder nums: inout [Int]) { + // base case [take into final answer] + if start == nums.count { + ans.append(nums) + return + } + + // for each idx, take, switch with start, backtrack, switch back + for i in start.. [Int] { + // parameters are immutable in swift + var digit = digits + for i in stride(from: digit.count - 1, through: 0, by: -1) { + digit[i] += 1 + + if digit[i] <= 9 { + return digit + } + + digit[i] = 0 + } + + digit.insert(1, at: 0) + return digit + } +} \ No newline at end of file diff --git a/swift/703-Kth-Largest-Element-In-A-Stream.swift b/swift/703-Kth-Largest-Element-In-A-Stream.swift new file mode 100644 index 000000000..c05107ffc --- /dev/null +++ b/swift/703-Kth-Largest-Element-In-A-Stream.swift @@ -0,0 +1,129 @@ +// Heap source code at: https://gist.github.com/kalub92/d269ba6b2bf05ca7dcbaae64b4ff7a2d +struct MinHeap { + var items: [Int] = [] + + //Get Index + private func getLeftChildIndex(_ parentIndex: Int) -> Int { + return 2 * parentIndex + 1 + } + private func getRightChildIndex(_ parentIndex: Int) -> Int { + return 2 * parentIndex + 2 + } + private func getParentIndex(_ childIndex: Int) -> Int { + return (childIndex - 1) / 2 + } + + // Boolean Check + private func hasLeftChild(_ index: Int) -> Bool { + return getLeftChildIndex(index) < items.count + } + private func hasRightChild(_ index: Int) -> Bool { + return getRightChildIndex(index) < items.count + } + private func hasParent(_ index: Int) -> Bool { + return getParentIndex(index) >= 0 + } + + // Return Item From Heap + private func leftChild(_ index: Int) -> Int { + return items[getLeftChildIndex(index)] + } + private func rightChild(_ index: Int) -> Int { + return items[getRightChildIndex(index)] + } + private func parent(_ index: Int) -> Int { + return items[getParentIndex(index)] + } + + // Heap Operations + mutating private func swap(indexOne: Int, indexTwo: Int) { + let placeholder = items[indexOne] + items[indexOne] = items[indexTwo] + items[indexTwo] = placeholder + } + + public func peek() -> Int { + if items.count != 0 { + return items[0] + } else { + fatalError() + } + } + + mutating public func poll() -> Int { + if items.count != 0 { + let item = items[0] + items[0] = items[items.count - 1] + heapifyDown() + items.removeLast() + return item + } else { + fatalError() + } + } + + mutating public func add(_ item: Int) { + items.append(item) + heapifyUp() + } + + mutating private func heapifyUp() { + var index = items.count - 1 + while hasParent(index) && parent(index) > items[index] { + swap(indexOne: getParentIndex(index), indexTwo: index) + index = getParentIndex(index) + } + } + + mutating private func heapifyDown() { + var index = 0 + while hasLeftChild(index) { + var smallerChildIndex = getLeftChildIndex(index) + if hasRightChild(index) && + rightChild(index) < leftChild(index) { + smallerChildIndex = getRightChildIndex(index) + } + + if items[index] < items[smallerChildIndex] { + break + } else { + swap(indexOne: index, indexTwo: smallerChildIndex) + } + + index = smallerChildIndex + } + } +} + +// Extensions to add for the required problem +extension MinHeap { + var size: Int { items.count } +} + +class KthLargest { + var minHeap = MinHeap() + var capacity = 0 + + init(_ k: Int, _ nums: [Int]) { + self.capacity = k + nums.forEach { add($0) } + } + + func add(_ val: Int) -> Int { + if minHeap.size >= capacity { + if val > minHeap.peek() { + minHeap.poll() + minHeap.add(val) + } + } else { + minHeap.add(val) + } + return minHeap.peek() + } +} + +/** + * Your KthLargest object will be instantiated and called as such: + * let obj = KthLargest(k, nums) + * let ret_1: Int = obj.add(val) + */ diff --git a/swift/875-Koko-Eating-Bananas.swift b/swift/875-Koko-Eating-Bananas.swift new file mode 100644 index 000000000..b75e4fa4d --- /dev/null +++ b/swift/875-Koko-Eating-Bananas.swift @@ -0,0 +1,23 @@ +class Solution { + func minEatingSpeed(_ piles: [Int], _ h: Int) -> Int { + let total = piles.reduce(0, +) + var left = (total + h - 1) / h, right = piles.max()! + + while left < right { + let mid = left + (right - left) / 2 + + var totalTime = 0 + for p in piles { + totalTime += (p + mid - 1) / mid + } + + if totalTime <= h { + right = mid + } + else { + left = mid + 1 + } + } + return right + } +} \ No newline at end of file diff --git a/typescript/130-Surrounded-Regions.ts b/typescript/130-Surrounded-Regions.ts new file mode 100644 index 000000000..1dfcc3740 --- /dev/null +++ b/typescript/130-Surrounded-Regions.ts @@ -0,0 +1,48 @@ +/** + Do not return anything, modify board in-place instead. + */ +function solve(board: string[][]): void { + const rowLen = board.length; + const colLen = board[0].length; + const lastRow = rowLen - 1; + const lastCol = colLen - 1; + + for (let r = 0; r < rowLen; ++r) { + markSeen(r, 0); + markSeen(r, lastCol); + } + for (let c = 1; c < lastCol; ++c) { + markSeen(0, c); + markSeen(lastRow, c); + } + + for (let r = 0; r < rowLen; ++r) { + for (let c = 0; c < colLen; ++c) { + switch (board[r][c]) { + case 'O': + board[r][c] = 'X'; + break; + case 'A': + board[r][c] = 'O'; + break; + } + } + } + +function markSeen(r: number, c: number): void { + if (!inBounds(r, c) || board[r][c] !== 'O') { + return; + } + + board[r][c] = 'A'; + + markSeen(r - 1, c); + markSeen(r + 1, c); + markSeen(r, c - 1); + markSeen(r, c + 1); +} + +function inBounds(r: number, c: number): boolean { + return r >= 0 && c >= 0 && r < rowLen && c < colLen; +} +}; \ No newline at end of file diff --git a/typescript/309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.ts b/typescript/309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.ts new file mode 100644 index 000000000..4b595a789 --- /dev/null +++ b/typescript/309-Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.ts @@ -0,0 +1,11 @@ +function maxProfit(prices: number[]): number { + let [ sold, hold, rest ] = [ 0, Number.MIN_SAFE_INTEGER, 0]; + + for (let i = 0; i < prices.length; i++) { + let prevSold = sold; + sold = hold + prices[i]; + hold = Math.max(hold, rest - prices[i]); + rest = Math.max(rest, prevSold); + } + return Math.max(sold, rest); +}; \ No newline at end of file diff --git a/typescript/435-Non-overlapping-Intervals.ts b/typescript/435-Non-overlapping-Intervals.ts new file mode 100644 index 000000000..f20df9d2b --- /dev/null +++ b/typescript/435-Non-overlapping-Intervals.ts @@ -0,0 +1,24 @@ +function eraseOverlapIntervals(intervals: number[][]): number { + intervals.sort(([aStart, aEnd], [bStart, bEnd]) => aEnd !== bEnd ? aEnd - bEnd : aStart - bStart); + + return getGaps(intervals); +}; + +function getGaps(intervals: number[][]): number { + let gaps = 0; + const prev = intervals.shift(); + + for (const curr of intervals) { + const [prevStart, prevEnd] = prev; + const [currStart, currEnd] = curr; + + const hasGap = prevEnd <= currStart; + if (!hasGap) { + continue; + } + + prev[1] = curr[1]; + gaps++; + } + return intervals.length - gaps; +} \ No newline at end of file diff --git a/typescript/51-N-Queens b/typescript/51-N-Queens new file mode 100644 index 000000000..35bf5295c --- /dev/null +++ b/typescript/51-N-Queens @@ -0,0 +1,62 @@ +//check if current state is valid +const isStateValid = (state: number[], n: number) => { + //if there are n queens inserted the state is valid + return state.length === n; +}; + +//convert given state(valid) to correct answer format(a string) +const stateToString = (state: number[]) => { + let arrs = state.map((col) => { + let newArr = new Array(state.length).fill('.'); + newArr[col] = 'Q'; + return newArr.join(''); + }); + + return arrs; +}; + +//recursive step +const searchRec = (state: number[], n: number, solutions: string[][]) => { + //if current state is valid, add it to the solutions array and return, we go back to previous states (DFS) + if (isStateValid(state, n)) return solutions.push(stateToString(state)); + + //get new possible candidates (the column in which to place current queen) to add to current State, start with every column + let candidates = new Set([...Array(n).keys()]); + + //the row in which next queen will be added + let rowToAdd = state.length; + + //iterates previous not empty rows to discard candidates before exploring them + for (let row = 0; row < state.length; row++) { + //the column in which is placed the queen at current row + let col = state[row]; + let dist = rowToAdd - row; + //discard the whole column where queen inserte in "row" is + candidates.delete(col); + //right diagonal intersection of queen inserted in "row" with the row where to add new queen(new queen cannot be here) + candidates.delete(col + dist); + //left diagonal intersection of queen inserted in "row" with the row where to add new queen(new queen cannot be here) + candidates.delete(col - dist); + } + + candidates.forEach((cand) => { + //temporarly add candidate to state + state.push(cand); + //explore new state with that candidate + searchRec(state, n, solutions); + //explored, remove the candidate to return at previous state + state.pop(); + }); + + return; +}; + +function solveNQueens(n: number): string[][] { + let solutions = []; + let start = []; + + //explore starting from empty state + searchRec(start, n, solutions); + + return solutions; +} diff --git a/typescript/56-Merge-Intervals.ts b/typescript/56-Merge-Intervals.ts new file mode 100644 index 000000000..0835cb77f --- /dev/null +++ b/typescript/56-Merge-Intervals.ts @@ -0,0 +1,25 @@ +function merge(intervals: number[][]): number[][] { + intervals.sort(([aStart, aEnd], [bStart, bEnd]) => aStart !== bStart ? aStart - bStart : aEnd - bEnd); + + return mergeInterval(intervals); +}; + +function mergeInterval(intervals: number[][]): number[][] { + let merged = []; + let prev = intervals.shift(); + + for (const curr of intervals) { + const [prevStart, prevEnd] = prev; + const [currStart, currEnd] = curr; + + // Overlap occurs + if (currStart <= prevEnd) { + prev[1] = Math.max(prev[1], curr[1]); + continue; + } + + merged.push(prev); + prev = curr; + } + return [...merged, prev]; +} \ No newline at end of file diff --git a/typescript/57-Insert-Interval.ts b/typescript/57-Insert-Interval.ts new file mode 100644 index 000000000..9b63bae71 --- /dev/null +++ b/typescript/57-Insert-Interval.ts @@ -0,0 +1,30 @@ +function insert(intervals: number[][], newInterval: number[]): number[][] { + const { beforeIndex, before } = getBefore(intervals, newInterval); + const afterIndex = mergeIntervals(intervals, newInterval, beforeIndex); + const after = intervals.slice(afterIndex); + + return [...before, newInterval, ...after]; +}; + +const getBefore = (intervals, newInterval, index = 0, before = []) => { + const hasGap = ([prevStart, prevEnd], [currStart, currEnd]) => prevEnd < currStart; + + while (index < intervals.length && hasGap(intervals[index], newInterval)) { + const current = intervals[index]; + before.push(current); + index++; + } + return { beforeIndex: index, before }; +}; + +const mergeIntervals = (intervals, newInterval, index) => { + const hasOverlap = ([prevStart, prevEnd], [currStart, currEnd]) => currStart <= prevEnd; + + while (index < intervals.length && hasOverlap(newInterval, intervals[index])) { + const current = intervals[index]; + newInterval[0] = Math.min(newInterval[0], current[0]); + newInterval[1] = Math.max(newInterval[1], current[1]); + index++; + } + return index; +}; \ No newline at end of file diff --git a/typescript/73-Set-Matrix-Zeroes.ts b/typescript/73-Set-Matrix-Zeroes.ts new file mode 100644 index 000000000..073c85ed0 --- /dev/null +++ b/typescript/73-Set-Matrix-Zeroes.ts @@ -0,0 +1,24 @@ +/** + Do not return anything, modify matrix in-place instead. + */ +function setZeroes(matrix: number[][]): void { + let row = new Array(matrix.length); + let col = new Array(matrix[0].length); + + for (let i = 0; i < row.length; i++) { + for (let j = 0; j < col.length; j++) { + if (matrix[i][j] === 0) { + row[i] = 0; + col[j] = 0; + } + } + } + + for (let i = 0; i < row.length; i++) { + for (let j = 0; j < col.length; j++) { + if (row[i] == 0 || col[j] == 0) { + matrix[i][j] = 0; + } + } + } +}; \ No newline at end of file