├── .gitignore ├── LICENSE ├── README.md ├── binaryTree.go ├── commonFunc.go ├── go.mod ├── main.go ├── week1-bestTimetoBuyandSellStockII.go ├── week1-bestTimetoBuyandSellStockII_test.go ├── week1-countingElements.go ├── week1-countingElements_test.go ├── week1-groupAnagrams.go ├── week1-groupAnagrams_test.go ├── week1-happyNumber.go ├── week1-happyNumber_test.go ├── week1-maximumSubarray.go ├── week1-maximumSubarray_test.go ├── week1-moveZeroes.go ├── week1-moveZeroes_test.go ├── week1-singleNumber.go ├── week1-singleNumber_test.go ├── week2-backspaceStringCompare.go ├── week2-backspaceStringCompare_test.go ├── week2-contiguousArray.go ├── week2-contiguousArray_test.go ├── week2-diameterofBinaryTree.go ├── week2-diameterofBinaryTree_test.go ├── week2-lastStoneWeight.go ├── week2-lastStoneWeight_test.go ├── week2-middleoftheLinkedList.go ├── week2-middleoftheLinkedList_test.go ├── week2-minStack.go ├── week2-performStringShifts.go ├── week2-performStringShifts_test.go ├── week3-constructBinarySearchTreefromPreorderTraversal.go ├── week3-leftmostColumnwithatLeastaOne.go ├── week3-leftmostColumnwithatLeastaOne_test.go ├── week3-minimumPathSum.go ├── week3-minimumPathSum_test.go ├── week3-numberofIslands.go ├── week3-numberofIslands_test.go ├── week3-productofArrayExceptSelf.go ├── week3-productofArrayExceptSelf_test.go ├── week3-searchinRotatedSortedArray.go ├── week3-searchinRotatedSortedArray_test.go ├── week3-validParenthesisString.go ├── week3-validParenthesisString_test.go ├── week4-LRU_Cache.go ├── week4-bitwiseANDofNumbersRange.go ├── week4-bitwiseANDofNumbersRange_test.go ├── week4-firstUniqueNumber.go ├── week4-jumpGame.go ├── week4-jumpGame_test.go ├── week4-longestCommonSubsequence.go ├── week4-longestCommonSubsequence_test.go ├── week4-maximalSquare.go ├── week4-maximalSquare_test.go ├── week4-subarraySumEqualsK.go ├── week4-subarraySumEqualsK_test.go ├── week5-binaryTreeMaximumPathSum.go └── week5-checkIfaStringIsaValidSequencefromRoottoLeavesPathinaBinaryTree.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, built with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # Dependency directories (remove the comment below to include it) 15 | # vendor/ 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 30-Day-LeetCoding-Challenge (2020-04-01 ~ 2020-04-30) 2 | [Challenge site](https://leetcode.com/explore/featured/card/30-day-leetcoding-challenge/) 3 | [github](https://github.com/eehsiao/30-Day-LeetCoding-Challenge) 4 | 5 | [My leetcode](https://leetcode.com/eehsiao/) 6 | 7 | # 2020-May-LeetCoding-Challenge 8 | [Challenge site](https://leetcode.com/explore/challenge/card/may-leetcoding-challenge/) 9 | 10 | [github](https://github.com/eehsiao/LeetCoding-Challenge/tree/master/May2020) 11 | 12 | # 2020-June-LeetCoding-Challenge 13 | [Challenge site](https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/) 14 | 15 | [github](https://github.com/eehsiao/LeetCoding-Challenge/tree/master/June2020) 16 | 17 | 18 | ## Week 1: April 1st–April 7th 19 | ### [Single Number](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week1-singleNumber.go) [(Test Case)](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week1-singleNumber_test.go) 20 | ``` 21 | Given a non-empty array of integers, every element appears twice except for one. Find that single one. 22 | Note: 23 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 24 | Example 1: 25 | Input: [2,2,1] 26 | Output: 1 27 | Example 2: 28 | Input: [4,1,2,1,2] 29 | Output: 4 30 | ``` 31 | 32 | ### [Happy Number](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week1-happyNumber.go) [(Test Case)](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week1-happyNumber_test.go) 33 | ``` 34 | Write an algorithm to determine if a number n is "happy". 35 | A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. 36 | Return True if n is a happy number, and False if not. 37 | Example: 38 | Input: 19 39 | Output: true 40 | Explanation: 41 | 12 + 92 = 82 42 | 82 + 22 = 68 43 | 62 + 82 = 100 44 | 12 + 02 + 02 = 1 45 | ``` 46 | 47 | ### [Maximum Subarray](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week1-maximumSubarray.go) [(Test Case)](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week1-maximumSubarray_test.go) 48 | ``` 49 | Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. 50 | Example: 51 | Input: [-2,1,-3,4,-1,2,1,-5,4], 52 | Output: 6 53 | Explanation: [4,-1,2,1] has the largest sum = 6. 54 | Follow up: 55 | If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. 56 | 57 | ``` 58 | 59 | ### [Move Zeroes](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week1-moveZeroes.go) [(Test Case)](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week1-moveZeroes_test.go) 60 | ``` 61 | Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. 62 | Example: 63 | Input: [0,1,0,3,12] 64 | Output: [1,3,12,0,0] 65 | Note: 66 | You must do this in-place without making a copy of the array. 67 | Minimize the total number of operations. 68 | Hide Hint #1 69 | In-place means we should not be allocating any space for extra array. But we are allowed to modify the existing array. However, as a first step, try coming up with a solution that makes use of additional space. For this problem as well, first apply the idea discussed using an additional array and the in-place solution will pop up eventually. 70 | Hide Hint #2 71 | A two-pointer approach could be helpful here. The idea would be to have one pointer for iterating the array and another pointer that just works on the non-zero elements of the array. 72 | ``` 73 | 74 | ### [Best Time to Buy and Sell Stock II](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week1-bestTimetoBuyandSellStockII.go) [(Test Case)](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week1-bestTimetoBuyandSellStockII_test.go) 75 | ``` 76 | Say you have an array prices for which the ith element is the price of a given stock on day i. 77 | Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times). 78 | Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). 79 | Example 1: 80 | Input: [7,1,5,3,6,4] 81 | Output: 7 82 | Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. 83 | Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. 84 | Example 2: 85 | Input: [1,2,3,4,5] 86 | Output: 4 87 | Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. 88 | Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are 89 | engaging multiple transactions at the same time. You must sell before buying again. 90 | Example 3: 91 | Input: [7,6,4,3,1] 92 | Output: 0 93 | Explanation: In this case, no transaction is done, i.e. max profit = 0. 94 | Constraints: 95 | 1 <= prices.length <= 3 * 10 ^ 4 96 | 0 <= prices[i] <= 10 ^ 4 97 | ``` 98 | 99 | ### [Group Anagrams](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week1-groupAnagrams.go) [(Test Case)](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week1-groupAnagrams_test.go) 100 | ``` 101 | Given an array of strings, group anagrams together. 102 | Example: 103 | Input: ["eat", "tea", "tan", "ate", "nat", "bat"], 104 | Output: 105 | [ 106 | ["ate","eat","tea"], 107 | ["nat","tan"], 108 | ["bat"] 109 | ] 110 | Note: 111 | All inputs will be in lowercase. 112 | The order of your output does not matter. 113 | ``` 114 | 115 | ### [Counting Elements](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week1-countingElements.go) [(Test Case)](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week1-countingElements_test.go) 116 | ``` 117 | Given an integer array arr, count element x such that x + 1 is also in arr. 118 | If there're duplicates in arr, count them seperately. 119 | Example 1: 120 | Input: arr = [1,2,3] 121 | Output: 2 122 | Explanation: 1 and 2 are counted cause 2 and 3 are in arr. 123 | Example 2: 124 | Input: arr = [1,1,3,3,5,5,7,7] 125 | Output: 0 126 | Explanation: No numbers are counted, cause there's no 2, 4, 6, or 8 in arr. 127 | Example 3: 128 | Input: arr = [1,3,2,3,5,0] 129 | Output: 3 130 | Explanation: 0, 1 and 2 are counted cause 1, 2 and 3 are in arr. 131 | Example 4: 132 | Input: arr = [1,1,2,2] 133 | Output: 2 134 | Explanation: Two 1s are counted cause 2 is in arr. 135 | Constraints: 136 | 1 <= arr.length <= 1000 137 | 0 <= arr[i] <= 1000 138 | ``` 139 | 140 | 141 | ## Week 2: Week 2: April 8th–April 14th 142 | ### [Middle of the Linked List](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week2-middleoftheLinkedList.go) [(Test Case)](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week2-middleoftheLinkedList_test.go) 143 | ``` 144 | Given a non-empty, singly linked list with head node head, return a middle node of linked list. 145 | If there are two middle nodes, return the second middle node. 146 | Example 1: 147 | Input: [1,2,3,4,5] 148 | Output: Node 3 from this list (Serialization: [3,4,5]) 149 | The returned node has value 3. (The judge's serialization of this node is [3,4,5]). 150 | Note that we returned a ListNode object ans, such that: 151 | ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL. 152 | Example 2: 153 | Input: [1,2,3,4,5,6] 154 | Output: Node 4 from this list (Serialization: [4,5,6]) 155 | Since the list has two middle nodes with values 3 and 4, we return the second one. 156 | Note: 157 | The number of nodes in the given list will be between 1 and 100. 158 | ``` 159 | 160 | ### [Backspace String Compare](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week2-backspaceStringCompare.go) [(Test Case)](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week2-backspaceStringCompare_test.go) 161 | ``` 162 | Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character. 163 | Note that after backspacing an empty text, the text will continue empty. 164 | Example 1: 165 | Input: S = "ab#c", T = "ad#c" 166 | Output: true 167 | Explanation: Both S and T become "ac". 168 | Example 2: 169 | Input: S = "ab##", T = "c#d#" 170 | Output: true 171 | Explanation: Both S and T become "". 172 | Example 3: 173 | Input: S = "a##c", T = "#a#c" 174 | Output: true 175 | Explanation: Both S and T become "c". 176 | Example 4: 177 | Input: S = "a#c", T = "b" 178 | Output: false 179 | Explanation: S becomes "c" while T becomes "b". 180 | Note: 181 | 1 <= S.length <= 200 182 | 1 <= T.length <= 200 183 | S and T only contain lowercase letters and '#' characters. 184 | Follow up: 185 | Can you solve it in O(N) time and O(1) space? 186 | ``` 187 | 188 | ### [Min Stack](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week2-minStack.go) 189 | ``` 190 | Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. 191 | push(x) -- Push element x onto stack. 192 | pop() -- Removes the element on top of the stack. 193 | top() -- Get the top element. 194 | getMin() -- Retrieve the minimum element in the stack. 195 | Example 1: 196 | Input 197 | ["MinStack","push","push","push","getMin","pop","top","getMin"] 198 | [[],[-2],[0],[-3],[],[],[],[]] 199 | Output 200 | [null,null,null,null,-3,null,0,-2] 201 | Explanation 202 | MinStack minStack = new MinStack(); 203 | minStack.push(-2); 204 | minStack.push(0); 205 | minStack.push(-3); 206 | minStack.getMin(); // return -3 207 | minStack.pop(); 208 | minStack.top(); // return 0 209 | minStack.getMin(); // return -2 210 | Constraints: 211 | Methods pop, top and getMin operations will always be called on non-empty stacks. 212 | Hide Hint #1 213 | Consider each node in the stack having a minimum value. (Credits to @aakarshmadhavan) 214 | ``` 215 | 216 | ### [Diameter of Binary Tree](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week2-diameterofBinaryTree.go) [(Test Case)](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week2-diameterofBinaryTree_test.go) 217 | ``` 218 | Diameter of Binary Tree 219 | Solution 220 | Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. 221 | Example: 222 | Given a binary tree 223 | 1 224 | / \ 225 | 2 3 226 | / \ 227 | 4 5 228 | Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3]. 229 | Note: The length of path between two nodes is represented by the number of edges between them. 230 | ``` 231 | 232 | ### [Last Stone Weight](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week2-lastStoneWeight.go) 233 | ``` 234 | We have a collection of stones, each stone has a positive integer weight. 235 | Each turn, we choose the two heaviest stones and smash them together. Suppose the stones have weights x and y with x <= y. The result of this smash is: 236 | If x == y, both stones are totally destroyed; 237 | If x != y, the stone of weight x is totally destroyed, and the stone of weight y has new weight y-x. 238 | At the end, there is at most 1 stone left. Return the weight of this stone (or 0 if there are no stones left.) 239 | Example 1: 240 | Input: [2,7,4,1,8,1] 241 | Output: 1 242 | Explanation: 243 | We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then, 244 | we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then, 245 | we combine 2 and 1 to get 1 so the array converts to [1,1,1] then, 246 | we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of last stone. 247 | Note: 248 | 1 <= stones.length <= 30 249 | 1 <= stones[i] <= 1000 250 | Hide Hint #1 251 | Simulate the process. We can do it with a heap, or by sorting some list of stones every time we take a turn. 252 | ``` 253 | 254 | ### [Contiguous Array](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week2-contiguousArray.go) [(Test Case)](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week2-contiguousArray_test.go) 255 | ``` 256 | Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1. 257 | Example 1: 258 | Input: [0,1] 259 | Output: 2 260 | Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1. 261 | Example 2: 262 | Input: [0,1,0] 263 | Output: 2 264 | Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1. 265 | Note: The length of the given binary array will not exceed 50,000. 266 | ``` 267 | 268 | ### [Perform String Shifts](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week2-performStringShifts.go) [(Test Case)](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week2-performStringShifts_test.go) 269 | ``` 270 | You are given a string s containing lowercase English letters, and a matrix shift, where shift[i] = [direction, amount]: 271 | direction can be 0 (for left shift) or 1 (for right shift). 272 | amount is the amount by which string s is to be shifted. 273 | A left shift by 1 means remove the first character of s and append it to the end. 274 | Similarly, a right shift by 1 means remove the last character of s and add it to the beginning. 275 | Return the final string after all operations. 276 | Example 1: 277 | Input: s = "abc", shift = [[0,1],[1,2]] 278 | Output: "cab" 279 | Explanation: 280 | [0,1] means shift to left by 1. "abc" -> "bca" 281 | [1,2] means shift to right by 2. "bca" -> "cab" 282 | Example 2: 283 | Input: s = "abcdefg", shift = [[1,1],[1,1],[0,2],[1,3]] 284 | Output: "efgabcd" 285 | Explanation: 286 | [1,1] means shift to right by 1. "abcdefg" -> "gabcdef" 287 | [1,1] means shift to right by 1. "gabcdef" -> "fgabcde" 288 | [0,2] means shift to left by 2. "fgabcde" -> "abcdefg" 289 | [1,3] means shift to right by 3. "abcdefg" -> "efgabcd" 290 | Constraints: 291 | 1 <= s.length <= 100 292 | s only contains lower case English letters. 293 | 1 <= shift.length <= 100 294 | shift[i].length == 2 295 | 0 <= shift[i][0] <= 1 296 | 0 <= shift[i][1] <= 100 297 | Hide Hint #1 298 | Intuitively performing all shift operations is acceptable due to the constraints. 299 | Hide Hint #2 300 | You may notice that left shift cancels the right shift, so count the total left shift times (may be negative if the final result is right shift), and perform it once. 301 | 302 | ``` 303 | 304 | ## Week 3: Week 3: April 15th–April 21st 305 | ### [Leftmost Column with at Least a One](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week3-leftmostColumnwithatLeastaOne.go) [(Test Case)](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week3-leftmostColumnwithatLeastaOne_test.go) 306 | ``` 307 | (This problem is an interactive problem.) 308 | A binary matrix means that all elements are 0 or 1. For each individual row of the matrix, this row is sorted in non-decreasing order. 309 | Given a row-sorted binary matrix binaryMatrix, return leftmost column index(0-indexed) with at least a 1 in it. If such index doesn't exist, return -1. 310 | You can't access the Binary Matrix directly. You may only access the matrix using a BinaryMatrix interface: 311 | BinaryMatrix.get(x, y) returns the element of the matrix at index (x, y) (0-indexed). 312 | BinaryMatrix.dimensions() returns a list of 2 elements [n, m], which means the matrix is n * m. 313 | Submissions making more than 1000 calls to BinaryMatrix.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification. 314 | For custom testing purposes you're given the binary matrix mat as input in the following four examples. You will not have access the binary matrix directly. 315 | Example 1: 316 | Input: mat = [[0,0],[1,1]] 317 | Output: 0 318 | Example 2: 319 | Input: mat = [[0,0],[0,1]] 320 | Output: 1 321 | Example 3: 322 | Input: mat = [[0,0],[0,0]] 323 | Output: -1 324 | Example 4: 325 | Input: mat = [[0,0,0,1],[0,0,1,1],[0,1,1,1]] 326 | Output: 1 327 | Constraints: 328 | 1 <= mat.length, mat[i].length <= 100 329 | mat[i][j] is either 0 or 1. 330 | mat[i] is sorted in a non-decreasing way. 331 | Hide Hint #1 332 | 1. (Binary Search) For each row do a binary search to find the leftmost one on that row and update the answer. 333 | Hide Hint #2 334 | 2. (Optimal Approach) Imagine there is a pointer p(x, y) starting from top right corner. p can only move left or down. If the value at p is 0, move down. If the value at p is 1, move left. Try to figure out the correctness and time complexity of this algorithm. 335 | ``` 336 | 337 | ### [Valid Parenthesis String](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week3-validParenthesisString.go) [(Test Case)](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week3-validParenthesisString_test.go) 338 | ``` 339 | Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules: 340 | Any left parenthesis '(' must have a corresponding right parenthesis ')'. 341 | Any right parenthesis ')' must have a corresponding left parenthesis '('. 342 | Left parenthesis '(' must go before the corresponding right parenthesis ')'. 343 | '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string. 344 | An empty string is also valid. 345 | Example 1: 346 | Input: "()" 347 | Output: True 348 | Example 2: 349 | Input: "(*)" 350 | Output: True 351 | Example 3: 352 | Input: "(*))" 353 | Output: True 354 | Note: 355 | The string size will be in the range [1, 100]. 356 | ``` 357 | 358 | ### [Number of Islands](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week3-numberofIslands.go) [(Test Case)](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week3-numberofIslands_test.go) 359 | ``` 360 | Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. 361 | Example 1: 362 | Input: 363 | 11110 364 | 11010 365 | 11000 366 | 00000 367 | Output: 1 368 | Example 2: 369 | Input: 370 | 11000 371 | 11000 372 | 00100 373 | 00011 374 | Output: 3 375 | ``` 376 | 377 | ### [Minimum Path Sum](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week3-minimumPathSum.go) [(Test Case)](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week3-minimumPathSum_test.go) 378 | ``` 379 | Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. 380 | Note: You can only move either down or right at any point in time. 381 | Example: 382 | Input: 383 | [ 384 | [1,3,1], 385 | [1,5,1], 386 | [4,2,1] 387 | ] 388 | Output: 7 389 | Explanation: Because the path 1→3→1→1→1 minimizes the sum. 390 | ``` 391 | 392 | ### [Searchin Rotated Sorted Array](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week3-searchinRotatedSortedArray.go) [(Test Case)](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week3-searchinRotatedSortedArray_test.go) 393 | ``` 394 | Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 395 | (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). 396 | You are given a target value to search. If found in the array return its index, otherwise return -1. 397 | You may assume no duplicate exists in the array. 398 | Your algorithm's runtime complexity must be in the order of O(log n). 399 | Example 1: 400 | Input: nums = [4,5,6,7,0,1,2], target = 0 401 | Output: 4 402 | Example 2: 403 | Input: nums = [4,5,6,7,0,1,2], target = 3 404 | Output: -1 405 | ``` 406 | 407 | ### [Construct Binary Search Tree from Preorder Traversal](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week3-constructBinarySearchTreefromPreorderTraversal.go) 408 | ``` 409 | Return the node node of a binary search tree that matches the given preorder traversal. 410 | (Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val. Also recall that a preorder traversal displays the value of the node first, then traverses node.left, then traverses node.right.) 411 | Example 1: 412 | Input: [8,5,1,7,10,12] 413 | Output: [8,5,10,1,7,null,12] 414 | 8 415 | / \ 416 | 5 10 417 | / \ \ 418 | 1 7 12 419 | Note: 420 | 1 <= preorder.length <= 100 421 | The values of preorder are distinct. 422 | ``` 423 | 424 | ## Week 4: April 22nd–April 28th 425 | ### [Subarray Sum Equals K](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week4-subarraySumEqualsK.go) [(Test Case)](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week4-subarraySumEqualsK_test.go) 426 | ``` 427 | Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. 428 | Example 1: 429 | Input:nums = [1,1,1], k = 2 430 | Output: 2 431 | Note: 432 | The length of the array is in range [1, 20,000]. 433 | The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7]. 434 | Hide Hint #1 435 | Will Brute force work here? Try to optimize it. 436 | Hide Hint #2 437 | Can we optimize it by using some extra space? 438 | Hide Hint #3 439 | What about storing sum frequencies in a hash table? Will it be useful? 440 | Hide Hint #4 441 | sum(i,j)=sum(0,j)-sum(0,i), where sum(i,j) represents the sum of all the elements from index i to j-1. Can we use this property to optimize it. 442 | https://leetcode.com/problems/subarray-sum-equals-k/solution/ 443 | ``` 444 | 445 | ### [Product of Array Except Self](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week3-productofArrayExceptSelf.go) [(Test Case)](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week3-productofArrayExceptSelf_test.go) 446 | ``` 447 | Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. 448 | Example: 449 | Input: [1,2,3,4] 450 | Output: [24,12,8,6] 451 | Constraint: It's guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer. 452 | Note: Please solve it without division and in O(n). 453 | Follow up: 454 | Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.) 455 | 456 | ``` 457 | 458 | ### [Subarray Sum Equals K](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week4-bitwiseANDofNumbersRange.go) [(Test Case)](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week4-bitwiseANDofNumbersRange_test.go) 459 | ``` 460 | Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. 461 | Example 1: 462 | Input: [5,7] 463 | Output: 4 464 | Example 2: 465 | Input: [0,1] 466 | Output: 0 467 | ``` 468 | 469 | ### [LRU Cache](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week4-LRU_Cache.go) 470 | ``` 471 | Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put. 472 | get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. 473 | put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item. 474 | The cache is initialized with a positive capacity. 475 | Follow up: 476 | Could you do both operations in O(1) time complexity? 477 | Example: 478 | LRUCache cache = new LRUCache( 2 /* capacity */ ); 479 | cache.put(1, 1); 480 | cache.put(2, 2); 481 | cache.get(1); // returns 1 482 | cache.put(3, 3); // evicts key 2 483 | cache.get(2); // returns -1 (not found) 484 | cache.put(4, 4); // evicts key 1 485 | cache.get(1); // returns -1 (not found) 486 | cache.get(3); // returns 3 487 | cache.get(4); // returns 4 488 | ``` 489 | ex: 490 | ``` 491 | cache := Constructor(2 /* capacity */) 492 | cache.Put(1, 1) 493 | cache.Put(2, 2) 494 | fmt.Println(cache.Get(1)) // returns 1 495 | cache.Put(3, 3) // evicts key 2 496 | fmt.Println(cache.Get(2)) // returns -1 (not found) 497 | cache.Put(4, 4) // evicts key 1 498 | fmt.Println(cache.Get(1)) // returns -1 (not found) 499 | fmt.Println(cache.Get(3)) // returns 3 500 | fmt.Println(cache.Get(4)) // returns 4 501 | ``` 502 | 503 | ### [Jump Game](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week4-jumpGame.go) [(Test Case)](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week4-jumpGame_test.go) 504 | ``` 505 | Given an array of non-negative integers, you are initially positioned at the first index of the array. 506 | Each element in the array represents your maximum jump length at that position. 507 | Determine if you are able to reach the last index. 508 | Example 1: 509 | Input: [2,3,1,1,4] 510 | Output: true 511 | Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. 512 | Example 2: 513 | Input: [3,2,1,0,4] 514 | Output: false 515 | Explanation: You will always arrive at index 3 no matter what. Its maximum 516 | jump length is 0, which makes it impossible to reach the last index. 517 | ``` 518 | 519 | ### [Longest Common Subsequence](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week4-longestCommonSubsequence.go) [(Test Case)](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week4-longestCommonSubsequence_test.go) 520 | ``` 521 | Given two strings text1 and text2, return the length of their longest common subsequence. 522 | A subsequence of a string is a new string generated from the original string with some characters(can be none) deleted without changing the relative order of the remaining characters. (eg, "ace" is a subsequence of "abcde" while "aec" is not). A common subsequence of two strings is a subsequence that is common to both strings. 523 | If there is no common subsequence, return 0. 524 | Example 1: 525 | Input: text1 = "abcde", text2 = "ace" 526 | Output: 3 527 | Explanation: The longest common subsequence is "ace" and its length is 3. 528 | Example 2: 529 | Input: text1 = "abc", text2 = "abc" 530 | Output: 3 531 | Explanation: The longest common subsequence is "abc" and its length is 3. 532 | Example 3: 533 | Input: text1 = "abc", text2 = "def" 534 | Output: 0 535 | Explanation: There is no such common subsequence, so the result is 0. 536 | Constraints: 537 | 1 <= text1.length <= 1000 538 | 1 <= text2.length <= 1000 539 | The input strings consist of lowercase English characters only. 540 | Hide Hint #1 541 | Try dynamic programming. DP[i][j] represents the longest common subsequence of text1[0 ... i] & text2[0 ... j]. 542 | Hide Hint #2 543 | DP[i][j] = DP[i - 1][j - 1] + 1 , if text1[i] == text2[j] DP[i][j] = max(DP[i - 1][j], DP[i][j - 1]) , otherwise 544 | ``` 545 | 546 | ### [Maximal Square](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week4-maximalSquare.go) [(Test Case)](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week4-maximalSquare_test.go) 547 | ``` 548 | Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. 549 | Example: 550 | Input: 551 | 1 0 1 0 0 552 | 1 0 1 1 1 553 | 1 1 1 1 1 554 | 1 0 0 1 0 555 | Output: 4 556 | ``` 557 | 558 | 559 | ### [Maximal Square](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week4-maximalSquare.go) 560 | ``` 561 | You have a queue of integers, you need to retrieve the first unique integer in the queue. 562 | Implement the FirstUnique class: 563 | FirstUnique(int[] nums) Initializes the object with the numbers in the queue. 564 | int showFirstUnique() returns the value of the first unique integer of the queue, and returns -1 if there is no such integer. 565 | void add(int value) insert value to the queue. 566 | Example 1: 567 | Input: 568 | ["FirstUnique","showFirstUnique","add","showFirstUnique","add","showFirstUnique","add","showFirstUnique"] 569 | [[[2,3,5]],[],[5],[],[2],[],[3],[]] 570 | Output: 571 | [null,2,null,2,null,3,null,-1] 572 | Explanation: 573 | FirstUnique firstUnique = new FirstUnique([2,3,5]); 574 | firstUnique.showFirstUnique(); // return 2 575 | firstUnique.add(5); // the queue is now [2,3,5,5] 576 | firstUnique.showFirstUnique(); // return 2 577 | firstUnique.add(2); // the queue is now [2,3,5,5,2] 578 | firstUnique.showFirstUnique(); // return 3 579 | firstUnique.add(3); // the queue is now [2,3,5,5,2,3] 580 | firstUnique.showFirstUnique(); // return -1 581 | Example 2: 582 | Input: 583 | ["FirstUnique","showFirstUnique","add","add","add","add","add","showFirstUnique"] 584 | [[[7,7,7,7,7,7]],[],[7],[3],[3],[7],[17],[]] 585 | Output: 586 | [null,-1,null,null,null,null,null,17] 587 | Explanation: 588 | FirstUnique firstUnique = new FirstUnique([7,7,7,7,7,7]); 589 | firstUnique.showFirstUnique(); // return -1 590 | firstUnique.add(7); // the queue is now [7,7,7,7,7,7,7] 591 | firstUnique.add(3); // the queue is now [7,7,7,7,7,7,7,3] 592 | firstUnique.add(3); // the queue is now [7,7,7,7,7,7,7,3,3] 593 | firstUnique.add(7); // the queue is now [7,7,7,7,7,7,7,3,3,7] 594 | firstUnique.add(17); // the queue is now [7,7,7,7,7,7,7,3,3,7,17] 595 | firstUnique.showFirstUnique(); // return 17 596 | Example 3: 597 | Input: 598 | ["FirstUnique","showFirstUnique","add","showFirstUnique"] 599 | [[[809]],[],[809],[]] 600 | Output: 601 | [null,809,null,-1] 602 | Explanation: 603 | FirstUnique firstUnique = new FirstUnique([809]); 604 | firstUnique.showFirstUnique(); // return 809 605 | firstUnique.add(809); // the queue is now [809,809] 606 | firstUnique.showFirstUnique(); // return -1 607 | Constraints: 608 | 1 <= nums.length <= 10^5 609 | 1 <= nums[i] <= 10^8 610 | 1 <= value <= 10^8 611 | At most 50000 calls will be made to showFirstUnique and add. 612 | Hide Hint #1 613 | Use doubly Linked list with hashmap of pointers to linked list nodes. add unique number to the linked list. When add is called check if the added number is unique then it have to be added to the linked list and if it is repeated remove it from the linked list if exists. When showFirstUnique is called retrieve the head of the linked list. 614 | Hide Hint #2 615 | Use queue and check that first element of the queue is always unique. 616 | Hide Hint #3 617 | Use set or heap to make running time of each function O(logn). 618 | ``` 619 | example: 620 | ``` 621 | firstUnique := FirstUnique_Constructor([]int{2, 3, 5}) 622 | firstUnique.prt() 623 | firstUnique.ShowFirstUnique() // return -1 624 | firstUnique.Add(5) // the queue is now [7,7,7,7,7,7,7] 625 | firstUnique.prt() 626 | firstUnique.Add(2) // the queue is now [7,7,7,7,7,7,7,3] 627 | firstUnique.prt() 628 | firstUnique.Add(3) // the queue is now [7,7,7,7,7,7,7,3,3] 629 | firstUnique.prt() 630 | firstUnique.ShowFirstUnique() // return 17 631 | ``` 632 | 633 | ## Week 5: April 29th–April 30th 634 | ### [Binary Tree Maximum Path Sum](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week5-binaryTreeMaximumPathSum.go) 635 | ``` 636 | Given a non-empty binary tree, find the maximum path sum. 637 | For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root. 638 | Example 1: 639 | Input: [1,2,3] 640 | 1 641 | / \ 642 | 2 3 643 | Output: 6 644 | Example 2: 645 | Input: [-10,9,20,null,null,15,7] 646 | -10 647 | / \ 648 | 9 20 649 | / \ 650 | 15 7 651 | Output: 42 652 | ``` 653 | 654 | ### [Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree](https://github.com/eehsiao/30-Day-LeetCoding-Challenge/blob/master/week5-checkIfaStringIsaValidSequencefromRoottoLeavesPathinaBinaryTree.go) 655 | ``` 656 | Given a binary tree where each path going from the root to any leaf form a valid sequence, check if a given string is a valid sequence in such binary tree. 657 | We get the given string from the concatenation of an array of integers arr and the concatenation of all values of the nodes along a path results in a sequence in the given binary tree. 658 | Example 1: 659 | Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,1,0,1] 660 | Output: true 661 | Explanation: 662 | The path 0 -> 1 -> 0 -> 1 is a valid sequence (green color in the figure). 663 | Other valid sequences are: 664 | 0 -> 1 -> 1 -> 0 665 | 0 -> 0 -> 0 666 | Example 2: 667 | Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,0,1] 668 | Output: false 669 | Explanation: The path 0 -> 0 -> 1 does not exist, therefore it is not even a sequence. 670 | Example 3: 671 | Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,1,1] 672 | Output: false 673 | Explanation: The path 0 -> 1 -> 1 is a sequence, but it is not a valid sequence. 674 | Constraints: 675 | 1 <= arr.length <= 5000 676 | 0 <= arr[i] <= 9 677 | Each node's value is between [0 - 9]. 678 | Hide Hint #1 679 | Depth-first search (DFS) with the parameters: current node in the binary tree and current position in the array of integers. 680 | Hide Hint #2 681 | When reaching at final position check if it is a leaf node. 682 | ``` -------------------------------------------------------------------------------- /binaryTree.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type TreeNode struct { 6 | Val int 7 | Left *TreeNode 8 | Right *TreeNode 9 | } 10 | 11 | func insertLevelOrder(nums []interface{}, i int) (node *TreeNode) { 12 | if len(nums) > i && nums[i] != nil { 13 | node = &TreeNode{Val: nums[i].(int)} 14 | node.Left = insertLevelOrder(nums, 2*i+1) 15 | node.Right = insertLevelOrder(nums, 2*i+2) 16 | } 17 | 18 | return node 19 | } 20 | 21 | func inOrder(node *TreeNode) { 22 | if node != nil { 23 | inOrder(node.Left) 24 | fmt.Print(node.Val, " > ") 25 | inOrder(node.Right) 26 | } 27 | } 28 | 29 | func preOrder(node *TreeNode) { 30 | if node != nil { 31 | fmt.Print(node.Val, " > ") 32 | preOrder(node.Left) 33 | preOrder(node.Right) 34 | } 35 | } 36 | 37 | func postOrder(node *TreeNode) { 38 | if node != nil { 39 | postOrder(node.Left) 40 | postOrder(node.Right) 41 | fmt.Print(node.Val, " > ") 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /commonFunc.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func max(a, b int) int { 4 | if a > b { 5 | return a 6 | } 7 | return b 8 | } 9 | 10 | func iif(l bool, a interface{}, b interface{}) interface{} { 11 | if l { 12 | return a 13 | } 14 | return b 15 | } -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/eehsiao/30-Day-LeetCoding-Challenge 2 | 3 | go 1.14 4 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | // Author : Eric 2 | // https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/ 3 | 4 | package main 5 | 6 | func main() { 7 | // cache := Constructor(2 /* capacity */) 8 | 9 | // cache.Put(1, 1) 10 | // cache.Put(2, 2) 11 | // fmt.Println(cache.Get(1)) // returns 1 12 | // cache.Put(3, 3) // evicts key 2 13 | // fmt.Println(cache.Get(2)) // returns -1 (not found) 14 | // cache.Put(4, 4) // evicts key 1 15 | // fmt.Println(cache.Get(1)) // returns -1 (not found) 16 | // fmt.Println(cache.Get(3)) // returns 3 17 | // fmt.Println(cache.Get(4)) // returns 4 18 | 19 | // firstUnique := FirstUnique_Constructor([]int{7, 7, 7, 7, 7, 7}) 20 | // firstUnique.prt() 21 | // firstUnique.ShowFirstUnique() // return -1 22 | // firstUnique.Add(7) // the queue is now [7,7,7,7,7,7,7] 23 | // firstUnique.prt() 24 | // firstUnique.Add(3) // the queue is now [7,7,7,7,7,7,7,3] 25 | // firstUnique.prt() 26 | // firstUnique.Add(3) // the queue is now [7,7,7,7,7,7,7,3,3] 27 | // firstUnique.prt() 28 | // firstUnique.Add(7) // the queue is now [7,7,7,7,7,7,7,3,3,7] 29 | // firstUnique.prt() 30 | // firstUnique.Add(17) // the queue is now [7,7,7,7,7,7,7,3,3,7,17] 31 | // firstUnique.prt() 32 | // firstUnique.ShowFirstUnique() // return 17 33 | 34 | firstUnique := FirstUnique_Constructor([]int{2, 3, 5}) 35 | firstUnique.prt() 36 | firstUnique.ShowFirstUnique() // return -1 37 | firstUnique.Add(5) // the queue is now [7,7,7,7,7,7,7] 38 | firstUnique.prt() 39 | firstUnique.Add(2) // the queue is now [7,7,7,7,7,7,7,3] 40 | firstUnique.prt() 41 | firstUnique.Add(3) // the queue is now [7,7,7,7,7,7,7,3,3] 42 | firstUnique.prt() 43 | firstUnique.ShowFirstUnique() // return 17 44 | } 45 | -------------------------------------------------------------------------------- /week1-bestTimetoBuyandSellStockII.go: -------------------------------------------------------------------------------- 1 | // Say you have an array prices for which the ith element is the price of a given stock on day i. 2 | // Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times). 3 | // Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). 4 | // Example 1: 5 | // Input: [7,1,5,3,6,4] 6 | // Output: 7 7 | // Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. 8 | // Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. 9 | // Example 2: 10 | // Input: [1,2,3,4,5] 11 | // Output: 4 12 | // Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. 13 | // Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are 14 | // engaging multiple transactions at the same time. You must sell before buying again. 15 | // Example 3: 16 | // Input: [7,6,4,3,1] 17 | // Output: 0 18 | // Explanation: In this case, no transaction is done, i.e. max profit = 0. 19 | // Constraints: 20 | // 1 <= prices.length <= 3 * 10 ^ 4 21 | // 0 <= prices[i] <= 10 ^ 4 22 | 23 | package main 24 | 25 | func maxProfit(prices []int) int { 26 | var maxProfit int 27 | for i := 1; i < len(prices); i++ { 28 | if prices[i] > prices[i-1] { 29 | maxProfit += prices[i] - prices[i-1] 30 | } 31 | } 32 | return maxProfit 33 | } 34 | -------------------------------------------------------------------------------- /week1-bestTimetoBuyandSellStockII_test.go: -------------------------------------------------------------------------------- 1 | // Say you have an array prices for which the ith element is the price of a given stock on day i. 2 | // Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times). 3 | // Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again). 4 | // Example 1: 5 | // Input: [7,1,5,3,6,4] 6 | // Output: 7 7 | // Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. 8 | // Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. 9 | // Example 2: 10 | // Input: [1,2,3,4,5] 11 | // Output: 4 12 | // Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. 13 | // Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are 14 | // engaging multiple transactions at the same time. You must sell before buying again. 15 | // Example 3: 16 | // Input: [7,6,4,3,1] 17 | // Output: 0 18 | // Explanation: In this case, no transaction is done, i.e. max profit = 0. 19 | // Constraints: 20 | // 1 <= prices.length <= 3 * 10 ^ 4 21 | // 0 <= prices[i] <= 10 ^ 4 22 | 23 | package main 24 | 25 | import "testing" 26 | 27 | func Test_maxProfit(t *testing.T) { 28 | type args struct { 29 | prices []int 30 | } 31 | tests := []struct { 32 | name string 33 | args args 34 | want int 35 | }{ 36 | { 37 | name: "case 1", 38 | args: args{ 39 | prices: []int{7, 1, 5, 3, 6, 4}, 40 | }, 41 | want: 7, 42 | }, 43 | { 44 | name: "case 2", 45 | args: args{ 46 | prices: []int{1, 2, 3, 4, 5}, 47 | }, 48 | want: 4, 49 | }, 50 | { 51 | name: "case 3", 52 | args: args{ 53 | prices: []int{7, 6, 4, 3, 1}, 54 | }, 55 | want: 0, 56 | }, 57 | } 58 | for _, tt := range tests { 59 | t.Run(tt.name, func(t *testing.T) { 60 | if got := maxProfit(tt.args.prices); got != tt.want { 61 | t.Errorf("maxProfit(%v) = %v, want %v", tt.args.prices, got, tt.want) 62 | } 63 | }) 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /week1-countingElements.go: -------------------------------------------------------------------------------- 1 | // Given an integer array arr, count element x such that x + 1 is also in arr. 2 | // If there're duplicates in arr, count them seperately. 3 | // Example 1: 4 | // Input: arr = [1,2,3] 5 | // Output: 2 6 | // Explanation: 1 and 2 are counted cause 2 and 3 are in arr. 7 | // Example 2: 8 | // Input: arr = [1,1,3,3,5,5,7,7] 9 | // Output: 0 10 | // Explanation: No numbers are counted, cause there's no 2, 4, 6, or 8 in arr. 11 | // Example 3: 12 | // Input: arr = [1,3,2,3,5,0] 13 | // Output: 3 14 | // Explanation: 0, 1 and 2 are counted cause 1, 2 and 3 are in arr. 15 | // Example 4: 16 | // Input: arr = [1,1,2,2] 17 | // Output: 2 18 | // Explanation: Two 1s are counted cause 2 is in arr. 19 | // Constraints: 20 | // 1 <= arr.length <= 1000 21 | // 0 <= arr[i] <= 1000 22 | 23 | package main 24 | 25 | func countElements(arr []int) int { 26 | var cnt int 27 | for i := 0; i < len(arr); i++ { 28 | for j := 0; j < len(arr); j++ { 29 | if arr[i]+1 == arr[j] { 30 | cnt++ 31 | break 32 | } 33 | } 34 | } 35 | return cnt 36 | } 37 | -------------------------------------------------------------------------------- /week1-countingElements_test.go: -------------------------------------------------------------------------------- 1 | // Given an integer array arr, count element x such that x + 1 is also in arr. 2 | // If there're duplicates in arr, count them seperately. 3 | // Example 1: 4 | // Input: arr = [1,2,3] 5 | // Output: 2 6 | // Explanation: 1 and 2 are counted cause 2 and 3 are in arr. 7 | // Example 2: 8 | // Input: arr = [1,1,3,3,5,5,7,7] 9 | // Output: 0 10 | // Explanation: No numbers are counted, cause there's no 2, 4, 6, or 8 in arr. 11 | // Example 3: 12 | // Input: arr = [1,3,2,3,5,0] 13 | // Output: 3 14 | // Explanation: 0, 1 and 2 are counted cause 1, 2 and 3 are in arr. 15 | // Example 4: 16 | // Input: arr = [1,1,2,2] 17 | // Output: 2 18 | // Explanation: Two 1s are counted cause 2 is in arr. 19 | // Constraints: 20 | // 1 <= arr.length <= 1000 21 | // 0 <= arr[i] <= 1000 22 | 23 | package main 24 | 25 | import "testing" 26 | 27 | func Test_countElements(t *testing.T) { 28 | type args struct { 29 | arr []int 30 | } 31 | tests := []struct { 32 | name string 33 | args args 34 | want int 35 | }{ 36 | { 37 | name: "case 1", 38 | args: args{ 39 | arr: []int{1, 2, 3}, 40 | }, 41 | want: 2, 42 | }, 43 | { 44 | name: "case 2", 45 | args: args{ 46 | arr: []int{1, 1, 3, 3, 5, 5, 7, 7}, 47 | }, 48 | want: 0, 49 | }, 50 | { 51 | name: "case 3", 52 | args: args{ 53 | arr: []int{1, 3, 2, 3, 5, 0}, 54 | }, 55 | want: 3, 56 | }, 57 | { 58 | name: "case 4", 59 | args: args{ 60 | arr: []int{1, 1, 2, 2}, 61 | }, 62 | want: 2, 63 | }, 64 | } 65 | for _, tt := range tests { 66 | t.Run(tt.name, func(t *testing.T) { 67 | if got := countElements(tt.args.arr); got != tt.want { 68 | t.Errorf("countElements(%v) = %v, want %v", tt.args.arr, got, tt.want) 69 | } 70 | }) 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /week1-groupAnagrams.go: -------------------------------------------------------------------------------- 1 | // Given an array of strings, group anagrams together. 2 | // Example: 3 | // Input: ["eat", "tea", "tan", "ate", "nat", "bat"], 4 | // Output: 5 | // [ 6 | // ["ate","eat","tea"], 7 | // ["nat","tan"], 8 | // ["bat"] 9 | // ] 10 | // Note: 11 | // All inputs will be in lowercase. 12 | // The order of your output does not matter. 13 | 14 | package main 15 | 16 | import ( 17 | "sort" 18 | "strings" 19 | ) 20 | 21 | func groupAnagrams(strs []string) [][]string { 22 | var ( 23 | mapGroup = make(map[string]int) 24 | strGroup [][]string 25 | SortString = func(w string) string { 26 | s := strings.Split(w, "") 27 | sort.Strings(s) 28 | return strings.Join(s, "") 29 | } 30 | ) 31 | 32 | for _, s := range strs { 33 | ss := SortString(s) 34 | if _, ok := mapGroup[ss]; !ok { 35 | mapGroup[ss] = len(strGroup) 36 | strGroup = append(strGroup, []string{s}) 37 | } else { 38 | strGroup[mapGroup[ss]] = append(strGroup[mapGroup[ss]], s) 39 | } 40 | } 41 | 42 | return strGroup 43 | } 44 | -------------------------------------------------------------------------------- /week1-groupAnagrams_test.go: -------------------------------------------------------------------------------- 1 | // Given an array of strings, group anagrams together. 2 | // Example: 3 | // Input: ["eat", "tea", "tan", "ate", "nat", "bat"], 4 | // Output: 5 | // [ 6 | // ["ate","eat","tea"], 7 | // ["nat","tan"], 8 | // ["bat"] 9 | // ] 10 | // Note: 11 | // All inputs will be in lowercase. 12 | // The order of your output does not matter. 13 | 14 | package main 15 | 16 | import ( 17 | "reflect" 18 | "testing" 19 | ) 20 | 21 | func Test_groupAnagrams(t *testing.T) { 22 | type args struct { 23 | strs []string 24 | } 25 | 26 | tests := []struct { 27 | name string 28 | args args 29 | want [][]string 30 | }{ 31 | { 32 | name: "case 1", 33 | args: args{ 34 | strs: []string{"eat", "tea", "tan", "ate", "nat", "bat"}, 35 | }, 36 | want: [][]string{ 37 | {"eat", "tea", "ate"}, 38 | {"tan", "nat"}, 39 | {"bat"}, 40 | }, 41 | }, 42 | } 43 | for _, tt := range tests { 44 | t.Run(tt.name, func(t *testing.T) { 45 | if got := groupAnagrams(tt.args.strs); !reflect.DeepEqual(got, tt.want) { 46 | t.Errorf("groupAnagrams() = %v, want %v", got, tt.want) 47 | } 48 | }) 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /week1-happyNumber.go: -------------------------------------------------------------------------------- 1 | // Write an algorithm to determine if a number n is "happy". 2 | // A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. 3 | // Return True if n is a happy number, and False if not. 4 | // Example: 5 | // Input: 19 6 | // Output: true 7 | // Explanation: 8 | // 12 + 92 = 82 9 | // 82 + 22 = 68 10 | // 62 + 82 = 100 11 | // 12 + 02 + 02 = 1 12 | 13 | package main 14 | 15 | func isHappy(n int) bool { 16 | var ( 17 | runed = make(map[int]struct{}, 0) 18 | happy bool 19 | ) 20 | 21 | for { 22 | if _, ok := runed[n]; ok { 23 | happy = false 24 | break 25 | } 26 | runed[n] = struct{}{} 27 | n = func(n int) (newN int) { 28 | for { 29 | newN += (n % 10) * (n % 10) 30 | if n /= 10; n == 0 { 31 | break 32 | } 33 | } 34 | return 35 | }(n) 36 | if n == 1 { 37 | happy = true 38 | break 39 | } 40 | } 41 | return happy 42 | } 43 | -------------------------------------------------------------------------------- /week1-happyNumber_test.go: -------------------------------------------------------------------------------- 1 | // Write an algorithm to determine if a number n is "happy". 2 | // A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. 3 | // Return True if n is a happy number, and False if not. 4 | // Example: 5 | // Input: 19 6 | // Output: true 7 | // Explanation: 8 | // 12 + 92 = 82 9 | // 82 + 22 = 68 10 | // 62 + 82 = 100 11 | // 12 + 02 + 02 = 1 12 | 13 | package main 14 | 15 | import "testing" 16 | 17 | func Test_isHappy(t *testing.T) { 18 | type args struct { 19 | n int 20 | } 21 | tests := []struct { 22 | name string 23 | args args 24 | want bool 25 | }{ 26 | { 27 | name: "case 1", 28 | args: args{ 29 | n: 19, 30 | }, 31 | want: true, 32 | }, 33 | } 34 | for _, tt := range tests { 35 | t.Run(tt.name, func(t *testing.T) { 36 | if got := isHappy(tt.args.n); got != tt.want { 37 | t.Errorf("isHappy() = %v, want %v", got, tt.want) 38 | } 39 | }) 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /week1-maximumSubarray.go: -------------------------------------------------------------------------------- 1 | // Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. 2 | // Example: 3 | // Input: [-2,1,-3,4,-1,2,1,-5,4], 4 | // Output: 6 5 | // Explanation: [4,-1,2,1] has the largest sum = 6. 6 | // Follow up: 7 | // If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. 8 | 9 | package main 10 | 11 | func maxSubArray(nums []int) int { 12 | var ( 13 | sum, max int = 0, nums[0] 14 | maxSum int = nums[0] 15 | ) 16 | for i, v := range nums { 17 | sum += v 18 | if sum < 0 { 19 | sum = 0 20 | } 21 | if maxSum < sum { 22 | maxSum = sum 23 | } 24 | if i > 0 && nums[i] > max { 25 | max = nums[i] 26 | } 27 | } 28 | if max < 0 { 29 | maxSum = max 30 | } 31 | 32 | return maxSum 33 | } 34 | -------------------------------------------------------------------------------- /week1-maximumSubarray_test.go: -------------------------------------------------------------------------------- 1 | // Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. 2 | // Example: 3 | // Input: [-2,1,-3,4,-1,2,1,-5,4], 4 | // Output: 6 5 | // Explanation: [4,-1,2,1] has the largest sum = 6. 6 | // Follow up: 7 | // If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. 8 | 9 | package main 10 | 11 | import "testing" 12 | 13 | func Test_maxSubArray(t *testing.T) { 14 | type args struct { 15 | nums []int 16 | } 17 | tests := []struct { 18 | name string 19 | args args 20 | want int 21 | }{ 22 | { 23 | name: "case 1", 24 | args: args{ 25 | nums: []int{-2, 1, -3, 4, -1, 2, 1, -5, 4}, 26 | }, 27 | want: 6, 28 | }, 29 | { 30 | name: "case 2", 31 | args: args{ 32 | nums: []int{-2, -1}, 33 | }, 34 | want: -1, 35 | }, 36 | { 37 | name: "case 3", 38 | args: args{ 39 | nums: []int{-1, -2}, 40 | }, 41 | want: -1, 42 | }, 43 | { 44 | name: "case 4", 45 | args: args{ 46 | nums: []int{-1, 2}, 47 | }, 48 | want: 2, 49 | }, 50 | { 51 | name: "case 5", 52 | args: args{ 53 | nums: []int{1, 2}, 54 | }, 55 | want: 3, 56 | }, 57 | { 58 | name: "case 6", 59 | args: args{ 60 | nums: []int{1, -2}, 61 | }, 62 | want: 1, 63 | }, 64 | { 65 | name: "case 7", 66 | args: args{ 67 | nums: []int{1, 2, -1, -2, 2, 1, -2, 1}, 68 | }, 69 | want: 3, 70 | }, 71 | { 72 | name: "case 8", 73 | args: args{ 74 | nums: []int{1}, 75 | }, 76 | want: 1, 77 | }, 78 | { 79 | name: "case 9", 80 | args: args{ 81 | nums: []int{0, -3, 1, 1}, 82 | }, 83 | want: 2, 84 | }, 85 | { 86 | name: "case 10", 87 | args: args{ 88 | nums: []int{0, -3, -2, 1}, 89 | }, 90 | want: 1, 91 | }, 92 | } 93 | for _, tt := range tests { 94 | t.Run(tt.name, func(t *testing.T) { 95 | if got := maxSubArray(tt.args.nums); got != tt.want { 96 | t.Errorf("%v maxSubArray(%v) = %v, want %v", tt.name, tt.args, got, tt.want) 97 | } 98 | }) 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /week1-moveZeroes.go: -------------------------------------------------------------------------------- 1 | // Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. 2 | // Example: 3 | // Input: [0,1,0,3,12] 4 | // Output: [1,3,12,0,0] 5 | // Note: 6 | // You must do this in-place without making a copy of the array. 7 | // Minimize the total number of operations. 8 | // Hide Hint #1 9 | // In-place means we should not be allocating any space for extra array. But we are allowed to modify the existing array. However, as a first step, try coming up with a solution that makes use of additional space. For this problem as well, first apply the idea discussed using an additional array and the in-place solution will pop up eventually. 10 | // Hide Hint #2 11 | // A two-pointer approach could be helpful here. The idea would be to have one pointer for iterating the array and another pointer that just works on the non-zero elements of the array. 12 | 13 | package main 14 | 15 | func moveZeroes(nums []int) { 16 | for i := 0; i < len(nums)-1; i++ { 17 | for j := 0; j < len(nums)-i-1; j++ { 18 | if nums[j] == 0 { 19 | nums[j], nums[j+1] = nums[j+1], nums[j] 20 | } 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /week1-moveZeroes_test.go: -------------------------------------------------------------------------------- 1 | // Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. 2 | // Example: 3 | // Input: [0,1,0,3,12] 4 | // Output: [1,3,12,0,0] 5 | // Note: 6 | // You must do this in-place without making a copy of the array. 7 | // Minimize the total number of operations. 8 | // Hide Hint #1 9 | // In-place means we should not be allocating any space for extra array. But we are allowed to modify the existing array. However, as a first step, try coming up with a solution that makes use of additional space. For this problem as well, first apply the idea discussed using an additional array and the in-place solution will pop up eventually. 10 | // Hide Hint #2 11 | // A two-pointer approach could be helpful here. The idea would be to have one pointer for iterating the array and another pointer that just works on the non-zero elements of the array. 12 | 13 | package main 14 | 15 | import ( 16 | "reflect" 17 | "testing" 18 | ) 19 | 20 | func Test_moveZeroes(t *testing.T) { 21 | type args struct { 22 | nums []int 23 | } 24 | tests := []struct { 25 | name string 26 | args args 27 | want []int 28 | }{ 29 | { 30 | name: "case 1", 31 | args: args{ 32 | nums: []int{0, 1, 0, 3, 12}, 33 | }, 34 | want: []int{1, 3, 12, 0, 0}, 35 | }, 36 | { 37 | name: "case 2", 38 | args: args{ 39 | nums: []int{0, 1, 0}, 40 | }, 41 | want: []int{1, 0, 0}, 42 | }, 43 | { 44 | name: "case 3", 45 | args: args{ 46 | nums: []int{0, 0, 1}, 47 | }, 48 | want: []int{1, 0, 0}, 49 | }, 50 | } 51 | for _, tt := range tests { 52 | t.Run(tt.name, func(t *testing.T) { 53 | moveZeroes(tt.args.nums) 54 | if !reflect.DeepEqual(tt.args.nums, tt.want) { 55 | t.Errorf("%v maxSubArray() = %v, want %v", tt.name, tt.args.nums, tt.want) 56 | } 57 | }) 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /week1-singleNumber.go: -------------------------------------------------------------------------------- 1 | // Given a non-empty array of integers, every element appears twice except for one. Find that single one. 2 | // Note: 3 | // Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 4 | // Example 1: 5 | // Input: [2,2,1] 6 | // Output: 1 7 | // Example 2: 8 | // Input: [4,1,2,1,2] 9 | // Output: 4 10 | 11 | package main 12 | 13 | func singleNumber(nums []int) int { 14 | var ( 15 | singleN = make(map[int]struct{}, 0) 16 | multiN = make(map[int]struct{}, 0) 17 | returnKey int 18 | ) 19 | 20 | for _, n := range nums { 21 | if _, ok := multiN[n]; ok { 22 | continue 23 | } 24 | if _, ok := singleN[n]; ok { 25 | multiN[n] = struct{}{} 26 | delete(singleN, n) 27 | } else { 28 | singleN[n] = struct{}{} 29 | } 30 | } 31 | 32 | for k, _ := range singleN { 33 | returnKey = k 34 | break 35 | } 36 | 37 | return returnKey 38 | } 39 | -------------------------------------------------------------------------------- /week1-singleNumber_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // Given a non-empty array of integers, every element appears twice except for one. Find that single one. 4 | // Note: 5 | // Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 6 | // Example 1: 7 | // Input: [2,2,1] 8 | // Output: 1 9 | // Example 2: 10 | // Input: [4,1,2,1,2] 11 | // Output: 4 12 | 13 | import "testing" 14 | 15 | func Test_singleNumber(t *testing.T) { 16 | type args struct { 17 | nums []int 18 | } 19 | tests := []struct { 20 | name string 21 | args args 22 | want int 23 | }{ 24 | { 25 | name: "case 1", 26 | args: args{ 27 | nums: []int{2, 2, 1}, 28 | }, 29 | want: 1, 30 | }, 31 | { 32 | name: "case 2", 33 | args: args{ 34 | nums: []int{4, 1, 2, 1, 2}, 35 | }, 36 | want: 4, 37 | }, 38 | } 39 | for _, tt := range tests { 40 | t.Run(tt.name, func(t *testing.T) { 41 | if got := singleNumber(tt.args.nums); got != tt.want { 42 | t.Errorf("singleNumber() = %v, want %v", got, tt.want) 43 | } 44 | }) 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /week2-backspaceStringCompare.go: -------------------------------------------------------------------------------- 1 | // Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character. 2 | // Note that after backspacing an empty text, the text will continue empty. 3 | // Example 1: 4 | // Input: S = "ab#c", T = "ad#c" 5 | // Output: true 6 | // Explanation: Both S and T become "ac". 7 | // Example 2: 8 | // Input: S = "ab##", T = "c#d#" 9 | // Output: true 10 | // Explanation: Both S and T become "". 11 | // Example 3: 12 | // Input: S = "a##c", T = "#a#c" 13 | // Output: true 14 | // Explanation: Both S and T become "c". 15 | // Example 4: 16 | // Input: S = "a#c", T = "b" 17 | // Output: false 18 | // Explanation: S becomes "c" while T becomes "b". 19 | // Note: 20 | // 1 <= S.length <= 200 21 | // 1 <= T.length <= 200 22 | // S and T only contain lowercase letters and '#' characters. 23 | // Follow up: 24 | // Can you solve it in O(N) time and O(1) space? 25 | 26 | package main 27 | 28 | import ( 29 | "strings" 30 | ) 31 | 32 | func backspaceCompare(S string, T string) bool { 33 | var ( 34 | s []string = strings.Split(S, "") 35 | t []string = strings.Split(T, "") 36 | compareS string = "" 37 | compareT string = "" 38 | ) 39 | for si, ti, sbi, tbi := 1, 1, 0, 0; ; si, ti = si+1, ti+1 { 40 | if compareS != compareT || (si > len(s) && ti > len(t)) { 41 | break 42 | } 43 | for si <= len(s) { 44 | if s[len(s)-si] == "#" { 45 | sbi++ 46 | } else if sbi > 0 { 47 | sbi-- 48 | } else { 49 | break 50 | } 51 | si++ 52 | } 53 | 54 | for ti <= len(t) { 55 | if t[len(t)-ti] == "#" { 56 | tbi++ 57 | } else if tbi > 0 { 58 | tbi-- 59 | } else { 60 | break 61 | } 62 | ti++ 63 | } 64 | if si <= len(s) { 65 | compareS = s[len(s)-si] + compareS 66 | } 67 | if ti <= len(t) { 68 | compareT = t[len(t)-ti] + compareT 69 | } 70 | } 71 | return compareS == compareT 72 | } 73 | -------------------------------------------------------------------------------- /week2-backspaceStringCompare_test.go: -------------------------------------------------------------------------------- 1 | // Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character. 2 | // Note that after backspacing an empty text, the text will continue empty. 3 | // Example 1: 4 | // Input: S = "ab#c", T = "ad#c" 5 | // Output: true 6 | // Explanation: Both S and T become "ac". 7 | // Example 2: 8 | // Input: S = "ab##", T = "c#d#" 9 | // Output: true 10 | // Explanation: Both S and T become "". 11 | // Example 3: 12 | // Input: S = "a##c", T = "#a#c" 13 | // Output: true 14 | // Explanation: Both S and T become "c". 15 | // Example 4: 16 | // Input: S = "a#c", T = "b" 17 | // Output: false 18 | // Explanation: S becomes "c" while T becomes "b". 19 | // Note: 20 | // 1 <= S.length <= 200 21 | // 1 <= T.length <= 200 22 | // S and T only contain lowercase letters and '#' characters. 23 | // Follow up: 24 | // Can you solve it in O(N) time and O(1) space? 25 | 26 | package main 27 | 28 | import "testing" 29 | 30 | func Test_backspaceCompare(t *testing.T) { 31 | type args struct { 32 | S string 33 | T string 34 | } 35 | tests := []struct { 36 | name string 37 | args args 38 | want bool 39 | }{ 40 | { 41 | name: "case 1", 42 | args: args{ 43 | S: "ab#c", 44 | T: "ad#c", 45 | }, 46 | want: true, 47 | }, 48 | { 49 | name: "case 2", 50 | args: args{ 51 | S: "ab##", 52 | T: "c#d#", 53 | }, 54 | want: true, 55 | }, 56 | { 57 | name: "case 3", 58 | args: args{ 59 | S: "a##c", 60 | T: "#a#c", 61 | }, 62 | want: true, 63 | }, 64 | { 65 | name: "case 4", 66 | args: args{ 67 | S: "a#c", 68 | T: "b", 69 | }, 70 | want: false, 71 | }, 72 | } 73 | for _, tt := range tests { 74 | t.Run(tt.name, func(t *testing.T) { 75 | if got := backspaceCompare(tt.args.S, tt.args.T); got != tt.want { 76 | t.Errorf("%v backspaceCompare(%v,%v) = %v, want %v", tt.name, tt.args.S, tt.args.T, got, tt.want) 77 | } 78 | }) 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /week2-contiguousArray.go: -------------------------------------------------------------------------------- 1 | // Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1. 2 | // Example 1: 3 | // Input: [0,1] 4 | // Output: 2 5 | // Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1. 6 | // Example 2: 7 | // Input: [0,1,0] 8 | // Output: 2 9 | // Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1. 10 | // Note: The length of the given binary array will not exceed 50,000. 11 | 12 | package main 13 | 14 | func findMaxLength(nums []int) int { 15 | var ( 16 | m map[int]int = make(map[int]int) 17 | maxLen, cnt int = 0, 0 18 | ) 19 | m[0] = -1 20 | for i := 0; i < len(nums); i++ { 21 | cnt += iif(nums[i] == 1, 1, -1).(int) 22 | if _, ok := m[cnt]; ok { 23 | maxLen = max(maxLen, i-m[cnt]) 24 | } else { 25 | m[cnt] = i 26 | } 27 | } 28 | return maxLen 29 | } 30 | -------------------------------------------------------------------------------- /week2-contiguousArray_test.go: -------------------------------------------------------------------------------- 1 | // Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1. 2 | // Example 1: 3 | // Input: [0,1] 4 | // Output: 2 5 | // Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1. 6 | // Example 2: 7 | // Input: [0,1,0] 8 | // Output: 2 9 | // Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1. 10 | // Note: The length of the given binary array will not exceed 50,000. 11 | 12 | package main 13 | 14 | import "testing" 15 | 16 | func Test_findMaxLength(t *testing.T) { 17 | type args struct { 18 | nums []int 19 | } 20 | tests := []struct { 21 | name string 22 | args args 23 | want int 24 | }{ 25 | { 26 | name: "case 1", 27 | args: args{ 28 | nums: []int{0, 1}, 29 | }, 30 | want: 2, 31 | }, 32 | { 33 | name: "case 2", 34 | args: args{ 35 | nums: []int{0, 1, 0}, 36 | }, 37 | want: 2, 38 | }, 39 | { 40 | name: "case 3", 41 | args: args{ 42 | nums: []int{0, 0, 1, 0, 0, 0, 1, 1}, 43 | }, 44 | want: 6, 45 | }, 46 | { 47 | name: "case 4", 48 | args: args{ 49 | nums: []int{0, 1, 0, 0, 1, 1, 0}, 50 | }, 51 | want: 6, 52 | }, 53 | } 54 | for _, tt := range tests { 55 | t.Run(tt.name, func(t *testing.T) { 56 | if got := findMaxLength(tt.args.nums); got != tt.want { 57 | t.Errorf("%v findMaxLength() = %v, want %v", tt.name, got, tt.want) 58 | } 59 | }) 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /week2-diameterofBinaryTree.go: -------------------------------------------------------------------------------- 1 | // Diameter of Binary Tree 2 | // Solution 3 | // Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. 4 | // Example: 5 | // Given a binary tree 6 | // 1 7 | // / \ 8 | // 2 3 9 | // / \ 10 | // 4 5 11 | // Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3]. 12 | // Note: The length of path between two nodes is represented by the number of edges between them. 13 | 14 | package main 15 | 16 | func depth(node *TreeNode, ans *int) int { 17 | if node == nil { 18 | return 0 19 | } 20 | L := depth(node.Left, ans) 21 | R := depth(node.Right, ans) 22 | *ans = max(*ans, L+R+1) 23 | return max(L, R) + 1 24 | } 25 | 26 | func diameterOfBinaryTree(root *TreeNode) int { 27 | var ans int = 1 28 | depth(root, &ans) 29 | return ans - 1 30 | } 31 | -------------------------------------------------------------------------------- /week2-diameterofBinaryTree_test.go: -------------------------------------------------------------------------------- 1 | // Diameter of Binary Tree 2 | // Solution 3 | // Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. 4 | // Example: 5 | // Given a binary tree 6 | // 1 7 | // / \ 8 | // 2 3 9 | // / \ 10 | // 4 5 11 | // Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3]. 12 | // Note: The length of path between two nodes is represented by the number of edges between them. 13 | 14 | package main 15 | 16 | import ( 17 | "fmt" 18 | "testing" 19 | ) 20 | 21 | func Test_diameterOfBinaryTree(t *testing.T) { 22 | type args struct { 23 | nums []interface{} 24 | } 25 | tests := []struct { 26 | name string 27 | args args 28 | want int 29 | }{ 30 | { 31 | name: "case 1", 32 | args: args{ 33 | nums: []interface{}{1, 2, 3, 4, 5}, 34 | }, 35 | want: 3, 36 | }, 37 | } 38 | for _, tt := range tests { 39 | t.Run(tt.name, func(t *testing.T) { 40 | root := insertLevelOrder(tt.args.nums, 0) 41 | postOrder(root) 42 | fmt.Println() 43 | if got := diameterOfBinaryTree(root); got != tt.want { 44 | t.Errorf("%v diameterOfBinaryTree() = %v, want %v", tt.name, got, tt.want) 45 | } 46 | }) 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /week2-lastStoneWeight.go: -------------------------------------------------------------------------------- 1 | // We have a collection of stones, each stone has a positive integer weight. 2 | // Each turn, we choose the two heaviest stones and smash them together. Suppose the stones have weights x and y with x <= y. The result of this smash is: 3 | // If x == y, both stones are totally destroyed; 4 | // If x != y, the stone of weight x is totally destroyed, and the stone of weight y has new weight y-x. 5 | // At the end, there is at most 1 stone left. Return the weight of this stone (or 0 if there are no stones left.) 6 | // Example 1: 7 | // Input: [2,7,4,1,8,1] 8 | // Output: 1 9 | // Explanation: 10 | // We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then, 11 | // we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then, 12 | // we combine 2 and 1 to get 1 so the array converts to [1,1,1] then, 13 | // we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of last stone. 14 | // Note: 15 | // 1 <= stones.length <= 30 16 | // 1 <= stones[i] <= 1000 17 | // Hide Hint #1 18 | // Simulate the process. We can do it with a heap, or by sorting some list of stones every time we take a turn. 19 | 20 | package main 21 | 22 | func lastStoneWeight(stones []int) int { 23 | 24 | var getMaxStone = func() (maxStone, secondStone, maxIdx int) { 25 | var secondIdx int 26 | maxStone = stones[0] 27 | for i := 1; i < len(stones); i++ { 28 | if stones[i] >= maxStone { 29 | secondStone = maxStone 30 | secondIdx = maxIdx 31 | maxStone = stones[i] 32 | maxIdx = i 33 | } else if stones[i] > secondStone { 34 | secondStone = stones[i] 35 | secondIdx = i 36 | } 37 | } 38 | 39 | if maxStone >= secondStone && secondStone > 0 { 40 | stones = append(stones[:secondIdx], stones[secondIdx+1:]...) 41 | if maxIdx > secondIdx { 42 | maxIdx-- 43 | } 44 | } 45 | return 46 | } 47 | 48 | for len(stones) > 1 { 49 | y, x, yIdx := getMaxStone() 50 | if x == y { 51 | if len(stones) > 1 { 52 | stones = append(stones[:yIdx], stones[yIdx+1:]...) 53 | } else { 54 | return 0 55 | } 56 | } else { 57 | stones[yIdx] = y - x 58 | } 59 | } 60 | return stones[0] 61 | } 62 | -------------------------------------------------------------------------------- /week2-lastStoneWeight_test.go: -------------------------------------------------------------------------------- 1 | // We have a collection of stones, each stone has a positive integer weight. 2 | // Each turn, we choose the two heaviest stones and smash them together. Suppose the stones have weights x and y with x <= y. The result of this smash is: 3 | // If x == y, both stones are totally destroyed; 4 | // If x != y, the stone of weight x is totally destroyed, and the stone of weight y has new weight y-x. 5 | // At the end, there is at most 1 stone left. Return the weight of this stone (or 0 if there are no stones left.) 6 | // Example 1: 7 | // Input: [2,7,4,1,8,1] 8 | // Output: 1 9 | // Explanation: 10 | // We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then, 11 | // we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then, 12 | // we combine 2 and 1 to get 1 so the array converts to [1,1,1] then, 13 | // we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of last stone. 14 | // Note: 15 | // 1 <= stones.length <= 30 16 | // 1 <= stones[i] <= 1000 17 | // Hide Hint #1 18 | // Simulate the process. We can do it with a heap, or by sorting some list of stones every time we take a turn. 19 | 20 | package main 21 | 22 | import "testing" 23 | 24 | func Test_lastStoneWeight(t *testing.T) { 25 | type args struct { 26 | stones []int 27 | } 28 | tests := []struct { 29 | name string 30 | args args 31 | want int 32 | }{ 33 | { 34 | name: "case 1", 35 | args: args{ 36 | stones: []int{2, 7, 4, 1, 8, 1}, 37 | }, 38 | want: 1, 39 | }, 40 | { 41 | name: "case 2", 42 | args: args{ 43 | stones: []int{2, 2}, 44 | }, 45 | want: 0, 46 | }, 47 | } 48 | for _, tt := range tests { 49 | t.Run(tt.name, func(t *testing.T) { 50 | if got := lastStoneWeight(tt.args.stones); got != tt.want { 51 | t.Errorf("lastStoneWeight() = %v, want %v", got, tt.want) 52 | } 53 | }) 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /week2-middleoftheLinkedList.go: -------------------------------------------------------------------------------- 1 | // Given a non-empty, singly linked list with head node head, return a middle node of linked list. 2 | // If there are two middle nodes, return the second middle node. 3 | // Example 1: 4 | // Input: [1,2,3,4,5] 5 | // Output: Node 3 from this list (Serialization: [3,4,5]) 6 | // The returned node has value 3. (The judge's serialization of this node is [3,4,5]). 7 | // Note that we returned a ListNode object ans, such that: 8 | // ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL. 9 | // Example 2: 10 | // Input: [1,2,3,4,5,6] 11 | // Output: Node 4 from this list (Serialization: [4,5,6]) 12 | // Since the list has two middle nodes with values 3 and 4, we return the second one. 13 | // Note: 14 | // The number of nodes in the given list will be between 1 and 100. 15 | 16 | package main 17 | 18 | type ListNode struct { 19 | Val int 20 | Next *ListNode 21 | } 22 | 23 | func middleNode(head *ListNode) *ListNode { 24 | var ( 25 | step1, step2 *ListNode = head, head 26 | ) 27 | for step2 != nil && step2.Next != nil { 28 | step1 = step1.Next 29 | step2 = step2.Next.Next 30 | } 31 | return step1 32 | } 33 | -------------------------------------------------------------------------------- /week2-middleoftheLinkedList_test.go: -------------------------------------------------------------------------------- 1 | // Given a non-empty, singly linked list with head node head, return a middle node of linked list. 2 | // If there are two middle nodes, return the second middle node. 3 | // Example 1: 4 | // Input: [1,2,3,4,5] 5 | // Output: Node 3 from this list (Serialization: [3,4,5]) 6 | // The returned node has value 3. (The judge's serialization of this node is [3,4,5]). 7 | // Note that we returned a ListNode object ans, such that: 8 | // ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL. 9 | // Example 2: 10 | // Input: [1,2,3,4,5,6] 11 | // Output: Node 4 from this list (Serialization: [4,5,6]) 12 | // Since the list has two middle nodes with values 3 and 4, we return the second one. 13 | // Note: 14 | // The number of nodes in the given list will be between 1 and 100. 15 | 16 | package main 17 | 18 | import ( 19 | "reflect" 20 | "testing" 21 | ) 22 | 23 | func Test_middleNode(t *testing.T) { 24 | type args struct { 25 | head *ListNode 26 | } 27 | tests := []struct { 28 | name string 29 | args args 30 | want *ListNode 31 | }{ 32 | { 33 | name: "case 1", 34 | args: args{ 35 | head: &ListNode{1, &ListNode{2, &ListNode{3, &ListNode{4, &ListNode{5, nil}}}}}, 36 | }, 37 | want: &ListNode{3, &ListNode{4, &ListNode{5, nil}}}, 38 | }, 39 | { 40 | name: "case 2", 41 | args: args{ 42 | head: &ListNode{1, &ListNode{2, &ListNode{3, &ListNode{4, &ListNode{5, &ListNode{6, nil}}}}}}, 43 | }, 44 | want: &ListNode{4, &ListNode{5, &ListNode{6, nil}}}, 45 | }, 46 | } 47 | for _, tt := range tests { 48 | t.Run(tt.name, func(t *testing.T) { 49 | if got := middleNode(tt.args.head); !reflect.DeepEqual(got, tt.want) { 50 | t.Errorf("middleNode() = %v, want %v", got, tt.want) 51 | } 52 | }) 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /week2-minStack.go: -------------------------------------------------------------------------------- 1 | // Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. 2 | // push(x) -- Push element x onto stack. 3 | // pop() -- Removes the element on top of the stack. 4 | // top() -- Get the top element. 5 | // getMin() -- Retrieve the minimum element in the stack. 6 | // Example 1: 7 | // Input 8 | // ["MinStack","push","push","push","getMin","pop","top","getMin"] 9 | // [[],[-2],[0],[-3],[],[],[],[]] 10 | // Output 11 | // [null,null,null,null,-3,null,0,-2] 12 | // Explanation 13 | // MinStack minStack = new MinStack(); 14 | // minStack.push(-2); 15 | // minStack.push(0); 16 | // minStack.push(-3); 17 | // minStack.getMin(); // return -3 18 | // minStack.pop(); 19 | // minStack.top(); // return 0 20 | // minStack.getMin(); // return -2 21 | // Constraints: 22 | // Methods pop, top and getMin operations will always be called on non-empty stacks. 23 | // Hide Hint #1 24 | // Consider each node in the stack having a minimum value. (Credits to @aakarshmadhavan) 25 | 26 | package main 27 | 28 | /** 29 | * Your MinStack object will be instantiated and called as such: 30 | * obj := Constructor(); 31 | * obj.Push(x); 32 | * obj.Pop(); 33 | * param_3 := obj.Top(); 34 | * param_4 := obj.GetMin(); 35 | */ 36 | 37 | type MinStack struct { 38 | data []int 39 | } 40 | 41 | /** initialize your data structure here. */ 42 | func MinStack_Constructor() MinStack { 43 | return MinStack{} 44 | } 45 | 46 | func (this *MinStack) Push(x int) { 47 | this.data = append(this.data, x) 48 | } 49 | 50 | func (this *MinStack) Pop() { 51 | this.data = this.data[:len(this.data)-1] 52 | } 53 | 54 | func (this *MinStack) Top() int { 55 | return this.data[len(this.data)-1] 56 | } 57 | 58 | func (this *MinStack) GetMin() int { 59 | min := this.data[0] 60 | for i := 1; i < len(this.data); i++ { 61 | if min > this.data[i] { 62 | min = this.data[i] 63 | } 64 | } 65 | return min 66 | } 67 | -------------------------------------------------------------------------------- /week2-performStringShifts.go: -------------------------------------------------------------------------------- 1 | // You are given a string s containing lowercase English letters, and a matrix shift, where shift[i] = [direction, amount]: 2 | // direction can be 0 (for left shift) or 1 (for right shift). 3 | // amount is the amount by which string s is to be shifted. 4 | // A left shift by 1 means remove the first character of s and append it to the end. 5 | // Similarly, a right shift by 1 means remove the last character of s and add it to the beginning. 6 | // Return the final string after all operations. 7 | // Example 1: 8 | // Input: s = "abc", shift = [[0,1],[1,2]] 9 | // Output: "cab" 10 | // Explanation: 11 | // [0,1] means shift to left by 1. "abc" -> "bca" 12 | // [1,2] means shift to right by 2. "bca" -> "cab" 13 | // Example 2: 14 | // Input: s = "abcdefg", shift = [[1,1],[1,1],[0,2],[1,3]] 15 | // Output: "efgabcd" 16 | // Explanation: 17 | // [1,1] means shift to right by 1. "abcdefg" -> "gabcdef" 18 | // [1,1] means shift to right by 1. "gabcdef" -> "fgabcde" 19 | // [0,2] means shift to left by 2. "fgabcde" -> "abcdefg" 20 | // [1,3] means shift to right by 3. "abcdefg" -> "efgabcd" 21 | // Constraints: 22 | // 1 <= s.length <= 100 23 | // s only contains lower case English letters. 24 | // 1 <= shift.length <= 100 25 | // shift[i].length == 2 26 | // 0 <= shift[i][0] <= 1 27 | // 0 <= shift[i][1] <= 100 28 | // Hide Hint #1 29 | // Intuitively performing all shift operations is acceptable due to the constraints. 30 | // Hide Hint #2 31 | // You may notice that left shift cancels the right shift, so count the total left shift times (may be negative if the final result is right shift), and perform it once. 32 | 33 | package main 34 | 35 | import ( 36 | "math" 37 | "strings" 38 | ) 39 | 40 | func stringShift(s string, shift [][]int) string { 41 | var shiftD int 42 | for i := 0; i < len(shift); i++ { 43 | if shift[i][0] == 0 { 44 | shiftD -= shift[i][1] 45 | } else { 46 | shiftD += shift[i][1] 47 | } 48 | } 49 | ss := strings.Split(s, "") 50 | for j := 0; j < int(math.Abs(float64(shiftD))); j++ { 51 | if shiftD > 0 { 52 | ss = append([]string{ss[len(ss)-1]}, ss[:len(ss)-1]...) 53 | } else { 54 | ss = append(ss[1:], ss[0]) 55 | } 56 | } 57 | 58 | return strings.Join(ss, "") 59 | } 60 | -------------------------------------------------------------------------------- /week2-performStringShifts_test.go: -------------------------------------------------------------------------------- 1 | // You are given a string s containing lowercase English letters, and a matrix shift, where shift[i] = [direction, amount]: 2 | // direction can be 0 (for left shift) or 1 (for right shift). 3 | // amount is the amount by which string s is to be shifted. 4 | // A left shift by 1 means remove the first character of s and append it to the end. 5 | // Similarly, a right shift by 1 means remove the last character of s and add it to the beginning. 6 | // Return the final string after all operations. 7 | // Example 1: 8 | // Input: s = "abc", shift = [[0,1],[1,2]] 9 | // Output: "cab" 10 | // Explanation: 11 | // [0,1] means shift to left by 1. "abc" -> "bca" 12 | // [1,2] means shift to right by 2. "bca" -> "cab" 13 | // Example 2: 14 | // Input: s = "abcdefg", shift = [[1,1],[1,1],[0,2],[1,3]] 15 | // Output: "efgabcd" 16 | // Explanation: 17 | // [1,1] means shift to right by 1. "abcdefg" -> "gabcdef" 18 | // [1,1] means shift to right by 1. "gabcdef" -> "fgabcde" 19 | // [0,2] means shift to left by 2. "fgabcde" -> "abcdefg" 20 | // [1,3] means shift to right by 3. "abcdefg" -> "efgabcd" 21 | // Constraints: 22 | // 1 <= s.length <= 100 23 | // s only contains lower case English letters. 24 | // 1 <= shift.length <= 100 25 | // shift[i].length == 2 26 | // 0 <= shift[i][0] <= 1 27 | // 0 <= shift[i][1] <= 100 28 | // Hide Hint #1 29 | // Intuitively performing all shift operations is acceptable due to the constraints. 30 | // Hide Hint #2 31 | // You may notice that left shift cancels the right shift, so count the total left shift times (may be negative if the final result is right shift), and perform it once. 32 | 33 | package main 34 | 35 | import "testing" 36 | 37 | func Test_stringShift(t *testing.T) { 38 | type args struct { 39 | s string 40 | shift [][]int 41 | } 42 | tests := []struct { 43 | name string 44 | args args 45 | want string 46 | }{ 47 | { 48 | name: "case 1", 49 | args: args{ 50 | s: "abc", 51 | shift: [][]int{{0, 1}, {1, 2}}, 52 | }, 53 | want: "cab", 54 | }, 55 | { 56 | name: "case 2", 57 | args: args{ 58 | s: "abcdefg", 59 | shift: [][]int{{1, 1}, {1, 1}, {0, 2}, {1, 3}}, 60 | }, 61 | want: "efgabcd", 62 | }, 63 | } 64 | for _, tt := range tests { 65 | t.Run(tt.name, func(t *testing.T) { 66 | if got := stringShift(tt.args.s, tt.args.shift); got != tt.want { 67 | t.Errorf("%v stringShift(%v) = %v, want %v", tt.name, tt.args.s, got, tt.want) 68 | } 69 | }) 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /week3-constructBinarySearchTreefromPreorderTraversal.go: -------------------------------------------------------------------------------- 1 | // Return the node node of a binary search tree that matches the given preorder traversal. 2 | // (Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val. Also recall that a preorder traversal displays the value of the node first, then traverses node.left, then traverses node.right.) 3 | // Example 1: 4 | // Input: [8,5,1,7,10,12] 5 | // Output: [8,5,10,1,7,null,12] 6 | // 8 7 | // / \ 8 | // 5 10 9 | // / \ \ 10 | // 1 7 12 11 | // Note: 12 | // 1 <= preorder.length <= 100 13 | // The values of preorder are distinct. 14 | 15 | package main 16 | 17 | // defin in week2-diameterofBinaryTree.go 18 | // type TreeNode struct { 19 | // Val int 20 | // Left *TreeNode 21 | // Right *TreeNode 22 | // } 23 | 24 | var order []int 25 | 26 | func bstFromPreorder(preorder []int) *TreeNode { 27 | var bTree *TreeNode 28 | 29 | order = make([]int, 0) 30 | for _, v := range preorder { 31 | newNode := &TreeNode{ 32 | Val: v, 33 | } 34 | 35 | if bTree == nil { 36 | bTree = newNode 37 | continue 38 | } 39 | node := bTree 40 | for { 41 | if node.Val > v { 42 | if node.Left != nil { 43 | node = node.Left 44 | } else { 45 | node.Left = newNode 46 | break 47 | } 48 | } else { 49 | if node.Right != nil { 50 | node = node.Right 51 | } else { 52 | node.Right = newNode 53 | break 54 | } 55 | } 56 | } 57 | } 58 | 59 | return bTree 60 | } 61 | -------------------------------------------------------------------------------- /week3-leftmostColumnwithatLeastaOne.go: -------------------------------------------------------------------------------- 1 | // (This problem is an interactive problem.) 2 | // A binary matrix means that all elements are 0 or 1. For each individual row of the matrix, this row is sorted in non-decreasing order. 3 | // Given a row-sorted binary matrix binaryMatrix, return leftmost column index(0-indexed) with at least a 1 in it. If such index doesn't exist, return -1. 4 | // You can't access the Binary Matrix directly. You may only access the matrix using a BinaryMatrix interface: 5 | // BinaryMatrix.get(x, y) returns the element of the matrix at index (x, y) (0-indexed). 6 | // BinaryMatrix.dimensions() returns a list of 2 elements [n, m], which means the matrix is n * m. 7 | // Submissions making more than 1000 calls to BinaryMatrix.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification. 8 | // For custom testing purposes you're given the binary matrix mat as input in the following four examples. You will not have access the binary matrix directly. 9 | // Example 1: 10 | // Input: mat = [[0,0],[1,1]] 11 | // Output: 0 12 | // Example 2: 13 | // Input: mat = [[0,0],[0,1]] 14 | // Output: 1 15 | // Example 3: 16 | // Input: mat = [[0,0],[0,0]] 17 | // Output: -1 18 | // Example 4: 19 | // Input: mat = [[0,0,0,1],[0,0,1,1],[0,1,1,1]] 20 | // Output: 1 21 | // Constraints: 22 | // 1 <= mat.length, mat[i].length <= 100 23 | // mat[i][j] is either 0 or 1. 24 | // mat[i] is sorted in a non-decreasing way. 25 | // Hide Hint #1 26 | // 1. (Binary Search) For each row do a binary search to find the leftmost one on that row and update the answer. 27 | // Hide Hint #2 28 | // 2. (Optimal Approach) Imagine there is a pointer p(x, y) starting from top right corner. p can only move left or down. If the value at p is 0, move down. If the value at p is 1, move left. Try to figure out the correctness and time complexity of this algorithm. 29 | 30 | package main 31 | 32 | type BinaryMatrix struct { 33 | matrix [][]int 34 | } 35 | 36 | func (b BinaryMatrix) Get(x int, y int) int { 37 | return b.matrix[x][y] 38 | } 39 | 40 | func (b BinaryMatrix) Dimensions() (dim []int) { 41 | return append(dim, len(b.matrix), len(b.matrix[0])) 42 | } 43 | 44 | func binarySearch(b BinaryMatrix, x, left, right int) int { 45 | if right > 0 { 46 | mid := left + (right-left)/2 47 | l, r := b.Get(x, mid), b.Get(x, mid+1) 48 | 49 | if l == 0 && r == 1 { 50 | return mid + 1 51 | } 52 | if l == 1 { 53 | return binarySearch(b, x, left, mid) 54 | } 55 | 56 | return binarySearch(b, x, mid, right) 57 | } 58 | 59 | if b.Get(x, 0) == 1 { 60 | return 0 61 | } else { 62 | return -1 63 | } 64 | } 65 | 66 | func leftMostColumnWithOne(binaryMatrix BinaryMatrix) int { 67 | var dim []int = binaryMatrix.Dimensions() 68 | var x, leftMost int = 0, dim[1] - 1 69 | var hit bool 70 | for ; x < dim[0]; x++ { 71 | if binaryMatrix.Get(x, leftMost) == 1 { 72 | hit = true 73 | leftMost = binarySearch(binaryMatrix, x, 0, leftMost) 74 | } 75 | } 76 | if !hit { 77 | leftMost = -1 78 | } 79 | return leftMost 80 | } 81 | -------------------------------------------------------------------------------- /week3-leftmostColumnwithatLeastaOne_test.go: -------------------------------------------------------------------------------- 1 | // (This problem is an interactive problem.) 2 | // A binary matrix means that all elements are 0 or 1. For each individual row of the matrix, this row is sorted in non-decreasing order. 3 | // Given a row-sorted binary matrix binaryMatrix, return leftmost column index(0-indexed) with at least a 1 in it. If such index doesn't exist, return -1. 4 | // You can't access the Binary Matrix directly. You may only access the matrix using a BinaryMatrix interface: 5 | // BinaryMatrix.get(x, y) returns the element of the matrix at index (x, y) (0-indexed). 6 | // BinaryMatrix.dimensions() returns a list of 2 elements [n, m], which means the matrix is n * m. 7 | // Submissions making more than 1000 calls to BinaryMatrix.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification. 8 | // For custom testing purposes you're given the binary matrix mat as input in the following four examples. You will not have access the binary matrix directly. 9 | // Example 1: 10 | // Input: mat = [[0,0],[1,1]] 11 | // Output: 0 12 | // Example 2: 13 | // Input: mat = [[0,0],[0,1]] 14 | // Output: 1 15 | // Example 3: 16 | // Input: mat = [[0,0],[0,0]] 17 | // Output: -1 18 | // Example 4: 19 | // Input: mat = [[0,0,0,1],[0,0,1,1],[0,1,1,1]] 20 | // Output: 1 21 | // Constraints: 22 | // 1 <= mat.length, mat[i].length <= 100 23 | // mat[i][j] is either 0 or 1. 24 | // mat[i] is sorted in a non-decreasing way. 25 | // Hide Hint #1 26 | // 1. (Binary Search) For each row do a binary search to find the leftmost one on that row and update the answer. 27 | // Hide Hint #2 28 | // 2. (Optimal Approach) Imagine there is a pointer p(x, y) starting from top right corner. p can only move left or down. If the value at p is 0, move down. If the value at p is 1, move left. Try to figure out the correctness and time complexity of this algorithm. 29 | 30 | package main 31 | 32 | import "testing" 33 | 34 | func Test_leftMostColumnWithOne(t *testing.T) { 35 | type args struct { 36 | binaryMatrix BinaryMatrix 37 | } 38 | tests := []struct { 39 | name string 40 | args args 41 | want int 42 | }{ 43 | { 44 | name: "case 1", 45 | args: args{ 46 | binaryMatrix: BinaryMatrix{matrix: [][]int{{0, 0}, {1, 1}}}, 47 | }, 48 | want: 0, 49 | }, 50 | { 51 | name: "case 2", 52 | args: args{ 53 | binaryMatrix: BinaryMatrix{matrix: [][]int{{0, 0}, {0, 1}}}, 54 | }, 55 | want: 1, 56 | }, 57 | { 58 | name: "case 3", 59 | args: args{ 60 | binaryMatrix: BinaryMatrix{matrix: [][]int{{0, 0}, {0, 0}}}, 61 | }, 62 | want: -1, 63 | }, 64 | { 65 | name: "case 4", 66 | args: args{ 67 | binaryMatrix: BinaryMatrix{matrix: [][]int{{0, 0, 0, 1}, {0, 0, 1, 1}, {0, 1, 1, 1}}}, 68 | }, 69 | want: 1, 70 | }, 71 | { 72 | name: "case 5", 73 | args: args{ 74 | binaryMatrix: BinaryMatrix{matrix: [][]int{ 75 | {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, 76 | {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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tests { 131 | t.Run(tt.name, func(t *testing.T) { 132 | if got := leftMostColumnWithOne(tt.args.binaryMatrix); got != tt.want { 133 | t.Errorf("%v leftMostColumnWithOne() = %v, want %v", tt.name, got, tt.want) 134 | } 135 | }) 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /week3-minimumPathSum.go: -------------------------------------------------------------------------------- 1 | // Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. 2 | // Note: You can only move either down or right at any point in time. 3 | // Example: 4 | // Input: 5 | // [ 6 | // [1,3,1], 7 | // [1,5,1], 8 | // [4,2,1] 9 | // ] 10 | // Output: 7 11 | // Explanation: Because the path 1→3→1→1→1 minimizes the sum. 12 | 13 | package main 14 | 15 | var min, road [][]int 16 | 17 | func minPath(grid [][]int, from, to int) { 18 | w, d := len(grid[0]), len(grid) 19 | x, y := from%w, from/w 20 | tx, ty := to%w, to/w 21 | 22 | road[ty][tx] = 1 23 | defer func() { 24 | road[ty][tx] = 0 25 | }() 26 | 27 | min[ty][tx] = min[y][x] + grid[ty][tx] 28 | currValue := min[ty][tx] 29 | if to == w*d-1 { 30 | // fmt.Println("-----") 31 | // for i := 0; i < d; i++ { 32 | // fmt.Println(road[i]) 33 | // } 34 | // fmt.Println("-----") 35 | // for i := 0; i < d; i++ { 36 | // fmt.Println(min[i]) 37 | // } 38 | 39 | return 40 | } 41 | if tx+1 < w && (road[ty][tx+1] == 0) && (min[ty][tx+1] == 0 || min[ty][tx+1] > currValue+grid[ty][tx+1]) { 42 | minPath(grid, to, to+1) 43 | } 44 | if ty+1 < d && (road[ty+1][tx] == 0) && (min[ty+1][tx] == 0 || min[ty+1][tx] > currValue+grid[ty+1][tx]) { 45 | minPath(grid, to, to+w) 46 | } 47 | // if tx > 0 && (road[ty][tx-1] == 0) && (min[ty][tx-1] == 0 || min[ty][tx-1] > currValue+grid[ty][tx-1]) { 48 | // minPath(grid, to, to-1) 49 | // } 50 | // if ty > 0 && (road[ty-1][tx] == 0) && (min[ty-1][tx] == 0 || min[ty-1][tx] > currValue+grid[ty-1][tx]) { 51 | // minPath(grid, to, to-w) 52 | // } 53 | } 54 | 55 | func minPathSum(grid [][]int) int { 56 | w, d := 0, 0 57 | min, road = nil, nil 58 | if len(grid) > 0 { 59 | w, d = len(grid[0]), len(grid) 60 | } 61 | if w == 0 || d == 0 { 62 | return 0 63 | } 64 | if w == 1 && d == 1 { 65 | return grid[0][0] 66 | } 67 | for i := 0; i < d; i++ { 68 | min = append(min, make([]int, w)) 69 | road = append(road, make([]int, w)) 70 | } 71 | min[0][0], road[0][0] = grid[0][0], 1 72 | minPath(grid, 0, 1) 73 | 74 | if d > 1 && (min[1][0] == 0 || min[1][0] > grid[0][0]+grid[1][0]) { 75 | min[0][0], road[0][0] = grid[0][0], 1 76 | minPath(grid, 0, w) 77 | } 78 | return min[d-1][w-1] 79 | } 80 | -------------------------------------------------------------------------------- /week3-minimumPathSum_test.go: -------------------------------------------------------------------------------- 1 | // Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. 2 | // Note: You can only move either down or right at any point in time. 3 | // Example: 4 | // Input: 5 | // [ 6 | // [1,3,1], 7 | // [1,5,1], 8 | // [4,2,1] 9 | // ] 10 | // Output: 7 11 | // Explanation: Because the path 1→3→1→1→1 minimizes the sum. 12 | 13 | package main 14 | 15 | import "testing" 16 | 17 | func Test_minPathSum(t *testing.T) { 18 | type args struct { 19 | grid [][]int 20 | } 21 | tests := []struct { 22 | name string 23 | args args 24 | want int 25 | }{ 26 | { 27 | name: "case 1", 28 | args: args{ 29 | grid: [][]int{ 30 | {1, 3, 1}, 31 | {1, 5, 1}, 32 | {4, 2, 1}, 33 | }, 34 | }, 35 | want: 7, 36 | }, 37 | { 38 | name: "case 2", 39 | args: args{ 40 | grid: [][]int{ 41 | {0}, 42 | }, 43 | }, 44 | want: 0, 45 | }, 46 | { 47 | name: "case 3", 48 | args: args{ 49 | grid: [][]int{ 50 | {1, 2}, 51 | {1, 1}, 52 | }, 53 | }, 54 | want: 3, 55 | }, 56 | { 57 | name: "case 4", 58 | args: args{ 59 | grid: [][]int{ 60 | {9, 1, 4, 8}, 61 | }, 62 | }, 63 | want: 22, 64 | }, 65 | { 66 | name: "case 5", 67 | args: args{ 68 | grid: [][]int{ 69 | {7, 0, 8, 8, 0, 3, 5, 8, 5, 4}, 70 | {4, 1, 2, 9, 9, 6, 0, 8, 6, 9}, 71 | {9, 7, 1, 1, 0, 1, 2, 4, 1, 7}, 72 | }, 73 | }, 74 | want: 27, 75 | }, 76 | { 77 | name: "case 6", 78 | args: args{ 79 | grid: [][]int{ 80 | {0, 7, 7, 8, 1, 2, 4, 3, 0, 0, 5, 9, 8, 3, 6, 5, 1, 0}, 81 | {2, 1, 1, 0, 8, 1, 3, 3, 9, 9, 5, 8, 7, 5, 7, 5, 5, 8}, 82 | {9, 2, 3, 1, 2, 8, 1, 2, 3, 7, 9, 7, 9, 3, 0, 0, 3, 8}, 83 | {3, 9, 3, 4, 8, 1, 2, 6, 8, 9, 3, 4, 9, 4, 8, 3, 6, 2}, 84 | {3, 7, 4, 7, 6, 5, 6, 5, 8, 6, 7, 3, 6, 2, 2, 9, 9, 3}, 85 | {2, 3, 1, 1, 5, 4, 7, 4, 0, 7, 7, 6, 9, 1, 5, 5, 0, 3}, 86 | {0, 8, 8, 8, 4, 7, 1, 0, 2, 6, 1, 1, 1, 6, 4, 2, 7, 9}, 87 | {8, 6, 6, 8, 3, 3, 5, 4, 6, 2, 9, 8, 6, 9, 6, 6, 9, 2}, 88 | {6, 2, 2, 8, 0, 6, 1, 1, 4, 5, 3, 1, 7, 3, 9, 3, 2, 2}, 89 | {8, 9, 8, 5, 3, 7, 5, 9, 8, 2, 8, 7, 4, 4, 1, 9, 2, 2}, 90 | {7, 3, 3, 1, 0, 9, 4, 7, 2, 3, 2, 6, 7, 1, 7, 7, 8, 1}, 91 | {4, 3, 2, 2, 7, 0, 1, 4, 4, 4, 3, 8, 6, 2, 1, 2, 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, 2, 7, 1, 5}, 117 | {1, 0, 0, 0, 6, 2, 0, 0, 2, 2, 8, 0, 9, 7, 0, 8, 0}, 118 | {1, 1, 7, 2, 9, 6, 5, 4, 8, 7, 8, 5, 0, 3, 8, 1, 5}, 119 | {8, 9, 7, 8, 1, 1, 3, 0, 1, 2, 9, 4, 0, 1, 5, 3, 1}, 120 | {9, 2, 7, 4, 8, 7, 3, 9, 2, 4, 2, 2, 7, 8, 2, 6, 7}, 121 | {3, 8, 1, 6, 0, 4, 8, 9, 8, 0, 2, 5, 3, 5, 5, 7, 5}, 122 | {1, 8, 2, 5, 7, 7, 1, 9, 9, 8, 9, 2, 4, 9, 5, 4, 0}, 123 | {3, 4, 4, 1, 5, 3, 3, 8, 8, 6, 3, 5, 3, 8, 7, 1, 3}, 124 | }, 125 | }, 126 | want: 82, 127 | }, 128 | } 129 | for _, tt := range tests { 130 | t.Run(tt.name, func(t *testing.T) { 131 | if got := minPathSum(tt.args.grid); got != tt.want { 132 | t.Errorf("%v minPathSum() = %v, want %v", tt.name, got, tt.want) 133 | } 134 | }) 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /week3-numberofIslands.go: -------------------------------------------------------------------------------- 1 | // Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. 2 | // Example 1: 3 | // Input: 4 | // 11110 5 | // 11010 6 | // 11000 7 | // 00000 8 | // Output: 1 9 | // Example 2: 10 | // Input: 11 | // 11000 12 | // 11000 13 | // 00100 14 | // 00011 15 | // Output: 3 16 | 17 | package main 18 | 19 | func island(grid [][]byte, i int, n int) { 20 | w, d := len(grid[0]), len(grid) 21 | x, y := i%w, i/w 22 | 23 | if y > d-1 || grid[y][x] == '0' { 24 | return 25 | } 26 | if grid[y][x] == '1' { 27 | grid[y][x] = 'x' 28 | } 29 | if x+1 < w && grid[y][x+1] == '1' { 30 | island(grid, i+1, n) 31 | } 32 | if x > 0 && grid[y][x-1] == '1' { 33 | island(grid, i-1, n) 34 | } 35 | if y+1 < d { 36 | island(grid, i+w, n) 37 | } 38 | if y > 0 && grid[y-1][x] == '1' { 39 | island(grid, i-w, n) 40 | } 41 | } 42 | 43 | func numIslands(grid [][]byte) int { 44 | w, d, n := 0, 0, 0 45 | if len(grid) > 0 { 46 | w, d = len(grid[0]), len(grid) 47 | } 48 | if w == 0 || d == 0 { 49 | return 0 50 | } 51 | 52 | for i := 0; i < w*d; i++ { 53 | x, y := i%w, i/w 54 | if grid[y][x] == '1' { 55 | n++ 56 | island(grid, i, n) 57 | } 58 | } 59 | 60 | return int(n) 61 | } 62 | -------------------------------------------------------------------------------- /week3-numberofIslands_test.go: -------------------------------------------------------------------------------- 1 | // Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. 2 | // Example 1: 3 | // Input: 4 | // 11110 5 | // 11010 6 | // 11000 7 | // 00000 8 | // Output: 1 9 | // Example 2: 10 | // Input: 11 | // 11000 12 | // 11000 13 | // 00100 14 | // 00011 15 | // Output: 3 16 | 17 | package main 18 | 19 | import "testing" 20 | 21 | func Test_numIslands(t *testing.T) { 22 | type args struct { 23 | grid [][]byte 24 | } 25 | tests := []struct { 26 | name string 27 | args args 28 | want int 29 | }{ 30 | { 31 | name: "case 1", 32 | args: args{ 33 | grid: [][]byte{ 34 | {'1', '1', '0', '0', '0'}, 35 | {'1', '1', '0', '0', '0'}, 36 | {'0', '0', '1', '0', '0'}, 37 | {'0', '0', '0', '1', '1'}, 38 | }, 39 | }, 40 | want: 3, 41 | }, 42 | { 43 | name: "case 2", 44 | args: args{ 45 | grid: [][]byte{ 46 | {'1', '1', '1', '1', '0'}, 47 | {'1', '1', '0', '1', '0'}, 48 | {'1', '1', '0', '0', '0'}, 49 | {'0', '0', '0', '0', '0'}, 50 | }, 51 | }, 52 | want: 1, 53 | }, 54 | { 55 | name: "case 3", 56 | args: args{ 57 | grid: [][]byte{}, 58 | }, 59 | want: 0, 60 | }, 61 | { 62 | name: "case 4", 63 | args: args{ 64 | grid: [][]byte{ 65 | {'1', '1', '1'}, 66 | {'0', '1', '0'}, 67 | {'1', '1', '1'}, 68 | }, 69 | }, 70 | want: 1, 71 | }, 72 | { 73 | name: "case 5", 74 | args: args{ 75 | grid: [][]byte{ 76 | {'1', '0', '1', '1', '1'}, 77 | {'1', '0', '1', '0', '1'}, 78 | {'1', '1', '1', '0', '1'}, 79 | }, 80 | }, 81 | want: 1, 82 | }, 83 | } 84 | for _, tt := range tests { 85 | t.Run(tt.name, func(t *testing.T) { 86 | if got := numIslands(tt.args.grid); got != tt.want { 87 | t.Errorf("%v numIslands() = %v, want %v", tt.name, got, tt.want) 88 | } 89 | }) 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /week3-productofArrayExceptSelf.go: -------------------------------------------------------------------------------- 1 | // Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. 2 | // Example: 3 | // Input: [1,2,3,4] 4 | // Output: [24,12,8,6] 5 | // Constraint: It's guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer. 6 | // Note: Please solve it without division and in O(n). 7 | // Follow up: 8 | // Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.) 9 | 10 | package main 11 | 12 | func productExceptSelf(nums []int) []int { 13 | var ( 14 | result []int = make([]int, len(nums)) 15 | ) 16 | 17 | result[0] = 1 18 | for i := 1; i < len(nums); i++ { 19 | result[i] = nums[i-1] * result[i-1] 20 | 21 | } 22 | R := 1 23 | for i := len(nums) - 1; i >= 0; i-- { 24 | result[i] = result[i] * R 25 | R *= nums[i] 26 | 27 | } 28 | 29 | return result 30 | } 31 | 32 | // wrong 33 | func _productExceptSelf(nums []int) []int { 34 | var ( 35 | result []int = make([]int, len(nums)) 36 | i, product int = 0, 1 37 | ) 38 | 39 | for i = 0; i < len(nums)/2; i++ { 40 | if nums[i] != 0 { 41 | product = product * nums[i] 42 | } 43 | if nums[len(nums)-i-1] != 0 { 44 | product = product * nums[len(nums)-i-1] 45 | } 46 | } 47 | if i*2 != len(nums) { 48 | product = product * nums[i] 49 | } 50 | 51 | if product != 0 { 52 | for i = 0; i < len(nums)/2; i++ { 53 | if nums[i] != 0 { 54 | result[i] = product / nums[i] 55 | } 56 | if nums[len(nums)-i-1] != 0 { 57 | result[len(nums)-i-1] = product / nums[len(nums)-i-1] 58 | } 59 | } 60 | if i*2 != len(nums) { 61 | if nums[i] != 0 { 62 | result[i] = product / nums[i] 63 | } 64 | } 65 | } 66 | 67 | return result 68 | } 69 | -------------------------------------------------------------------------------- /week3-productofArrayExceptSelf_test.go: -------------------------------------------------------------------------------- 1 | // Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. 2 | // Example: 3 | // Input: [1,2,3,4] 4 | // Output: [24,12,8,6] 5 | // Constraint: It's guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer. 6 | // Note: Please solve it without division and in O(n). 7 | // Follow up: 8 | // Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.) 9 | 10 | package main 11 | 12 | import ( 13 | "reflect" 14 | "testing" 15 | ) 16 | 17 | func Test_productExceptSelf(t *testing.T) { 18 | type args struct { 19 | nums []int 20 | } 21 | tests := []struct { 22 | name string 23 | args args 24 | want []int 25 | }{ 26 | { 27 | name: "case 1", 28 | args: args{ 29 | nums: []int{1, 2, 3, 4}, 30 | }, 31 | want: []int{24, 12, 8, 6}, 32 | }, 33 | { 34 | name: "case 2", 35 | args: args{ 36 | nums: []int{0, 0}, 37 | }, 38 | want: []int{0, 0}, 39 | }, 40 | { 41 | name: "case 3", 42 | args: args{ 43 | nums: []int{1, 0}, 44 | }, 45 | want: []int{0, 1}, 46 | }, 47 | } 48 | for _, tt := range tests { 49 | t.Run(tt.name, func(t *testing.T) { 50 | if got := productExceptSelf(tt.args.nums); !reflect.DeepEqual(got, tt.want) { 51 | t.Errorf("%v productExceptSelf() = %v, want %v", tt.name, got, tt.want) 52 | } 53 | }) 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /week3-searchinRotatedSortedArray.go: -------------------------------------------------------------------------------- 1 | // Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 2 | // (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). 3 | // You are given a target value to search. If found in the array return its index, otherwise return -1. 4 | // You may assume no duplicate exists in the array. 5 | // Your algorithm's runtime complexity must be in the order of O(log n). 6 | // Example 1: 7 | // Input: nums = [4,5,6,7,0,1,2], target = 0 8 | // Output: 4 9 | // Example 2: 10 | // Input: nums = [4,5,6,7,0,1,2], target = 3 11 | // Output: -1 12 | 13 | package main 14 | 15 | func search(nums []int, target int) int { 16 | start, end, mid := 0, len(nums)-1, 0 17 | 18 | for start <= end { 19 | mid = start + (end-start)/2 20 | if target == nums[mid] { 21 | return mid 22 | } else if nums[mid] >= nums[start] { 23 | if target < nums[mid] && target >= nums[start] { 24 | end = mid - 1 25 | } else { 26 | start = mid + 1 27 | } 28 | } else if nums[mid] < nums[start] { 29 | if target > nums[mid] && target < nums[start] { 30 | start = mid + 1 31 | } else { 32 | end = mid - 1 33 | } 34 | } 35 | } 36 | return -1 37 | } 38 | -------------------------------------------------------------------------------- /week3-searchinRotatedSortedArray_test.go: -------------------------------------------------------------------------------- 1 | // Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 2 | // (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). 3 | // You are given a target value to search. If found in the array return its index, otherwise return -1. 4 | // You may assume no duplicate exists in the array. 5 | // Your algorithm's runtime complexity must be in the order of O(log n). 6 | // Example 1: 7 | // Input: nums = [4,5,6,7,0,1,2], target = 0 8 | // Output: 4 9 | // Example 2: 10 | // Input: nums = [4,5,6,7,0,1,2], target = 3 11 | // Output: -1 12 | 13 | package main 14 | 15 | import "testing" 16 | 17 | func Test_search(t *testing.T) { 18 | type args struct { 19 | nums []int 20 | target int 21 | } 22 | tests := []struct { 23 | name string 24 | args args 25 | want int 26 | }{ 27 | { 28 | name: "case 1", 29 | args: args{ 30 | nums: []int{4, 5, 6, 7, 0, 1, 2}, 31 | target: 0, 32 | }, 33 | want: 4, 34 | }, 35 | { 36 | name: "case 2", 37 | args: args{ 38 | nums: []int{4, 5, 6, 7, 0, 1, 2}, 39 | target: 3, 40 | }, 41 | want: -1, 42 | }, 43 | } 44 | for _, tt := range tests { 45 | t.Run(tt.name, func(t *testing.T) { 46 | if got := search(tt.args.nums, tt.args.target); got != tt.want { 47 | t.Errorf("search() = %v, want %v", got, tt.want) 48 | } 49 | }) 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /week3-validParenthesisString.go: -------------------------------------------------------------------------------- 1 | // Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules: 2 | // Any left parenthesis '(' must have a corresponding right parenthesis ')'. 3 | // Any right parenthesis ')' must have a corresponding left parenthesis '('. 4 | // Left parenthesis '(' must go before the corresponding right parenthesis ')'. 5 | // '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string. 6 | // An empty string is also valid. 7 | // Example 1: 8 | // Input: "()" 9 | // Output: True 10 | // Example 2: 11 | // Input: "(*)" 12 | // Output: True 13 | // Example 3: 14 | // Input: "(*))" 15 | // Output: True 16 | // Note: 17 | // The string size will be in the range [1, 100]. 18 | 19 | package main 20 | 21 | import "strings" 22 | 23 | func checkValidString(s string) bool { 24 | var l, h = 0, 0 25 | sc := strings.Split(s, "") 26 | for _, c := range sc { 27 | l += iif(c == "(", 1, -1).(int) 28 | h += iif(c != ")", 1, -1).(int) 29 | if h < 0 { 30 | break 31 | } 32 | l = max(l, 0) 33 | } 34 | 35 | return l == 0 36 | } 37 | -------------------------------------------------------------------------------- /week3-validParenthesisString_test.go: -------------------------------------------------------------------------------- 1 | // Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules: 2 | // Any left parenthesis '(' must have a corresponding right parenthesis ')'. 3 | // Any right parenthesis ')' must have a corresponding left parenthesis '('. 4 | // Left parenthesis '(' must go before the corresponding right parenthesis ')'. 5 | // '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string. 6 | // An empty string is also valid. 7 | // Example 1: 8 | // Input: "()" 9 | // Output: True 10 | // Example 2: 11 | // Input: "(*)" 12 | // Output: True 13 | // Example 3: 14 | // Input: "(*))" 15 | // Output: True 16 | // Note: 17 | // The string size will be in the range [1, 100]. 18 | 19 | package main 20 | 21 | import "testing" 22 | 23 | func Test_checkValidString(t *testing.T) { 24 | type args struct { 25 | s string 26 | } 27 | tests := []struct { 28 | name string 29 | args args 30 | want bool 31 | }{ 32 | { 33 | name: "case 1", 34 | args: args{ 35 | s: "()", 36 | }, 37 | want: true, 38 | }, 39 | { 40 | name: "case 2", 41 | args: args{ 42 | s: "(*)", 43 | }, 44 | want: true, 45 | }, 46 | { 47 | name: "case 3", 48 | args: args{ 49 | s: "(*))", 50 | }, 51 | want: true, 52 | }, 53 | } 54 | for _, tt := range tests { 55 | t.Run(tt.name, func(t *testing.T) { 56 | if got := checkValidString(tt.args.s); got != tt.want { 57 | t.Errorf("%v checkValidString() = %v, want %v", tt.name, got, tt.want) 58 | } 59 | }) 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /week4-LRU_Cache.go: -------------------------------------------------------------------------------- 1 | // Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put. 2 | // get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. 3 | // put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item. 4 | // The cache is initialized with a positive capacity. 5 | // Follow up: 6 | // Could you do both operations in O(1) time complexity? 7 | // Example: 8 | // LRUCache cache = new LRUCache( 2 /* capacity */ ); 9 | // cache.put(1, 1); 10 | // cache.put(2, 2); 11 | // cache.get(1); // returns 1 12 | // cache.put(3, 3); // evicts key 2 13 | // cache.get(2); // returns -1 (not found) 14 | // cache.put(4, 4); // evicts key 1 15 | // cache.get(1); // returns -1 (not found) 16 | // cache.get(3); // returns 3 17 | // cache.get(4); // returns 4 18 | /** 19 | * Your LRUCache object will be instantiated and called as such: 20 | * obj := Constructor(capacity); 21 | * param_1 := obj.Get(key); 22 | * obj.Put(key,value); 23 | */ 24 | // cache := Constructor(2 /* capacity */) 25 | // cache.Put(1, 1) 26 | // cache.Put(2, 2) 27 | // fmt.Println(cache.Get(1)) // returns 1 28 | // cache.Put(3, 3) // evicts key 2 29 | // fmt.Println(cache.Get(2)) // returns -1 (not found) 30 | // cache.Put(4, 4) // evicts key 1 31 | // fmt.Println(cache.Get(1)) // returns -1 (not found) 32 | // fmt.Println(cache.Get(3)) // returns 3 33 | // fmt.Println(cache.Get(4)) // returns 4 34 | 35 | package main 36 | 37 | type dataNode struct { 38 | k, v int 39 | preNode, nextNode *dataNode 40 | } 41 | 42 | type LRUCache struct { 43 | capacity int 44 | cache map[int]*dataNode 45 | first *dataNode 46 | last *dataNode 47 | } 48 | 49 | func Constructor(capacity int) LRUCache { 50 | return LRUCache{ 51 | capacity: capacity, 52 | cache: make(map[int]*dataNode), 53 | } 54 | } 55 | 56 | func (this *LRUCache) Get(k int) int { 57 | if node, ok := this.cache[k]; ok { 58 | this.moveToFirst(node) 59 | return node.v 60 | } 61 | return -1 62 | } 63 | 64 | func (this *LRUCache) Put(k int, v int) { 65 | var ( 66 | node *dataNode 67 | ok bool 68 | ) 69 | if node, ok = this.cache[k]; !ok { 70 | if len(this.cache) >= this.capacity { 71 | this.removeLast() 72 | } 73 | node = &dataNode{} 74 | } 75 | node.k = k 76 | node.v = v 77 | 78 | this.moveToFirst(node) 79 | this.cache[k] = node 80 | } 81 | 82 | func (this *LRUCache) removeLast() { 83 | if this.last != nil { 84 | last := this.last 85 | if last.preNode != nil { 86 | this.last.preNode.nextNode = nil 87 | this.last = this.last.preNode 88 | } else { 89 | this.first = nil 90 | this.last = nil 91 | } 92 | delete(this.cache, last.k) 93 | } 94 | } 95 | 96 | func (this *LRUCache) moveToFirst(node *dataNode) { 97 | if node == this.first { 98 | return 99 | } 100 | if node.preNode != nil { 101 | node.preNode.nextNode = node.nextNode 102 | } 103 | if node.nextNode != nil { 104 | node.nextNode.preNode = node.preNode 105 | } 106 | if this.last == node { 107 | this.last = node.preNode 108 | } 109 | if this.first != nil { 110 | node.nextNode = this.first 111 | this.first.preNode = node 112 | } 113 | this.first = node 114 | node.preNode = nil 115 | if this.last == nil { 116 | this.last = this.first 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /week4-bitwiseANDofNumbersRange.go: -------------------------------------------------------------------------------- 1 | // Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. 2 | // Example 1: 3 | // Input: [5,7] 4 | // Output: 4 5 | // Example 2: 6 | // Input: [0,1] 7 | // Output: 0 8 | 9 | // 0000 0 10 | // 0001 1 11 | // 0010 2 12 | // 0011 3 13 | // 0100 4 14 | // 0101 5 15 | // 0110 6 16 | // 0111 7 17 | // 1000 8 18 | // 1001 9 19 | // 1010 10 20 | // 1011 11 21 | // 1100 12 22 | // 1101 13 23 | // 1110 14 24 | // 1111 15 25 | // 10000 16 26 | // 10001 17 27 | // 10010 18 28 | // 10011 19 29 | // 10100 20 30 | // 10101 21 31 | // 10110 22 32 | // 10111 33 | // 11000 34 | // 11001 35 | // 11010 36 | // 11011 37 | // 11100 38 | // 11101 39 | // 11110 40 | // 11111 41 | 42 | package main 43 | 44 | import ( 45 | "math" 46 | ) 47 | 48 | // the best solution 49 | func rangeBitwiseAnd(m int, n int) int { 50 | for n > m { 51 | n = n & (n - 1) 52 | } 53 | return n & m 54 | } 55 | 56 | // my solution 57 | func my_rangeBitwiseAnd(m int, n int) int { 58 | var sumBitwise int 59 | 60 | if n <= m+1 { 61 | return m & n 62 | } 63 | for bit := 15; bit > int(math.Log2(float64(n-m))); bit-- { 64 | bitCompare := int(math.Pow(2, float64(bit))) 65 | if m&bitCompare > 0 && n&bitCompare > 0 { 66 | sumBitwise += bitCompare 67 | } 68 | } 69 | return sumBitwise 70 | } 71 | 72 | // Brute force 73 | func _rangeBitwiseAnd(m int, n int) int { 74 | var bitwiseAnd int = m 75 | 76 | for i := m + 1; i <= n; i++ { 77 | bitwiseAnd &= i 78 | } 79 | 80 | return bitwiseAnd 81 | } 82 | 83 | // case 8 not pass 84 | func ___rangeBitwiseAnd(m int, n int) int { 85 | var bit int 86 | if m == n { 87 | return m 88 | } 89 | if n == m+1 { 90 | return n & m 91 | } 92 | for ; bit < 16; bit++ { 93 | if m>>1 == 0 { 94 | break 95 | } 96 | m >>= 1 97 | n >>= 1 98 | } 99 | if m != n { 100 | return 0 101 | } 102 | return int(math.Pow(float64((m&n)*2), float64(bit))) 103 | } 104 | -------------------------------------------------------------------------------- /week4-bitwiseANDofNumbersRange_test.go: -------------------------------------------------------------------------------- 1 | // Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. 2 | // Example 1: 3 | // Input: [5,7] 4 | // Output: 4 5 | // Example 2: 6 | // Input: [0,1] 7 | // Output: 0 8 | 9 | package main 10 | 11 | import "testing" 12 | 13 | func Test_rangeBitwiseAnd(t *testing.T) { 14 | type args struct { 15 | m int 16 | n int 17 | } 18 | tests := []struct { 19 | name string 20 | args args 21 | want int 22 | }{ 23 | { 24 | name: "case 1", 25 | args: args{ 26 | m: 5, 27 | n: 7, 28 | }, 29 | want: 4, 30 | }, 31 | { 32 | name: "case 2", 33 | args: args{ 34 | m: 0, 35 | n: 1, 36 | }, 37 | want: 0, 38 | }, 39 | { 40 | name: "case 3", 41 | args: args{ 42 | m: 1, 43 | n: 2, 44 | }, 45 | want: 0, 46 | }, 47 | { 48 | name: "case 4", 49 | args: args{ 50 | m: 1, 51 | n: 1, 52 | }, 53 | want: 1, 54 | }, 55 | { 56 | name: "case 5", 57 | args: args{ 58 | m: 0, 59 | n: 0, 60 | }, 61 | want: 0, 62 | }, 63 | { 64 | name: "case 6", 65 | args: args{ 66 | m: 3, 67 | n: 3, 68 | }, 69 | want: 3, 70 | }, 71 | { 72 | name: "case 7", 73 | args: args{ 74 | m: 6, 75 | n: 7, 76 | }, 77 | want: 6, 78 | }, 79 | { 80 | name: "case 8", 81 | args: args{ 82 | m: 12, 83 | n: 14, 84 | }, 85 | want: 12, 86 | }, 87 | { 88 | name: "case 9", 89 | args: args{ 90 | m: 12, 91 | n: 140, 92 | }, 93 | want: 0, 94 | }, 95 | { 96 | name: "case 10", 97 | args: args{ 98 | m: 10, 99 | n: 11, 100 | }, 101 | want: 10, 102 | }, 103 | { 104 | name: "case 11", 105 | args: args{ 106 | m: 20, 107 | n: 22, 108 | }, 109 | want: 20, 110 | }, 111 | { 112 | name: "case 12", 113 | args: args{ 114 | m: 32, 115 | n: 57, 116 | }, 117 | want: 32, 118 | }, 119 | { 120 | name: "case 13", 121 | args: args{ 122 | m: 64, 123 | n: 113, 124 | }, 125 | want: 64, 126 | }, 127 | } 128 | for _, tt := range tests { 129 | t.Run(tt.name, func(t *testing.T) { 130 | if got := rangeBitwiseAnd(tt.args.m, tt.args.n); got != tt.want { 131 | t.Errorf("%v rangeBitwiseAnd(%v, %v) = %v, want %v", tt.name, tt.args.m, tt.args.n, got, tt.want) 132 | } 133 | }) 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /week4-firstUniqueNumber.go: -------------------------------------------------------------------------------- 1 | // You have a queue of integers, you need to retrieve the first unique integer in the queue. 2 | // Implement the FirstUnique class: 3 | // FirstUnique(int[] nums) Initializes the object with the numbers in the queue. 4 | // int showFirstUnique() returns the value of the first unique integer of the queue, and returns -1 if there is no such integer. 5 | // void add(int value) insert value to the queue. 6 | // Example 1: 7 | // Input: 8 | // ["FirstUnique","showFirstUnique","add","showFirstUnique","add","showFirstUnique","add","showFirstUnique"] 9 | // [[[2,3,5]],[],[5],[],[2],[],[3],[]] 10 | // Output: 11 | // [null,2,null,2,null,3,null,-1] 12 | // Explanation: 13 | // FirstUnique firstUnique = new FirstUnique([2,3,5]); 14 | // firstUnique.showFirstUnique(); // return 2 15 | // firstUnique.add(5); // the queue is now [2,3,5,5] 16 | // firstUnique.showFirstUnique(); // return 2 17 | // firstUnique.add(2); // the queue is now [2,3,5,5,2] 18 | // firstUnique.showFirstUnique(); // return 3 19 | // firstUnique.add(3); // the queue is now [2,3,5,5,2,3] 20 | // firstUnique.showFirstUnique(); // return -1 21 | // Example 2: 22 | // Input: 23 | // ["FirstUnique","showFirstUnique","add","add","add","add","add","showFirstUnique"] 24 | // [[[7,7,7,7,7,7]],[],[7],[3],[3],[7],[17],[]] 25 | // Output: 26 | // [null,-1,null,null,null,null,null,17] 27 | // Explanation: 28 | // FirstUnique firstUnique = new FirstUnique([7,7,7,7,7,7]); 29 | // firstUnique.showFirstUnique(); // return -1 30 | // firstUnique.add(7); // the queue is now [7,7,7,7,7,7,7] 31 | // firstUnique.add(3); // the queue is now [7,7,7,7,7,7,7,3] 32 | // firstUnique.add(3); // the queue is now [7,7,7,7,7,7,7,3,3] 33 | // firstUnique.add(7); // the queue is now [7,7,7,7,7,7,7,3,3,7] 34 | // firstUnique.add(17); // the queue is now [7,7,7,7,7,7,7,3,3,7,17] 35 | // firstUnique.showFirstUnique(); // return 17 36 | // Example 3: 37 | // Input: 38 | // ["FirstUnique","showFirstUnique","add","showFirstUnique"] 39 | // [[[809]],[],[809],[]] 40 | // Output: 41 | // [null,809,null,-1] 42 | // Explanation: 43 | // FirstUnique firstUnique = new FirstUnique([809]); 44 | // firstUnique.showFirstUnique(); // return 809 45 | // firstUnique.add(809); // the queue is now [809,809] 46 | // firstUnique.showFirstUnique(); // return -1 47 | // Constraints: 48 | // 1 <= nums.length <= 10^5 49 | // 1 <= nums[i] <= 10^8 50 | // 1 <= value <= 10^8 51 | // At most 50000 calls will be made to showFirstUnique and add. 52 | // Hide Hint #1 53 | // Use doubly Linked list with hashmap of pointers to linked list nodes. add unique number to the linked list. When add is called check if the added number is unique then it have to be added to the linked list and if it is repeated remove it from the linked list if exists. When showFirstUnique is called retrieve the head of the linked list. 54 | // Hide Hint #2 55 | // Use queue and check that first element of the queue is always unique. 56 | // Hide Hint #3 57 | // Use set or heap to make running time of each function O(logn). 58 | 59 | package main 60 | 61 | import "fmt" 62 | 63 | type linked struct { 64 | prv *linked 65 | next *linked 66 | num int 67 | } 68 | 69 | type FirstUnique struct { 70 | head *linked 71 | last *linked 72 | m map[int]*linked 73 | } 74 | 75 | func FirstUnique_Constructor(nums []int) FirstUnique { 76 | firstUnique := FirstUnique{ 77 | head: nil, 78 | last: nil, 79 | m: make(map[int]*linked), 80 | } 81 | 82 | for _, v := range nums { 83 | firstUnique.Add(v) 84 | } 85 | 86 | return firstUnique 87 | } 88 | 89 | func (this *FirstUnique) ShowFirstUnique() int { 90 | num := -1 91 | if this.head != nil { 92 | num = this.head.num 93 | } 94 | 95 | return num 96 | } 97 | 98 | func (this *FirstUnique) Add(value int) { 99 | if this.head == nil { 100 | if l, ok := this.m[value]; ok { 101 | if l != nil { 102 | this.remove(l) 103 | this.m[value] = nil 104 | } 105 | } else { 106 | this.head = &linked{ 107 | prv: nil, 108 | next: nil, 109 | num: value, 110 | } 111 | this.last = this.head 112 | this.m[value] = this.head 113 | } 114 | } else { 115 | if l, ok := this.m[value]; ok { 116 | if l != nil { 117 | this.remove(l) 118 | this.m[value] = nil 119 | } 120 | } else { 121 | this.last.next = &linked{ 122 | prv: this.last, 123 | next: nil, 124 | num: value, 125 | } 126 | this.last = this.last.next 127 | this.m[value] = this.last 128 | } 129 | 130 | } 131 | } 132 | 133 | func (this *FirstUnique) remove(l *linked) { 134 | if this.head == l && this.last == l { 135 | this.head, this.last, l = nil, nil, nil 136 | } else { 137 | if l.prv != nil { 138 | l.prv.next = l.next 139 | } else { 140 | l.next.prv = nil 141 | this.head = l.next 142 | } 143 | 144 | if l.next != nil { 145 | l.next.prv = l.prv 146 | } else { 147 | l.prv.next = nil 148 | this.last = l.prv 149 | } 150 | l = nil 151 | } 152 | } 153 | 154 | func (this *FirstUnique) prt() { 155 | fmt.Print("linked: ") 156 | if this.head != nil { 157 | l := this.head 158 | for l != nil { 159 | fmt.Print(l.num, " > ") 160 | l = l.next 161 | } 162 | } 163 | fmt.Print("\n") 164 | } 165 | 166 | /** 167 | * Your FirstUnique object will be instantiated and called as such: 168 | * obj := Constructor(nums); 169 | * param_1 := obj.ShowFirstUnique(); 170 | * obj.Add(value); 171 | */ 172 | -------------------------------------------------------------------------------- /week4-jumpGame.go: -------------------------------------------------------------------------------- 1 | // Given an array of non-negative integers, you are initially positioned at the first index of the array. 2 | // Each element in the array represents your maximum jump length at that position. 3 | // Determine if you are able to reach the last index. 4 | // Example 1: 5 | // Input: [2,3,1,1,4] 6 | // Output: true 7 | // Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. 8 | // Example 2: 9 | // Input: [3,2,1,0,4] 10 | // Output: false 11 | // Explanation: You will always arrive at index 3 no matter what. Its maximum 12 | // jump length is 0, which makes it impossible to reach the last index. 13 | 14 | package main 15 | 16 | func jump(nums []int, i int) bool { 17 | if i >= len(nums)-1 { 18 | return true 19 | } 20 | if nums[i] == 0 { 21 | return false 22 | } 23 | 24 | for k := i + 1; k <= i+nums[i]; k++ { 25 | if jump(nums, k) { 26 | return true 27 | } 28 | } 29 | nums[i] = 0 30 | return false 31 | } 32 | 33 | func canJump(nums []int) bool { 34 | return jump(nums, 0) 35 | } 36 | -------------------------------------------------------------------------------- /week4-longestCommonSubsequence.go: -------------------------------------------------------------------------------- 1 | // Given two strings text1 and text2, return the length of their longest common subsequence. 2 | // A subsequence of a string is a new string generated from the original string with some characters(can be none) deleted without changing the relative order of the remaining characters. (eg, "ace" is a subsequence of "abcde" while "aec" is not). A common subsequence of two strings is a subsequence that is common to both strings. 3 | // If there is no common subsequence, return 0. 4 | // Example 1: 5 | // Input: text1 = "abcde", text2 = "ace" 6 | // Output: 3 7 | // Explanation: The longest common subsequence is "ace" and its length is 3. 8 | // Example 2: 9 | // Input: text1 = "abc", text2 = "abc" 10 | // Output: 3 11 | // Explanation: The longest common subsequence is "abc" and its length is 3. 12 | // Example 3: 13 | // Input: text1 = "abc", text2 = "def" 14 | // Output: 0 15 | // Explanation: There is no such common subsequence, so the result is 0. 16 | // Constraints: 17 | // 1 <= text1.length <= 1000 18 | // 1 <= text2.length <= 1000 19 | // The input strings consist of lowercase English characters only. 20 | // Hide Hint #1 21 | // Try dynamic programming. DP[i][j] represents the longest common subsequence of text1[0 ... i] & text2[0 ... j]. 22 | // Hide Hint #2 23 | // DP[i][j] = DP[i - 1][j - 1] + 1 , if text1[i] == text2[j] DP[i][j] = max(DP[i - 1][j], DP[i][j - 1]) , otherwise 24 | 25 | package main 26 | 27 | import ( 28 | "strings" 29 | ) 30 | 31 | func longestCommonSubsequence(text1 string, text2 string) int { 32 | var dp [][]int 33 | st1, st2 := strings.Split(text1, ""), strings.Split(text2, "") 34 | w, d := len(st1), len(st2) 35 | if w == 0 || d == 0 { 36 | return 0 37 | } 38 | 39 | for i := 0; i <= w; i++ { 40 | dp = append(dp, make([]int, d+1)) 41 | } 42 | 43 | for i := w; i >= 0; i-- { 44 | for j := d; j >= 0; j-- { 45 | if i == w || j == d { 46 | dp[i][j] = 0 47 | } else if st1[i] == st2[j] { 48 | dp[i][j] = dp[i+1][j+1] + 1 49 | } else { 50 | dp[i][j] = max(dp[i+1][j], dp[i][j+1]) 51 | } 52 | } 53 | } 54 | 55 | return dp[0][0] 56 | } 57 | -------------------------------------------------------------------------------- /week4-longestCommonSubsequence_test.go: -------------------------------------------------------------------------------- 1 | // Given two strings text1 and text2, return the length of their longest common subsequence. 2 | // A subsequence of a string is a new string generated from the original string with some characters(can be none) deleted without changing the relative order of the remaining characters. (eg, "ace" is a subsequence of "abcde" while "aec" is not). A common subsequence of two strings is a subsequence that is common to both strings. 3 | // If there is no common subsequence, return 0. 4 | // Example 1: 5 | // Input: text1 = "abcde", text2 = "ace" 6 | // Output: 3 7 | // Explanation: The longest common subsequence is "ace" and its length is 3. 8 | // Example 2: 9 | // Input: text1 = "abc", text2 = "abc" 10 | // Output: 3 11 | // Explanation: The longest common subsequence is "abc" and its length is 3. 12 | // Example 3: 13 | // Input: text1 = "abc", text2 = "def" 14 | // Output: 0 15 | // Explanation: There is no such common subsequence, so the result is 0. 16 | // Constraints: 17 | // 1 <= text1.length <= 1000 18 | // 1 <= text2.length <= 1000 19 | // The input strings consist of lowercase English characters only. 20 | // Hide Hint #1 21 | // Try dynamic programming. DP[i][j] represents the longest common subsequence of text1[0 ... i] & text2[0 ... j]. 22 | // Hide Hint #2 23 | // DP[i][j] = DP[i - 1][j - 1] + 1 , if text1[i] == text2[j] DP[i][j] = max(DP[i - 1][j], DP[i][j - 1]) , otherwise 24 | 25 | package main 26 | 27 | import "testing" 28 | 29 | func Test_longestCommonSubsequence(t *testing.T) { 30 | type args struct { 31 | text1 string 32 | text2 string 33 | } 34 | tests := []struct { 35 | name string 36 | args args 37 | want int 38 | }{ 39 | { 40 | name: "case 1", 41 | args: args{ 42 | text1: "abcde", 43 | text2: "abc", 44 | }, 45 | want: 3, 46 | }, 47 | { 48 | name: "case 2", 49 | args: args{ 50 | text1: "abc", 51 | text2: "abc", 52 | }, 53 | want: 3, 54 | }, 55 | { 56 | name: "case 3", 57 | args: args{ 58 | text1: "abc", 59 | text2: "def", 60 | }, 61 | want: 0, 62 | }, 63 | { 64 | name: "case 4", 65 | args: args{ 66 | text1: "abcde", 67 | text2: "ace", 68 | }, 69 | want: 3, 70 | }, 71 | } 72 | for _, tt := range tests { 73 | t.Run(tt.name, func(t *testing.T) { 74 | if got := longestCommonSubsequence(tt.args.text1, tt.args.text2); got != tt.want { 75 | t.Errorf("%v longestCommonSubsequence() = %v, want %v", tt.name, got, tt.want) 76 | } 77 | }) 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /week4-maximalSquare.go: -------------------------------------------------------------------------------- 1 | // Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. 2 | // Example: 3 | // Input: 4 | // 1 0 1 0 0 5 | // 1 0 1 1 1 6 | // 1 1 1 1 1 7 | // 1 0 0 1 0 8 | // Output: 4 9 | 10 | package main 11 | 12 | var sw int 13 | 14 | func findSquare(matrix [][]byte, from, to int) { 15 | w, d := len(matrix[0]), len(matrix) 16 | fx, fy := from%w, from/w 17 | x, y := to%w, to/w 18 | 19 | for i := x; i >= fx; i-- { 20 | if matrix[y][i] != '1' { 21 | return 22 | } 23 | } 24 | for i := y; i >= fy; i-- { 25 | if matrix[i][x] != '1' { 26 | return 27 | } 28 | } 29 | if x-fx >= sw { 30 | sw = x - fx + 1 31 | } 32 | 33 | if x+1 < w && y+1 < d && matrix[y+1][x+1] == '1' { 34 | findSquare(matrix, from, to+w+1) 35 | } 36 | 37 | } 38 | 39 | func maximalSquare(matrix [][]byte) int { 40 | w, d := 0, 0 41 | sw = 0 42 | if len(matrix) > 0 { 43 | w, d = len(matrix[0]), len(matrix) 44 | } 45 | if w == 0 || d == 0 { 46 | return 0 47 | } 48 | 49 | for i := 0; i < w*d; i++ { 50 | x, y := i%w, i/w 51 | if matrix[y][x] == '1' && sw == 0 { 52 | sw = 1 53 | } 54 | if x+1 < w && y+1 < d && matrix[y][x] == '1' && matrix[y+1][x+1] == '1' { 55 | findSquare(matrix, i, i+w+1) 56 | } 57 | } 58 | 59 | return sw * sw 60 | } 61 | -------------------------------------------------------------------------------- /week4-maximalSquare_test.go: -------------------------------------------------------------------------------- 1 | // Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. 2 | // Example: 3 | // Input: 4 | // 1 0 1 0 0 5 | // 1 0 1 1 1 6 | // 1 1 1 1 1 7 | // 1 0 0 1 0 8 | // Output: 4 9 | 10 | package main 11 | 12 | import "testing" 13 | 14 | func Test_maximalSquare(t *testing.T) { 15 | type args struct { 16 | matrix [][]byte 17 | } 18 | tests := []struct { 19 | name string 20 | args args 21 | want int 22 | }{ 23 | { 24 | name: "case 1", 25 | args: args{ 26 | matrix: [][]byte{ 27 | {'1', '0', '1', '0', '0'}, 28 | {'1', '0', '1', '1', '1'}, 29 | {'1', '1', '1', '1', '1'}, 30 | {'1', '0', '0', '1', '0'}, 31 | }, 32 | }, 33 | want: 4, 34 | }, 35 | { 36 | name: "case 1", 37 | args: args{ 38 | matrix: [][]byte{ 39 | {'0'}, 40 | }, 41 | }, 42 | want: 0, 43 | }, 44 | { 45 | name: "case 2", 46 | args: args{ 47 | matrix: [][]byte{ 48 | {'1'}, 49 | }, 50 | }, 51 | want: 1, 52 | }, 53 | } 54 | for _, tt := range tests { 55 | t.Run(tt.name, func(t *testing.T) { 56 | if got := maximalSquare(tt.args.matrix); got != tt.want { 57 | t.Errorf("%v maximalSquare() = %v, want %v", tt.name, got, tt.want) 58 | } 59 | }) 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /week4-subarraySumEqualsK.go: -------------------------------------------------------------------------------- 1 | // Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. 2 | // Example 1: 3 | // Input:nums = [1,1,1], k = 2 4 | // Output: 2 5 | // Note: 6 | // The length of the array is in range [1, 20,000]. 7 | // The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7]. 8 | // Hide Hint #1 9 | // Will Brute force work here? Try to optimize it. 10 | // Hide Hint #2 11 | // Can we optimize it by using some extra space? 12 | // Hide Hint #3 13 | // What about storing sum frequencies in a hash table? Will it be useful? 14 | // Hide Hint #4 15 | // sum(i,j)=sum(0,j)-sum(0,i), where sum(i,j) represents the sum of all the elements from index i to j-1. Can we use this property to optimize it. 16 | // https://leetcode.com/problems/subarray-sum-equals-k/solution/ 17 | 18 | package main 19 | 20 | func subarraySum(nums []int, k int) int { 21 | var ( 22 | sumMap map[int]int = make(map[int]int) 23 | cnt, sum int 24 | ) 25 | sumMap[0] = 1 26 | for i := 0; i < len(nums); i++ { 27 | sum += nums[i] 28 | if v, ok := sumMap[sum-k]; ok { 29 | cnt += v 30 | } 31 | if _, ok := sumMap[sum]; ok { 32 | sumMap[sum]++ 33 | } else { 34 | sumMap[sum] = 1 35 | } 36 | } 37 | return cnt 38 | } 39 | 40 | //Time Limit Exceeded 41 | func _subarraySum(nums []int, k int) int { 42 | var ( 43 | sumMap map[int]int = make(map[int]int) 44 | cnt int 45 | ) 46 | sumMap[-1] = 0 47 | for i := 0; i < len(nums); i++ { 48 | sumMap[i] = sumMap[i-1] + nums[i] 49 | if sumMap[i] == k { 50 | cnt++ 51 | } 52 | for j := 0; j < i; j++ { 53 | if sumMap[i]-sumMap[j] == k { 54 | cnt++ 55 | } 56 | } 57 | } 58 | return cnt 59 | } 60 | -------------------------------------------------------------------------------- /week5-binaryTreeMaximumPathSum.go: -------------------------------------------------------------------------------- 1 | // Given a non-empty binary tree, find the maximum path sum. 2 | // For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root. 3 | // Example 1: 4 | // Input: [1,2,3] 5 | // 1 6 | // / \ 7 | // 2 3 8 | // Output: 6 9 | // Example 2: 10 | // Input: [-10,9,20,null,null,15,7] 11 | // -10 12 | // / \ 13 | // 9 20 14 | // / \ 15 | // 15 7 16 | // Output: 42 17 | 18 | package main 19 | 20 | // defin in week2-diameterofBinaryTree.go 21 | /** 22 | * Definition for a binary tree node. 23 | * type TreeNode struct { 24 | * Val int 25 | * Left *TreeNode 26 | * Right *TreeNode 27 | * } 28 | */ 29 | 30 | var maxValue int 31 | 32 | func retriveMax(node *TreeNode) int { 33 | if node == nil { 34 | return 0 35 | } 36 | leftMax := max(retriveMax(node.Left), 0) 37 | rightMax := max(retriveMax(node.Right), 0) 38 | maxValue = max(maxValue, node.Val+leftMax+rightMax) 39 | 40 | return node.Val + max(leftMax, rightMax) 41 | } 42 | 43 | func maxPathSum(root *TreeNode) int { 44 | // maxValue = -(int(^uint(0) >> 1)) - 1 45 | maxValue = root.Val 46 | retriveMax(root) 47 | 48 | return maxValue 49 | } 50 | -------------------------------------------------------------------------------- /week5-checkIfaStringIsaValidSequencefromRoottoLeavesPathinaBinaryTree.go: -------------------------------------------------------------------------------- 1 | // Given a binary tree where each path going from the root to any leaf form a valid sequence, check if a given string is a valid sequence in such binary tree. 2 | // We get the given string from the concatenation of an array of integers arr and the concatenation of all values of the nodes along a path results in a sequence in the given binary tree. 3 | // Example 1: 4 | // https://assets.leetcode.com/uploads/2019/12/18/leetcode_testcase_1.png 5 | // Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,1,0,1] 6 | // Output: true 7 | // Explanation: 8 | // The path 0 -> 1 -> 0 -> 1 is a valid sequence (green color in the figure). 9 | // Other valid sequences are: 10 | // 0 -> 1 -> 1 -> 0 11 | // 0 -> 0 -> 0 12 | // Example 2: 13 | // https://assets.leetcode.com/uploads/2019/12/18/leetcode_testcase_2.png 14 | // Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,0,1] 15 | // Output: false 16 | // Explanation: The path 0 -> 0 -> 1 does not exist, therefore it is not even a sequence. 17 | // Example 3: 18 | // https://assets.leetcode.com/uploads/2019/12/18/leetcode_testcase_3.png 19 | // Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,1,1] 20 | // Output: false 21 | // Explanation: The path 0 -> 1 -> 1 is a sequence, but it is not a valid sequence. 22 | // Constraints: 23 | // 1 <= arr.length <= 5000 24 | // 0 <= arr[i] <= 9 25 | // Each node's value is between [0 - 9]. 26 | // Hide Hint #1 27 | // Depth-first search (DFS) with the parameters: current node in the binary tree and current position in the array of integers. 28 | // Hide Hint #2 29 | // When reaching at final position check if it is a leaf node. 30 | 31 | package main 32 | 33 | /** 34 | * Definition for a binary tree node. 35 | * type TreeNode struct { 36 | * Val int 37 | * Left *TreeNode 38 | * Right *TreeNode 39 | * } 40 | */ 41 | 42 | var valid bool 43 | 44 | func dfsVerify(node *TreeNode, arr []int, i int) { 45 | if arr[len(arr)-i] == node.Val { 46 | if i == 1 && node.Left == nil && node.Right == nil { 47 | valid = true 48 | return 49 | } 50 | i-- 51 | if i > 0 { 52 | if node.Left != nil { 53 | dfsVerify(node.Left, arr, i) 54 | } 55 | if node.Right != nil { 56 | dfsVerify(node.Right, arr, i) 57 | } 58 | } 59 | } 60 | } 61 | 62 | func isValidSequence(root *TreeNode, arr []int) bool { 63 | valid = false 64 | dfsVerify(root, arr, len(arr)) 65 | return valid 66 | } 67 | --------------------------------------------------------------------------------