diff --git a/Easy.md b/Easy.md new file mode 100644 index 0000000..540a506 --- /dev/null +++ b/Easy.md @@ -0,0 +1,179 @@ +## Easy +|LC #|Description| +|:-:|:-| +|[1480](https://leetcode.com/problems/running-sum-of-1d-array/)| Running Sum of 1d Array| +|[1431](https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/)| Kids With the Greatest Number of Candies| +|[1](https://leetcode.com/problems/two-sum/)| Two Sum| +|[575](https://leetcode.com/problems/distribute-candies/)| Distribute Candies| +|[1365](https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/)| How Many Numbers Are Smaller Than the Current Number| +|[1773](https://leetcode.com/problems/count-items-matching-a-rule/)| Count Items Matching a Rule| +|[645](https://leetcode.com/problems/set-mismatch/)| Set Mismatch| +|[268](https://leetcode.com/problems/missing-number/)| Missing Number| +|[160](https://leetcode.com/problems/intersection-of-two-linked-lists/)| Intersection of Two Linked Lists| +|[637](https://leetcode.com/problems/average-of-levels-in-binary-tree/)| Average of Levels in Binary Tree| +|[559](https://leetcode.com/problems/maximum-depth-of-n-ary-tree/)| Maximum Depth of N-ary Tree| +|[690](https://leetcode.com/problems/employee-importance/)| Employee Importance| +|[993](https://leetcode.com/problems/cousins-in-binary-tree/)| Cousins in Binary Tree| +|[1748](https://leetcode.com/problems/sum-of-unique-elements/)| Sum of Unique Elements| +|[232](https://leetcode.com/problems/implement-queue-using-stacks/)| Implement Queue using Stacks| +|[1332](https://leetcode.com/problems/remove-palindromic-subsequences/)| Remove Palindromic Subsequences| +|[1678](https://leetcode.com/problems/goal-parser-interpretation/)| Goal Parser Interpretation| +|[1022](https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/)| Sum of Root To Leaf Binary Numbers| +|[404](https://leetcode.com/problems/sum-of-left-leaves/)| Sum of Left Leaves| +|[112](https://leetcode.com/problems/path-sum/)| Path Sum| +|[535](https://leetcode.com/problems/encode-and-decode-tinyurl/)| Encode and Decode TinyURL| +|[1560](https://leetcode.com/problems/most-visited-sector-in-a-circular-track/)| Most Visited Sector in a Circular Track| +|[598](https://leetcode.com/problems/range-addition-ii/)| Range Addition II| +|[762](https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/)| Prime Number of Set Bits in Binary Representation| +|[500](https://leetcode.com/problems/keyboard-row/)| Keyboard Row| +|[1656](https://leetcode.com/problems/design-an-ordered-stream/)| Design an Ordered Stream| +|[234](https://leetcode.com/problems/palindrome-linked-list/)| Palindrome Linked List| +|[1614](https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/)| Maximum Nesting Depth of the Parentheses| +|[1668](https://leetcode.com/problems/maximum-repeating-substring/)| Maximum Repeating Substring| +|[1704](https://leetcode.com/problems/determine-if-string-halves-are-alike/)| Determine if String Halves Are Alike| +|[953](https://leetcode.com/problems/verifying-an-alien-dictionary/)| Verifying an Alien Dictionary| +|[509](https://leetcode.com/problems/fibonacci-number/)| Fibonacci Number| +|[589](https://leetcode.com/problems/n-ary-tree-preorder-traversal/)| N-ary Tree Preorder Traversal| +|[696](https://leetcode.com/problems/count-binary-substrings/)| Count Binary Substrings| +|[326](https://leetcode.com/problems/power-of-three/)| Power of Three| +|[703](https://leetcode.com/problems/kth-largest-element-in-a-stream/)| Kth Largest Element in a Stream| +|[204](https://leetcode.com/problems/count-primes/)| Count Primes| +|[453](https://leetcode.com/problems/minimum-moves-to-equal-array-elements/)| Minimum Moves to Equal Array Elements| +|[709](https://leetcode.com/problems/to-lower-case/)| To Lower Case| +|[1710](https://leetcode.com/problems/maximum-units-on-a-truck/)| Maximum Units on a Truck| +|[1047](https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/)| Remove All Adjacent Duplicates In String| +|[108](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/)| Convert Sorted Array to Binary Search Tree| +|[415](https://leetcode.com/problems/add-strings/)| Add Strings| +|[653](https://leetcode.com/problems/two-sum-iv-input-is-a-bst/)| Two Sum IV - Input is a BST| +|[1629](https://leetcode.com/problems/slowest-key/)| Slowest Key| +|[206](https://leetcode.com/problems/reverse-linked-list/)| Reverse Linked List| +|[1189](https://leetcode.com/problems/maximum-number-of-balloons/)| Maximum Number of Balloons| +|[350](https://leetcode.com/problems/intersection-of-two-arrays-ii/)| Intersection of Two Arrays II| +|[1275](https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/)| Find Winner on a Tic Tac Toe Game| +|[485](https://leetcode.com/problems/max-consecutive-ones/)| Max Consecutive Ones| +|[929](https://leetcode.com/problems/unique-email-addresses/)| Unique Email Addresses| +|[922](https://leetcode.com/problems/sort-array-by-parity-ii/)| Sort Array By Parity II| +|[463](https://leetcode.com/problems/island-perimeter/)| Island Perimeter| +|[70](https://leetcode.com/problems/climbing-stairs/)| Climbing Stairs| +|[543](https://leetcode.com/problems/diameter-of-binary-tree/)| Diameter of Binary Tree| +|[374](https://leetcode.com/problems/guess-number-higher-or-lower/)| Guess Number Higher or Lower| +|[496](https://leetcode.com/problems/next-greater-element-i/)| Next Greater Element I| +|[155](https://leetcode.com/problems/min-stack/)| Min Stack| +|[226](https://leetcode.com/problems/invert-binary-tree/)| Invert Binary Tree| +|[441](https://leetcode.com/problems/arranging-coins/)| Arranging Coins| +|[1413](https://leetcode.com/problems/minimum-value-to-get-positive-step-by-step-sum/)| Minimum Value to Get Positive Step by Step Sum| +|[203](https://leetcode.com/problems/remove-linked-list-elements/)| Remove Linked List Elements| +|[448](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/)| Find All Numbers Disappeared in an Array| +|[461](https://leetcode.com/problems/hamming-distance/)| Hamming Distance| +|[53](https://leetcode.com/problems/maximum-subarray/)| Maximum Subarray| +|[35](https://leetcode.com/problems/search-insert-position/)| Search Insert Position| +|[1217](https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/)| Minimum Cost to Move Chips to The Same Position| +|[563](https://leetcode.com/problems/binary-tree-tilt/)| Binary Tree Tilt| +|[1446](https://leetcode.com/problems/consecutive-characters/)| Consecutive Characters| +|[938](https://leetcode.com/problems/range-sum-of-bst/)| Range Sum of BST| +|[1200](https://leetcode.com/problems/minimum-absolute-difference/)| Minimum Absolute Difference| +|[231](https://leetcode.com/problems/power-of-two/)| Power of Two| +|[476](https://leetcode.com/problems/number-complement/)| Number Complement| +|[876](https://leetcode.com/problems/middle-of-the-linked-list/)| Middle of the Linked List| +|[997](https://leetcode.com/problems/find-the-town-judge/)| Find the Town Judge| +|[1009](https://leetcode.com/problems/complement-of-base-10-integer/)| Complement of Base 10 Integer| +|[67](https://leetcode.com/problems/add-binary/)| Add Binary| +|[290](https://leetcode.com/problems/word-pattern/)| Word Pattern| +|[605](https://leetcode.com/problems/can-place-flowers/)| Can Place Flowers| +|[520](https://leetcode.com/problems/detect-capital/)| Detect Capital| +|[941](https://leetcode.com/problems/valid-mountain-array/)| Valid Mountain Array| +|[389](https://leetcode.com/problems/find-the-difference/)| Find the Difference| +|[258](https://leetcode.com/problems/add-digits/)| Add Digits| +|[1108](https://leetcode.com/problems/defanging-an-ip-address/)| Defanging an IP Address| +|[1832](https://leetcode.com/problems/check-if-the-sentence-is-pangram/)| Check if the Sentence Is Pangram| +|[104](https://leetcode.com/problems/maximum-depth-of-binary-tree/)| Maximum Depth of Binary Tree| +|[136](https://leetcode.com/problems/single-number/)| Single Number| +|[171](https://leetcode.com/problems/excel-sheet-column-number/)| Excel Sheet Column Number| +|[228](https://leetcode.com/problems/summary-ranges/)| Summary Ranges| +|[338](https://leetcode.com/problems/counting-bits/)| Counting Bits| +|[392](https://leetcode.com/problems/is-subsequence/)| Is Subsequence| +|[21](https://leetcode.com/problems/merge-two-sorted-lists/)| Merge Two Sorted Lists| +|[141](https://leetcode.com/problems/linked-list-cycle/)| Linked List Cycle| +|[617](https://leetcode.com/problems/merge-two-binary-trees/)| Merge Two Binary Trees| +|[20](https://leetcode.com/problems/valid-parentheses/)| Valid Parentheses| +|[1351](https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix/)| Count Negative Numbers in a Sorted Matrix| +|[905](https://leetcode.com/problems/sort-array-by-parity/)| Sort Array By Parity| +|[344](https://leetcode.com/problems/reverse-string/)| Reverse String| +|[1460](https://leetcode.com/problems/make-two-arrays-equal-by-reversing-sub-arrays/)| Make Two Arrays Equal by Reversing Sub-arrays| +|[977](https://leetcode.com/problems/squares-of-a-sorted-array/)| Squares of a Sorted Array| +|[349](https://leetcode.com/problems/intersection-of-two-arrays/)| Intersection of Two Arrays| +|[1002](https://leetcode.com/problems/find-common-characters/)| Find Common Characters| +|[766](https://leetcode.com/problems/toeplitz-matrix/)| Toeplitz Matrix| +|[704](https://leetcode.com/problems/binary-search/)| Binary Search| +|[1160](https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/)| Find Words That Can Be Formed by Characters| +|[412](https://leetcode.com/problems/fizz-buzz/)| Fizz Buzz| +|[266](https://leetcode.com/problems/palindrome-permutation/)| Palindrome Permutation| +|[145](https://leetcode.com/problems/binary-tree-postorder-traversal/)| Binary Tree Postorder Traversal| +|[169](https://leetcode.com/problems/majority-element/)| Majority Element| +|[242](https://leetcode.com/problems/valid-anagram/)| Valid Anagram| +|[217](https://leetcode.com/problems/contains-duplicate/)| Contains Duplicate| +|[283](https://leetcode.com/problems/move-zeroes/)| Move Zeroes| +|[1260](https://leetcode.com/problems/shift-2d-grid/)| Shift 2D Grid| +|[700](https://leetcode.com/problems/search-in-a-binary-search-tree/)| Search in a Binary Search Tree| +|[844](https://leetcode.com/problems/backspace-string-compare/)| Backspace String Compare| +|[88](https://leetcode.com/problems/merge-sorted-array/)| Merge Sorted Array| +|[859](https://leetcode.com/problems/buddy-strings/)| Buddy Strings| +|[557](https://leetcode.com/problems/reverse-words-in-a-string-iii/)| Reverse Words in a String III| +|[976](https://leetcode.com/problems/largest-perimeter-triangle/)| Largest Perimeter Triangle| +|[219](https://leetcode.com/problems/contains-duplicate-ii/)| Contains Duplicate II| +|[1544](https://leetcode.com/problems/make-the-string-great/)| Make The String Great| +|[1323](https://leetcode.com/problems/maximum-69-number/)| Maximum 69 Number| +|[2325](https://leetcode.com/problems/decode-the-message/)| Decode the Message| +|[121](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/)| Best Time to Buy and Sell Stock| +|[1971](https://leetcode.com/problems/find-if-path-exists-in-graph/)| Find if Path Exists in Graph| +|[2389](https://leetcode.com/problems/longest-subsequence-with-limited-sum/)| Longest Subsequence With Limited Sum| +|[2073](https://leetcode.com/problems/time-needed-to-buy-tickets/)| Time Needed to Buy Tickets| +|[697](https://leetcode.com/problems/degree-of-an-array/)| Degree of an Array| +|[1071](https://leetcode.com/problems/greatest-common-divisor-of-strings/)| Greatest Common Divisor of Strings| +|[1470](https://leetcode.com/problems/shuffle-the-array/)| Shuffle the Array| +|[1523](https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/)| Count Odd Numbers in an Interval Range| +|[989](https://leetcode.com/problems/add-to-array-form-of-integer/)| Add to Array-Form of Integer| +|[783](https://leetcode.com/problems/minimum-distance-between-bst-nodes/)| Minimum Distance Between BST Nodes| +|[1137](https://leetcode.com/problems/n-th-tribonacci-number/)| N-th Tribonacci Number| +|[746](https://leetcode.com/problems/min-cost-climbing-stairs/)| Min Cost Climbing Stairs| +|[1539](https://leetcode.com/problems/kth-missing-positive-number/)| Kth Missing Positive Number| +|[101](https://leetcode.com/problems/symmetric-tree/)| Symmetric Tree| +|[1768](https://leetcode.com/problems/merge-strings-alternately/)| Merge Strings Alternately| +|[1491](https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary/)| Average Salary Excluding the Minimum and Maximum Salary| +|[1822](https://leetcode.com/problems/sign-of-the-product-of-an-array/)| Sign of the Product of an Array| +|[2215](https://leetcode.com/problems/find-the-difference-of-two-arrays/)| Find the Difference of Two Arrays| +|[1572](https://leetcode.com/problems/matrix-diagonal-sum/)| Matrix Diagonal Sum| +|[1456](https://leetcode.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length/)| Maximum Number of Vowels in a Substring of Given Length| +|[744](https://leetcode.com/problems/find-smallest-letter-greater-than-target/)| Find Smallest Letter Greater Than Target| +|[530](https://leetcode.com/problems/minimum-absolute-difference-in-bst/)| Minimum Absolute Difference in BST| +|[111](https://leetcode.com/problems/minimum-depth-of-binary-tree/)| Minimum Depth of Binary Tree| +|[191](https://leetcode.com/problems/number-of-1-bits/)| Number of 1 Bits| +|[2264](https://leetcode.com/problems/largest-3-same-digit-number-in-string/)| Largest 3-Same-Digit Number in String| +|[1266](https://leetcode.com/problems/minimum-time-visiting-all-points/)| Minimum Time Visiting All Points| +|[1903](https://leetcode.com/problems/largest-odd-number-in-string/)| Largest Odd Number in String| +|[1716](https://leetcode.com/problems/calculate-money-in-leetcode-bank/)| Calculate Money in Leetcode Bank| +|[606](https://leetcode.com/problems/construct-string-from-binary-tree/)| Construct String from Binary Tree| +|[94](https://leetcode.com/problems/binary-tree-inorder-traversal/)| Binary Tree Inorder Traversal| +|[1287](https://leetcode.com/problems/element-appearing-more-than-25-in-sorted-array/)| Element Appearing More Than 25% In Sorted Array| +|[1582](https://leetcode.com/problems/special-positions-in-a-binary-matrix/)| Special Positions in a Binary Matrix| +|[1436](https://leetcode.com/problems/destination-city/)| Destination City| +|[1512](https://leetcode.com/problems/number-of-good-pairs/)| Number of Good Pairs| +|[661](https://leetcode.com/problems/image-smoother/)| Image Smoother| +|[1913](https://leetcode.com/problems/maximum-product-difference-between-two-pairs/)| Maximum Product Difference Between Two Pairs| +|[2706](https://leetcode.com/problems/buy-two-chocolates/)| Buy Two Chocolates| +|[1422](https://leetcode.com/problems/maximum-score-after-splitting-a-string/)| Maximum Score After Splitting a String| +|[1758](https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/)| Minimum Changes To Make Alternating Binary String| +|[1496](https://leetcode.com/problems/path-crossing/)| Path Crossing| +|[1897](https://leetcode.com/problems/redistribute-characters-to-make-all-strings-equal/)| Redistribute Characters to Make All Strings Equal| +|[1624](https://leetcode.com/problems/largest-substring-between-two-equal-characters/)| Largest Substring Between Two Equal Characters| +|[455](https://leetcode.com/problems/assign-cookies/)| Assign Cookies| +|[501](https://leetcode.com/problems/find-mode-in-binary-search-tree/)| Find Mode in Binary Search Tree| +|[872](https://leetcode.com/problems/leaf-similar-trees/)| Leaf-Similar Trees| +|[119](https://leetcode.com/problems/pascals-triangle-ii/)| Pascal's Triangle II| +|[1700](https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/)| Number of Students Unable to Eat Lunch| +|[678](https://leetcode.com/problems/valid-parenthesis-string/)| Valid Parenthesis String| +|[2000](https://leetcode.com/problems/reverse-prefix-of-word/)| Reverse Prefix of Word| +|[2441](https://leetcode.com/problems/largest-positive-integer-that-exists-with-its-negative/)| Largest Positive Integer That Exists With Its Negative| +|[2373](https://leetcode.com/problems/largest-local-values-in-a-matrix/)| Largest Local Values in a Matrix| +|[2331](https://leetcode.com/problems/evaluate-boolean-binary-tree/)| Evaluate Boolean Binary Tree| +|[860](https://leetcode.com/problems/lemonade-change/)| Lemonade Change| diff --git a/Easy/L101.go b/Easy/L101.go new file mode 100644 index 0000000..5c89435 --- /dev/null +++ b/Easy/L101.go @@ -0,0 +1,29 @@ +package Easy + +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func isSymmetric(root *TreeNode) bool { + if root == nil { + return true + } + + var solve func(left, right *TreeNode) bool + solve = func(left, right *TreeNode) bool { + if left == nil || right == nil { + return left == right + } + if left.Val != right.Val { + return false + } + + return solve(left.Left, right.Right) && solve(left.Right, right.Left) + } + + return solve(root.Left, root.Right) +} diff --git a/Easy/L111.go b/Easy/L111.go new file mode 100644 index 0000000..6d3f859 --- /dev/null +++ b/Easy/L111.go @@ -0,0 +1,41 @@ +package Easy + +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func minDepth(root *TreeNode) int { + if root == nil { + return 0 + } + + var q []*TreeNode + lvl := 1 + q = append(q, root) + + for len(q) > 0 { + size := len(q) + for i := 0; i < size; i++ { + node := q[0] + q = q[1:] + + if node.Left == nil && node.Right == nil { + return lvl + } + + if node.Left != nil { + q = append(q, node.Left) + } + if node.Right != nil { + q = append(q, node.Right) + } + } + lvl++ + } + + return lvl +} diff --git a/Easy/L1137.go b/Easy/L1137.go new file mode 100644 index 0000000..62455c2 --- /dev/null +++ b/Easy/L1137.go @@ -0,0 +1,25 @@ +package Easy + +func tribonacci(n int) int { + mp := map[int]int{ + 0: 0, + 1: 1, + 2: 1, + } + + var solve func(int) int + solve = func(n int) int { + if n < 0 { + return 0 + } + + if v, ok := mp[n]; ok { + return v + } + + mp[n] = solve(n - 1) + solve(n - 2) + solve(n - 3) + return mp[n] + } + + return solve(n) +} diff --git a/Easy/L1160.go b/Easy/L1160.go index 98e1960..bca44ba 100644 --- a/Easy/L1160.go +++ b/Easy/L1160.go @@ -1,25 +1,31 @@ package Easy func countCharacters(words []string, chars string) int { - res, cnt := 0, make([]int, 26) + var isMatch func(s string) bool + res := 0 - for i := range chars { - cnt[chars[i]-'a']++ - } + isMatch = func(s string) bool { + mp := make(map[byte]int) - for _, w := range words { - match, tmp := true, make([]int, 26) - copy(tmp, cnt) + for _, c := range chars { + mp[byte(c)]++ + } - for i := range w { - tmp[w[i]-'a']-- - if tmp[w[i]-'a'] < 0 { - match = false - break + for _, c := range s { + if _, ok := mp[byte(c)]; !ok { + return false + } + mp[byte(c)]-- + if mp[byte(c)] < 0 { + return false } } - if match { + return true + } + + for _, w := range words { + if isMatch(w) { res += len(w) } } diff --git a/Easy/L119.go b/Easy/L119.go new file mode 100644 index 0000000..323d63e --- /dev/null +++ b/Easy/L119.go @@ -0,0 +1,14 @@ +package Easy + +func getRow(rowIndex int) []int { + res := make([]int, rowIndex+1) + res[0] = 1 + + for i := 1; i < rowIndex+1; i++ { + for j := i; j >= 1; j-- { + res[j] += res[j-1] + } + } + + return res +} diff --git a/Easy/L1266.go b/Easy/L1266.go new file mode 100644 index 0000000..d1a4122 --- /dev/null +++ b/Easy/L1266.go @@ -0,0 +1,30 @@ +package Easy + +func minTimeToVisitAllPoints(points [][]int) int { + cnt := 0 + + for i := 1; i < len(points); i++ { + x := abs(points[i - 1][0] - points[i][0]) + y := abs(points[i - 1][1] - points[i][1]) + + cnt += max(x, y) + } + + return cnt +} + +func max(a, b int) int { + if a > b { + return a + } + + return b +} + +func abs(a int) int { + if a < 0 { + return -a + } + + return a +} diff --git a/Easy/L1287.go b/Easy/L1287.go new file mode 100644 index 0000000..3af0d0a --- /dev/null +++ b/Easy/L1287.go @@ -0,0 +1,13 @@ +package Easy + +func findSpecialInteger(arr []int) int { + n, t := len(arr), len(arr)/4 + + for i := 0; i < n-t; i++ { + if arr[i] == arr[i+t] { + return arr[i] + } + } + + return -1 +} diff --git a/Easy/L1422.go b/Easy/L1422.go new file mode 100644 index 0000000..4aeeecd --- /dev/null +++ b/Easy/L1422.go @@ -0,0 +1,27 @@ +package Easy + +func maxScore(s string) int { + zeroes, ones, maximum := 0, 0, math.MinInt32 + + for i := 0; i < len(s); i++ { + if s[i] == '0' { + zeroes++ + } else { + ones++ + } + + if i != len(s)-1 { + maximum = max(maximum, zeroes-ones) + } + } + + return maximum + ones +} + +func max(a, b int) int { + if a > b { + return a + } + + return b +} diff --git a/Easy/L1436.go b/Easy/L1436.go new file mode 100644 index 0000000..9c86773 --- /dev/null +++ b/Easy/L1436.go @@ -0,0 +1,18 @@ +package Easy + +func destCity(paths [][]string) string { + inDeg, outDeg := make(map[string]int), make(map[string]int) + + for _, p := range paths { + outDeg[p[0]] += 1 + inDeg[p[1]] += 1 + } + + for k, v := range inDeg { + if v == 1 && outDeg[k] == 0 { + return k + } + } + + return "" +} diff --git a/Easy/L1456.go b/Easy/L1456.go new file mode 100644 index 0000000..bfe8430 --- /dev/null +++ b/Easy/L1456.go @@ -0,0 +1,32 @@ +package Easy + +var exists struct{} + +func max(a, b int) int { + if a > b { + return a + } + + return b +} +func maxVowels(s string, k int) int { + vowels, ans, cnt := "aeiou", 0, 0 + st := make(map[byte]struct{}) + for i := range vowels { + st[vowels[i]] = exists + } + + for i := range s { + if _, ok := st[s[i]]; ok { + cnt++ + } + if i >= k { + if _, ok := st[s[i - k]]; ok { + cnt-- + } + } + ans = max(ans, cnt) + } + + return ans +} diff --git a/Easy/L1491.go b/Easy/L1491.go new file mode 100644 index 0000000..8aa3f23 --- /dev/null +++ b/Easy/L1491.go @@ -0,0 +1,30 @@ +package Easy + +func average(salary []int) float64 { + var sum float64 + minimum, maximum := math.MaxInt32, math.MinInt32 + + for i := 0; i < len(salary); i++ { + sum += float64(salary[i]) + minimum, maximum = min(minimum, salary[i]), max(maximum, salary[i]) + } + + sum -= float64(minimum + maximum) + return sum / float64(len(salary)-2) +} + +func min(a, b int) int { + if a < b { + return a + } + + return b +} + +func max(a, b int) int { + if a > b { + return a + } + + return b +} diff --git a/Easy/L1496.go b/Easy/L1496.go new file mode 100644 index 0000000..fe3b7c3 --- /dev/null +++ b/Easy/L1496.go @@ -0,0 +1,33 @@ +package Easy + +func isPathCrossing(path string) bool { + var ( + getNextPoint func(b byte) ([]int, string) + key string + ) + visited, curr := make(map[string]bool), []int{0, 0} + visited[fmt.Sprintf("%d#%d", curr[0], curr[1])] = true + + getNextPoint = func(b byte) ([]int, string) { + mp := map[byte][]int{ + 'N': {0, 1}, + 'S': {0, -1}, + 'E': {1, 1}, + 'W': {-1, -1}, + } + + nextPoint := []int{curr[0] + mp[b][0], curr[1] + mp[b][1]} + return nextPoint, fmt.Sprintf("%d#%d", nextPoint[0], nextPoint[1]) + } + + for _, p := range path { + curr, key = getNextPoint(byte(p)) + + if _, ok := visited[key]; ok { + return true + } + visited[key] = true + } + + return false +} diff --git a/Easy/L1512.go b/Easy/L1512.go new file mode 100644 index 0000000..7c9a395 --- /dev/null +++ b/Easy/L1512.go @@ -0,0 +1,15 @@ +package Medium + +func numIdenticalPairs(nums []int) int { + cnt := 0 + + for i := 0; i < len(nums); i++ { + for j := i + 1; j < len(nums); j++ { + if nums[i] == nums[j] { + cnt++ + } + } + } + + return cnt +} diff --git a/Easy/L1539.go b/Easy/L1539.go new file mode 100644 index 0000000..db486c5 --- /dev/null +++ b/Easy/L1539.go @@ -0,0 +1,17 @@ +package Easy + +func findKthPositive(arr []int, k int) int { + left, right := 0, len(arr)-1 + + for left <= right { + mid := left + (right-left)/2 + + if arr[mid]-mid <= k { + left = mid + 1 + } else { + right = mid - 1 + } + } + + return left + k +} diff --git a/Easy/L1572.go b/Easy/L1572.go new file mode 100644 index 0000000..c5d4f63 --- /dev/null +++ b/Easy/L1572.go @@ -0,0 +1,15 @@ +package Easy + +func diagonalSum(mat [][]int) int { + sum, n := 0, len(mat[0]) + + for i := 0; i < n; i++ { + sum += mat[i][i] + + if i != n - 1 - i { + sum += mat[i][n - 1 - i] + } + } + + return sum +} diff --git a/Easy/L1582.go b/Easy/L1582.go new file mode 100644 index 0000000..05bafc4 --- /dev/null +++ b/Easy/L1582.go @@ -0,0 +1,23 @@ +package Easy + +func numSpecial(mat [][]int) int { + m, n, res, col, row := len(mat), len(mat[0]), 0, make([]int, len(mat[0])), make([]int, len(mat)) + + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if mat[i][j] == 1 { + col[j], row[i] = col[j]+1, row[i]+1 + } + } + } + + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if mat[i][j] == 1 && row[i] == 1 && col[j] == 1 { + res++ + } + } + } + + return res +} diff --git a/Easy/L1624.go b/Easy/L1624.go new file mode 100644 index 0000000..9216099 --- /dev/null +++ b/Easy/L1624.go @@ -0,0 +1,19 @@ +package Easy + +func maxLengthBetweenEqualCharacters(s string) int { + indexes, dist := make(map[byte]int), -1 + + for i := 0; i < len(s); i++ { + if v, ok := indexes[s[i]-'a']; ok { + dist = max(dist, i-v+1) + } else { + indexes[s[i]-'a'] = i + } + } + + if dist == -1 { + return dist + } + + return dist - 2 +} diff --git a/Easy/L1700.go b/Easy/L1700.go new file mode 100644 index 0000000..da13a4d --- /dev/null +++ b/Easy/L1700.go @@ -0,0 +1,29 @@ +package Easy + +func countStudents(students []int, sandwiches []int) int { + ones, zeroes := 0, 0 + + for _, student := range students { + if student == 0 { + zeroes++ + } else { + ones++ + } + } + + for _, sandwich := range sandwiches { + if sandwich == 0 { + if zeroes == 0 { + return ones + } + zeroes-- + } else { + if ones == 0 { + return zeroes + } + ones-- + } + } + + return 0 +} diff --git a/Easy/L1716.go b/Easy/L1716.go new file mode 100644 index 0000000..f70f12f --- /dev/null +++ b/Easy/L1716.go @@ -0,0 +1,19 @@ +package Easy + +func totalMoney(n int) int { + sum, prev, tot, cnt := 0, 1, 0, 0 + + for i := 1; i <= n; i++ { + if cnt == 7 { + cnt, tot = 0, prev+1 + prev = tot + } else { + tot++ + } + + sum += tot + cnt++ + } + + return sum +} diff --git a/Easy/L1758.go b/Easy/L1758.go new file mode 100644 index 0000000..76d5330 --- /dev/null +++ b/Easy/L1758.go @@ -0,0 +1,18 @@ +package Easy + +func minOperations(s string) int { + swaps := 0 + for i := 0; i < len(s); i++ { + if i %2 == 0 { + if s[i] != '0' { + swaps++ + } + } else { + if s[i] != '1' { + swaps++ + } + } + } + + return min(swaps, len(s) - swaps) +} diff --git a/Easy/L1768.go b/Easy/L1768.go new file mode 100644 index 0000000..ce7213b --- /dev/null +++ b/Easy/L1768.go @@ -0,0 +1,22 @@ +package Easy + +func mergeAlternately(word1 string, word2 string) string { + i, j, n, m := 0, 0, len(word1), len(word2) + res := make([]byte, n + m) + + for k := 0; k < n + m; k++ { + if i < n && j < m { + res[k] = word1[i] + k, i = k + 1, i + 1 + } else if i < n { + res[k] = word1[i] + i++ + } + if j < m { + res[k] = word2[j] + j++ + } + } + + return string(res) +} diff --git a/Easy/L1822.go b/Easy/L1822.go new file mode 100644 index 0000000..170c4db --- /dev/null +++ b/Easy/L1822.go @@ -0,0 +1,14 @@ +package Easy + +func arraySign(nums []int) int { + sign := 1 + for _, n := range nums { + if n < 0 { + sign *= -1 + } else if n == 0 { + return 0 + } + } + + return sign +} diff --git a/Easy/L1897.go b/Easy/L1897.go new file mode 100644 index 0000000..31fa2f9 --- /dev/null +++ b/Easy/L1897.go @@ -0,0 +1,19 @@ +package Easy + +func makeEqual(words []string) bool { + counts := make(map[byte]int) + for _, w := range words { + for i := 0; i < len(w); i++ { + counts[w[i] - 'a']++ + } + } + + n := len(words) + for _, v := range counts { + if v % n != 0 { + return false + } + } + + return true +} diff --git a/Easy/L1903.go b/Easy/L1903.go new file mode 100644 index 0000000..4d2589f --- /dev/null +++ b/Easy/L1903.go @@ -0,0 +1,11 @@ +package Easy + +func largestOddNumber(num string) string { + for i := len(num) - 1; i >= 0; i-- { + if ((num[i] - '0') % 2) > 0 { + return num[0 : i+1] + } + } + + return "" +} diff --git a/Easy/L191.go b/Easy/L191.go new file mode 100644 index 0000000..0f5c33f --- /dev/null +++ b/Easy/L191.go @@ -0,0 +1,12 @@ +package Easy + +func hammingWeight(num uint32) int { + cnt := 0 + + for num != 0 { + num = num & (num - 1) + cnt++ + } + + return cnt +} diff --git a/Easy/L1913.go b/Easy/L1913.go new file mode 100644 index 0000000..f8b65a0 --- /dev/null +++ b/Easy/L1913.go @@ -0,0 +1,20 @@ +package Easy + +func maxProductDifference(nums []int) int { + largest, secondLargest, smallest, secondSmallest := 0, 0, math.MaxInt32, math.MaxInt32 + for i := 0; i < len(nums); i++ { + if nums[i] >= largest { + secondLargest, largest = largest, nums[i] + } else if nums[i] > secondLargest { + secondLargest = nums[i] + } + + if nums[i] <= smallest { + secondSmallest, smallest = smallest, nums[i] + } else if nums[i] < secondSmallest { + secondSmallest = nums[i] + } + } + + return largest*secondLargest - smallest*secondSmallest +} diff --git a/Easy/L2000.go b/Easy/L2000.go new file mode 100644 index 0000000..333db46 --- /dev/null +++ b/Easy/L2000.go @@ -0,0 +1,21 @@ +package Easy + +func reversePrefix(word string, ch byte) string { + for i := 0; i < len(word); i++ { + if word[i] == ch { + return reverse(word[:i+1]) + word[i+1:] + } + } + + return word +} + +func reverse(s string) string { + n := len(s) + runes := make([]rune, n) + for _, ch := range s { + n-- + runes[n] = ch + } + return string(runes) +} diff --git a/Easy/L2215.go b/Easy/L2215.go new file mode 100644 index 0000000..3581603 --- /dev/null +++ b/Easy/L2215.go @@ -0,0 +1,35 @@ +package Easy + +var exists struct{} + +func findDifference(nums1 []int, nums2 []int) [][]int { + var res [][]int + st1, st2, i := make(map[int]struct{}), make(map[int]struct{}), 0 + + for i = 0; i < len(nums1); i++ { + st1[nums1[i]] = exists + if i < len(nums2) { + st2[nums2[i]] = exists + } + } + for ; i < len(nums2); i++ { + st2[nums2[i]] = exists + } + + var res1, res2 []int + for k, _ := range st1 { + if _, ok := st2[k]; ok { + continue + } + res1 = append(res1, k) + } + for k, _ := range st2 { + if _, ok := st1[k]; ok { + continue + } + res2 = append(res2, k) + } + + res = append(res, res1, res2) + return res +} diff --git a/Easy/L2264.go b/Easy/L2264.go new file mode 100644 index 0000000..213b404 --- /dev/null +++ b/Easy/L2264.go @@ -0,0 +1,24 @@ +package Easy + +func largestGoodInteger(num string) string { + res := -1 + for i := 0; i+2 < len(num); i++ { + if num[i] == num[i+1] && num[i+1] == num[i+2] { + res = max(res, int(num[i]-'0')) + } + } + + if res == -1 { + return "" + } + + return fmt.Sprintf("%d%d%d", res, res, res) +} + +func max(a, b int) int { + if a > b { + return a + } + + return b +} diff --git a/Easy/L2331.go b/Easy/L2331.go new file mode 100644 index 0000000..0a895c1 --- /dev/null +++ b/Easy/L2331.go @@ -0,0 +1,39 @@ +package Easy + +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func evaluateTree(root *TreeNode) bool { + var solve func(root *TreeNode) bool + mp := map[int]bool{ + 0: false, + 1: true, + } + + solve = func(node *TreeNode) bool { + if node.Right == nil && node.Left == nil { + return mp[node.Val] + } + + var left, right bool + if node.Left != nil { + left = solve(node.Left) + } + if node.Right != nil { + right = solve(node.Right) + } + + if node.Val == 2 { + return left || right + } + + return left && right + } + + return solve(root) +} diff --git a/Easy/L2373.go b/Easy/L2373.go new file mode 100644 index 0000000..188b7cc --- /dev/null +++ b/Easy/L2373.go @@ -0,0 +1,25 @@ +package Easy + +func largestLocal(grid [][]int) [][]int { + n := len(grid) + res := make([][]int, n-2) + for i := 0; i < len(res); i++ { + res[i] = make([]int, n-2) + } + + for i := 1; i < n-1; i++ { + for j := 1; j < n-1; j++ { + tmp := 0 + + for k := i - 1; k <= i + 1; k++ { + for l := j - 1; l <= j + 1; l++ { + tmp = max(tmp, grid[k][l]) + } + } + + res[i-1][j-1] = tmp + } + } + + return res +} diff --git a/Easy/L2441.go b/Easy/L2441.go new file mode 100644 index 0000000..5a9abef --- /dev/null +++ b/Easy/L2441.go @@ -0,0 +1,22 @@ +package Easy + +func findMaxK(nums []int) int { + mp, res := make(map[int]bool), -1 + + for _, n := range nums { + if mp[-n] { + res = max(res, abs(n)) + } + mp[n] = true + } + + return res +} + +func abs(a int) int { + if a < 0 { + return -a + } + + return a +} diff --git a/Easy/L2706.go b/Easy/L2706.go new file mode 100644 index 0000000..76f10bb --- /dev/null +++ b/Easy/L2706.go @@ -0,0 +1,23 @@ +package Easy + +func buyChoco(prices []int, money int) int { + if len(prices) < 2 { + return money + } + + first, second := math.MaxInt32, math.MaxInt32 + + for _, p := range prices { + if p < first { + second, first = first, p + }else if p < second { + second = p + } + } + + if first + second > money { + return money + } + + return money - (first + second) +} diff --git a/Easy/L455.go b/Easy/L455.go new file mode 100644 index 0000000..3ef58ed --- /dev/null +++ b/Easy/L455.go @@ -0,0 +1,15 @@ +package Easy + +func findContentChildren(children []int, cookies []int) int { + sort.Ints(children) + sort.Ints(cookies) + + child := 0 + for cookie := 0; child < len(children) && cookie < len(cookies); cookie++ { + if cookies[cookie] >= children[child] { + child++ + } + } + + return child +} diff --git a/Easy/L501.go b/Easy/L501.go new file mode 100644 index 0000000..6823db0 --- /dev/null +++ b/Easy/L501.go @@ -0,0 +1,35 @@ +package Easy + +func findMode(root *TreeNode) []int { + var ( + modes []int + solve func(node *TreeNode, count *int) + ) + prev, cnt, maxCnt := root, 0, math.MinInt32 + + solve = func(node *TreeNode, count *int) { + if node == nil { + return + } + solve(node.Left, count) + if prev.Val == node.Val { + *count++ + } else { + *count = 1 + } + + if *count == maxCnt { + modes = append(modes, node.Val) + } else if *count > maxCnt { + modes = nil + modes = append(modes, node.Val) + maxCnt = *count + } + + prev = node + solve(node.Right, count) + } + + solve(root, &cnt) + return modes +} diff --git a/Easy/L509.go b/Easy/L509.go index dc20ce7..b4ab958 100644 --- a/Easy/L509.go +++ b/Easy/L509.go @@ -17,3 +17,25 @@ func fibo(mp map[int]int, n int) int { return mp[n] } + +// With anonymous function +func fib(n int) int { + mp := map[int]int{ + 0: 0, + 1: 1, + 2: 1, + } + + var solve func(n int) int + solve = func(n int) int { + if v, ok := mp[n]; ok { + return v + } + + mp[n] = solve(n-1) + solve(n-2) + + return mp[n] + } + + return solve(n) +} diff --git a/Easy/L530.go b/Easy/L530.go new file mode 100644 index 0000000..ff78a39 --- /dev/null +++ b/Easy/L530.go @@ -0,0 +1,35 @@ +package Easy + +func min(a, b int) int { + if a < b { + return a + } + + return b +} + +func getMinimumDifference(root *TreeNode) int { + var ( + solve func(root *TreeNode) int + ) + minimum, prev := math.MaxInt32, -1 + + solve = func(root *TreeNode) int { + if root == nil { + return minimum + } + + solve(root.Left) + + if prev != -1 { + minimum = min(minimum, root.Val-prev) + } + prev = root.Val + + solve(root.Right) + + return minimum + } + + return solve(root) +} diff --git a/Easy/L606.go b/Easy/L606.go new file mode 100644 index 0000000..7b07fd0 --- /dev/null +++ b/Easy/L606.go @@ -0,0 +1,45 @@ +package Easy + +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func tree2str(root *TreeNode) string { + var ( + sb strings.Builder + solve func(root *TreeNode) + ) + if root == nil { + return "" + } + + solve = func(root *TreeNode) { + sb.WriteString(fmt.Sprintf("%d", root.Val)) + if root.Left == nil && root.Right == nil { + return + } + + if root.Left != nil { + sb.WriteString("(") + solve(root.Left) + sb.WriteString(")") + } + + if root.Right != nil { + if root.Left == nil { + sb.WriteString("()") + } + + sb.WriteString("(") + solve(root.Right) + sb.WriteString(")") + } + } + + solve(root) + return sb.String() +} diff --git a/Easy/L661.go b/Easy/L661.go new file mode 100644 index 0000000..c59cab8 --- /dev/null +++ b/Easy/L661.go @@ -0,0 +1,37 @@ +package Easy + +func imageSmoother(img [][]int) [][]int { + if len(img) == 0 { + return [][]int{} + } + + dirs := [][]int{{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 0}, {0, 1}, {1, -1}, {1, 0}, {1, 1}} + rows, cols := len(img), len(img[0]) + var isValid func(x, y int) bool + + isValid = func(x, y int) bool { + return x >= 0 && x < rows && y >= 0 && y < cols + } + + res := make([][]int, rows) + for i := 0; i < rows; i++ { + res[i] = make([]int, cols) + } + + for row := 0; row < rows; row++ { + for col := 0; col < cols; col++ { + cnt, sum := 0, 0 + for _, d := range dirs { + newRow, newCol := row+d[0], col+d[1] + if isValid(newRow, newCol) { + cnt++ + sum += img[newRow][newCol] + } + } + + res[row][col] = sum / cnt + } + } + + return res +} diff --git a/Easy/L678.go b/Easy/L678.go new file mode 100644 index 0000000..237fa12 --- /dev/null +++ b/Easy/L678.go @@ -0,0 +1,22 @@ +package Easy + +func checkValidString(s string) bool { + cMin, cMax := 0, 0 + for i := 0; i < len(s); i++ { + if s[i] == '(' { + cMax, cMin = cMax+1, cMin+1 + } else if s[i] == ')' { + cMax, cMin = cMax-1, cMin-1 + } else if s[i] == '*' { + cMax, cMin = cMax+1, cMin-1 + } + + if cMax < 0 { + return false + } + + cMin = max(cMin, 0) + } + + return cMin == 0 +} diff --git a/Easy/L70.go b/Easy/L70.go index a487033..b3759d7 100644 --- a/Easy/L70.go +++ b/Easy/L70.go @@ -16,3 +16,28 @@ func dp(mp map[int]int, n int) int { return mp[n] } + +// With anonymous function +func climbStairs(n int) int { + mp := map[int]int{ + 0: 0, + 1: 1, + 2: 2, + } + + var solve func(int) int + solve = func(n int) int { + if n < 0 { + return 0 + } + + if v, ok := mp[n]; ok { + return v + } + + mp[n] = solve(n-1) + solve(n-2) + return mp[n] + } + + return solve(n) +} diff --git a/Easy/L744.go b/Easy/L744.go new file mode 100644 index 0000000..cf207de --- /dev/null +++ b/Easy/L744.go @@ -0,0 +1,20 @@ +package Easy + +func nextGreatestLetter(letters []byte, target byte) byte { + low, high := 0, len(letters) - 1 + + if target >= letters[len(letters) - 1] { + return letters[0] + } + + for low < high { + mid := low + (high - low) / 2 + if letters[mid] > target { + high = mid + } else { + low = mid + 1 + } + } + + return letters[low % len(letters)] +} diff --git a/Easy/L746.go b/Easy/L746.go new file mode 100644 index 0000000..7ee5a88 --- /dev/null +++ b/Easy/L746.go @@ -0,0 +1,31 @@ +package Easy + +func minCostClimbingStairs(cost []int) int { + mp := make(map[int]int) + + var solve func(int) int + solve = func(n int) int { + if n >= len(cost) { + return 0 + } + if v, ok := mp[n]; ok { + return v + } + + oneStep := cost[n] + solve(n + 1) + twoStep := cost[n] + solve(n + 2) + + mp[n] = min(oneStep, twoStep) + return mp[n] + } + + return min(solve(0), solve(1)) +} + +func min(a, b int) int { + if a < b { + return a + } + + return b +} diff --git a/Easy/L783.go b/Easy/L783.go new file mode 100644 index 0000000..a48fe7a --- /dev/null +++ b/Easy/L783.go @@ -0,0 +1,31 @@ +package Easy + +func min(a, b int) int { + if a < b { + return a + } + + return b +} + +func minDiffInBST(root *TreeNode) int { + var prev *TreeNode + minimum := math.MaxInt32 + + solve := func(root *TreeNode, prev **TreeNode) {} + solve = func(root *TreeNode, prev **TreeNode) { + if root == nil { + return + } + + solve(root.Left, prev) + if prev != nil && *prev != nil { + minimum = min(minimum, root.Val-(*prev).Val) + } + *prev = root + solve(root.Right, prev) + } + + solve(root, &prev) + return minimum +} diff --git a/Easy/L860.py b/Easy/L860.py new file mode 100644 index 0000000..5473705 --- /dev/null +++ b/Easy/L860.py @@ -0,0 +1,17 @@ +class Solution: + def lemonadeChange(self, bills): + five = ten = 0 + for num in bills: + if num == 5: + five += 1 + elif num == 10 and five: + ten += 1 + five -= 1 + elif num == 20 and five and ten: + five -= 1 + ten -= 1 + elif num == 20 and five >= 3: + five -= 3 + else: + return False + return True diff --git a/Easy/L872.go b/Easy/L872.go new file mode 100644 index 0000000..76a6cb8 --- /dev/null +++ b/Easy/L872.go @@ -0,0 +1,32 @@ +package Easy + +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func leafSimilar(root1 *TreeNode, root2 *TreeNode) bool { + var ( + root1Leaves, root2Leaves string + solve func(root *TreeNode, rootLeaves *string) + ) + + solve = func(root *TreeNode, rootLeaves *string) { + if root == nil { + return + } + if root.Left == nil && root.Right == nil { + *rootLeaves = fmt.Sprintf("%s%d#", *rootLeaves, root.Val) + } + solve(root.Left, rootLeaves) + solve(root.Right, rootLeaves) + } + + solve(root1, &root1Leaves) + solve(root2, &root2Leaves) + + return root1Leaves == root2Leaves +} diff --git a/Easy/L94.go b/Easy/L94.go new file mode 100644 index 0000000..f0fd539 --- /dev/null +++ b/Easy/L94.go @@ -0,0 +1,29 @@ +package Easy + +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func inorderTraversal(root *TreeNode) []int { + var ( + res []int + solve func(root *TreeNode) + ) + + solve = func(root *TreeNode) { + if root == nil { + return + } + + solve(root.Left) + res = append(res, root.Val) + solve(root.Right) + } + + solve(root) + return res +} diff --git a/Hard.md b/Hard.md new file mode 100644 index 0000000..8d0115c --- /dev/null +++ b/Hard.md @@ -0,0 +1,85 @@ +## Hard +|LC #|Description| +|:-:|:-| +|[354](https://leetcode.com/problems/russian-doll-envelopes/)| Russian Doll Envelopes| +|[936](https://leetcode.com/problems/stamping-the-sequence/)| Stamping The Sequence| +|[32](https://leetcode.com/problems/longest-valid-parentheses/)| Longest Valid Parentheses| +|[1559](https://leetcode.com/problems/detect-cycles-in-2d-grid/)| Detect Cycles in 2D Grid| +|[329](https://leetcode.com/problems/longest-increasing-path-in-a-matrix/)| Longest Increasing Path in a Matrix| +|[1192](https://leetcode.com/problems/critical-connections-in-a-network/)| Critical Connections in a Network| +|[980](https://leetcode.com/problems/unique-paths-iii/)| Unique Paths III| +|[745](https://leetcode.com/problems/prefix-and-suffix-search/)| Prefix and Suffix Search| +|[630](https://leetcode.com/problems/course-schedule-iii/)| Course Schedule III| +|[65](https://leetcode.com/problems/valid-number/)| Valid Number| +|[968](https://leetcode.com/problems/binary-tree-cameras/)| Binary Tree Cameras| +|[1473](https://leetcode.com/problems/paint-house-iii/)| Paint House III| +|[51](https://leetcode.com/problems/n-queens/)| N-Queens| +|[52](https://leetcode.com/problems/n-queens-ii/)| N-Queens II| +|[778](https://leetcode.com/problems/swim-in-rising-water/)| Swim in Rising Water| +|[315](https://leetcode.com/problems/count-of-smaller-numbers-after-self/)| Count of Smaller Numbers After Self| +|[135](https://leetcode.com/problems/candy/)| Candy| +|[927](https://leetcode.com/problems/three-equal-parts/)| Three Equal Parts| +|[25](https://leetcode.com/problems/reverse-nodes-in-k-group/)| Reverse Nodes in k-Group| +|[233](https://leetcode.com/problems/number-of-digit-one/)| Number of Digit One| +|[42](https://leetcode.com/problems/trapping-rain-water/)| Trapping Rain Water| +|[132](https://leetcode.com/problems/palindrome-partitioning-ii/)| Palindrome Partitioning II| +|[546](https://leetcode.com/problems/remove-boxes/)| Remove Boxes| +|[37](https://leetcode.com/problems/sudoku-solver/)| Sudoku Solver| +|[850](https://leetcode.com/problems/rectangle-area-ii/)| Rectangle Area II| +|[330](https://leetcode.com/problems/patching-array//)| Patching Array| +|[899](https://leetcode.com/problems/orderly-queue/)| Orderly Queue| +|[224](https://leetcode.com/problems/basic-calculator/)| Basic Calculator| +|[782](https://leetcode.com/problems/transform-to-chessboard/)| Transform to Chessboard| +|[174](https://leetcode.com/problems/dungeon-game/)| Dungeon Game| +|[123](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/)| Best Time to Buy and Sell Stock III| +|[154](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/)| Find Minimum in Rotated Sorted Array II| +|[668](https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/)| Kth Smallest Number in Multiplication Table| +|[952](https://leetcode.com/problems/largest-component-size-by-common-factor/)| Largest Component Size by Common Factor| +|[85](https://leetcode.com/problems/maximal-rectangle/)| Maximal Rectangle| +|[1032](https://leetcode.com/problems/stream-of-characters/)| Stream of Characters| +|[878](https://leetcode.com/problems/nth-magical-number/)| Nth Magical Number| +|[902](https://leetcode.com/problems/numbers-at-most-n-given-digit-set/)| Numbers At Most N Given Digit Set| +|[1463](https://leetcode.com/problems/cherry-pickup-ii/)| Cherry Pickup II| +|[1345](https://leetcode.com/problems/jump-game-iv/)| Jump Game IV| +|[1510](https://leetcode.com/problems/stone-game-iv/)| Stone Game IV| +|[127](https://leetcode.com/problems/word-ladder/)| Word Ladder| +|[410](https://leetcode.com/problems/split-array-largest-sum/)| Split Array Largest Sum| +|[629](https://leetcode.com/problems/k-inverse-pairs-array/)| K Inverse Pairs Array| +|[1074](https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/)| Number of Submatrices That Sum to Target| +|[1531](https://leetcode.com/problems/string-compression-ii/)| String Compression II| +|[1335](https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/)| Minimum Difficulty of a Job Schedule| +|[76](https://leetcode.com/problems/minimum-window-substring/)| Minimum Window Substring| +|[2136](https://leetcode.com/problems/earliest-possible-day-of-full-bloom/)| Earliest Possible Day of Full Bloom| +|[2193](https://leetcode.com/problems/minimum-number-of-moves-to-make-palindrome/)| Minimum Number of Moves to Make Palindrome| +|[1235](https://leetcode.com/problems/maximum-profit-in-job-scheduling/)| Maximum Profit in Job Scheduling| +|[446](https://leetcode.com/problems/arithmetic-slices-ii-subsequence/)| Arithmetic Slices II - Subsequence| +|[124](https://leetcode.com/problems/binary-tree-maximum-path-sum/)| Binary Tree Maximum Path Sum| +|[600](https://leetcode.com/problems/non-negative-integers-without-consecutive-ones/)| Non-negative Integers without Consecutive Ones| +|[72](https://leetcode.com/problems/edit-distance/)| Edit Distance| +|[1340](https://leetcode.com/problems/jump-game-v/)| Jump Game V| +|[403](https://leetcode.com/problems/frog-jump/)| Frog Jump| +|[188](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/)| Best Time to Buy and Sell Stock IV| +|[149](https://leetcode.com/problems/max-points-on-a-line/)| Max Points on a Line| +|[140](https://leetcode.com/problems/word-break-ii/)| Word Break II| +|[1289](https://leetcode.com/problems/minimum-falling-path-sum-ii/)| Minimum Falling Path Sum II| +|[2246](https://leetcode.com/problems/longest-path-with-different-adjacent-characters/)| Longest Path With Different Adjacent Characters| +|[2421](https://leetcode.com/problems/number-of-good-paths/)| Number of Good Paths| +|[472](https://leetcode.com/problems/concatenated-words/)| Concatenated Words| +|[2444](https://leetcode.com/problems/count-subarrays-with-fixed-bounds/)| Count Subarrays With Fixed Bounds| +|[23](https://leetcode.com/problems/merge-k-sorted-lists/)| Merge k Sorted Lists| +|[2360](https://leetcode.com/problems/longest-cycle-in-a-graph/)| Longest Cycle in a Graph| +|[1402](https://leetcode.com/problems/reducing-dishes/)| Reducing Dishes| +|[87](https://leetcode.com/problems/scramble-string/)| Scramble String| +|[1857](https://leetcode.com/problems/largest-color-value-in-a-directed-graph/)| Largest Color Value in a Directed Graph| +|[879](https://leetcode.com/problems/profitable-schemes/)| Profitable Schemes| +|[839](https://leetcode.com/problems/similar-string-groups/)| Similar String Groups| +|[2551](https://leetcode.com/problems/put-marbles-in-bags/)| Put Marbles in Bags| +|[2141](https://leetcode.com/problems/maximum-running-time-of-n-computers/)| Maximum Running Time of N Computers| +|[664](https://leetcode.com/problems/strange-printer/)| Strange Printer| +|[239](https://leetcode.com/problems/sliding-window-maximum/)| Sliding Window Maximum| +|[68](https://leetcode.com/problems/text-justification/)| Text Justification| +|[1611](https://leetcode.com/problems/minimum-one-bit-operations-to-make-integers-zero/)| Minimum One Bit Operations to Make Integers Zero| +|[1458](https://leetcode.com/problems/max-dot-product-of-two-subsequences/)| Max Dot Product of Two Subsequences| +|[1793](https://leetcode.com/problems/maximum-score-of-a-good-subarray/)| Maximum Score of a Good Subarray| +|[514](https://leetcode.com/problems/freedom-trail/)| Freedom Trail| +|[834](https://leetcode.com/problems/sum-of-distances-in-tree/)| Sum of Distances in Tree| diff --git a/Hard/L1402.go b/Hard/L1402.go new file mode 100644 index 0000000..65fd78d --- /dev/null +++ b/Hard/L1402.go @@ -0,0 +1,34 @@ +package Hard + +func maxSatisfaction(satisfaction []int) int { + sort.Ints(satisfaction) + mp := make(map[string]int) + var solve func(idx, time int) int + + solve = func(idx, time int) int { + if idx == len(satisfaction) { + return 0 + } + + key := fmt.Sprintf("%d-%d", idx, time) + if v, ok := mp[key]; ok { + return v + } + + includeDish := (satisfaction[idx] * (time + 1)) + solve(idx+1, time+1) + excludeDish := solve(idx+1, time) + + mp[key] = max(includeDish, excludeDish) + return mp[key] + } + + return solve(0, 0) +} + +func max(a, b int) int { + if a > b { + return a + } + + return b +} diff --git a/Hard/L1458.go b/Hard/L1458.go new file mode 100644 index 0000000..61f3071 --- /dev/null +++ b/Hard/L1458.go @@ -0,0 +1,33 @@ +package Hard + +func maxDotProduct(nums1 []int, nums2 []int) int { + dp := make(map[string]int) + var solve func(n, m int) int + + solve = func(n, m int) int { + key := fmt.Sprintf("%d#%d", n, m) + if v, ok := dp[key]; ok { + return v + } + + p1 := nums1[n] * nums2[m] + ans := p1 + + if (n < len(nums1)-1) && (m < len(nums2)-1) { + p1 += solve(n+1, m+1) + } + + if n < len(nums1)-1 { + ans = max(ans, solve(n+1, m)) + } + + if m < len(nums2)-1 { + ans = max(ans, solve(n, m+1)) + } + + dp[key] = max(ans, p1) + return dp[key] + } + + return solve(0, 0) +} diff --git a/Hard/L1611.go b/Hard/L1611.go new file mode 100644 index 0000000..577045f --- /dev/null +++ b/Hard/L1611.go @@ -0,0 +1,19 @@ +package Medium + +func minimumOneBitOperations(n int) int { + var solve func(n, res int) int + + solve = func(n, res int) int { + if n == 0 { + return res + } + b := 1 + for (b << 1) <= n { + b = b << 1 + } + + return solve((b >> 1) ^ b ^ n, res + b) + } + + return solve(n, 0) +} diff --git a/Hard/L1793.go b/Hard/L1793.go new file mode 100644 index 0000000..cd55da3 --- /dev/null +++ b/Hard/L1793.go @@ -0,0 +1,23 @@ +package Hard + +func maximumScore(nums []int, k int) int { + maxScore, minValue := nums[k], nums[k] + left, right := k, k + + for left >= 0 && right < len(nums) { + minValue = min(minValue, min(nums[left], nums[right])) + maxScore = max(minValue*(right-left+1), maxScore) + + if left == 0 && right < len(nums) { + right++ + } else if right == len(nums)-1 && left >= 0 { + left-- + } else if nums[right+1] > nums[left-1] { + right++ + } else { + left-- + } + } + + return maxScore +} diff --git a/Hard/L1857.go b/Hard/L1857.go new file mode 100644 index 0000000..cdbdf73 --- /dev/null +++ b/Hard/L1857.go @@ -0,0 +1,76 @@ +package Hard + +func max(a, b int) int { + if a > b { + return a + } + + return b +} + +func largestPathValue(colors string, edges [][]int) int { + var graph [][]int + n, inDegree := len(colors), make([]int, len(colors)) + + for i := 0; i < n; i++ { + graph = append(graph, make([]int, 0)) + } + for _, e := range edges { + u, v := e[0], e[1] + inDegree[v]++ + graph[u] = append(graph[u], v) + } + + mp := make([][]int, n) + for i := 0; i < n; i++ { + mp[i] = make([]int, 26) + } + + var q []int + for i := 0; i < n; i++ { + if inDegree[i] == 0 { + q = append(q, i) + mp[i][colors[i]-'a'] = 1 + } + } + + getMax := func(nums []int) int { + maxi := math.MinInt32 + + for _, n := range nums { + maxi = max(maxi, n) + } + + return maxi + } + + var res, seen int + for len(q) > 0 { + node := q[0] + q = q[1:] + seen++ + + res = max(res, getMax(mp[node])) + + for _, nei := range graph[node] { + for i := 0; i < 26; i++ { + val := mp[node][i] + if int(colors[nei]-'a') == i { + val++ + } + mp[nei][i] = max(mp[nei][i], val) + } + inDegree[nei]-- + + if inDegree[nei] == 0 { + q = append(q, nei) + } + } + } + + if seen == n { + return res + } + + return -1 +} diff --git a/Hard/L2141.go b/Hard/L2141.go new file mode 100644 index 0000000..ea4f548 --- /dev/null +++ b/Hard/L2141.go @@ -0,0 +1,47 @@ +package Hard + +func maxRunTime(n int, batteries []int) int64 { + var ( + canFit func(k int64) bool + lower, upper, res, batSum int64 + ) + + for _, b := range batteries { + batSum += int64(b) + } + lower, upper, res = 0, batSum/int64(n), -1 + + canFit = func(k int64) bool { + var ( + currBatSum, target int64 + ) + + target = int64(n) * k + for _, b := range batteries { + if int64(b) < k { + currBatSum += int64(b) + } else { + currBatSum += k + } + + if currBatSum >= target { + return true + } + } + + return currBatSum >= target + } + + for lower <= upper { + var mid int64 + mid = lower + (upper - lower) / 2 + + if canFit(mid) { + res, lower = mid, mid + 1 + } else { + upper = mid - 1 + } + } + + return res +} diff --git a/Hard/L23.go b/Hard/L23.go new file mode 100644 index 0000000..d3a69b6 --- /dev/null +++ b/Hard/L23.go @@ -0,0 +1,50 @@ +package Hard + +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func mergeKLists(lists []*ListNode) *ListNode { + var ( + merge func(l1, l2 *ListNode) *ListNode + partition func(start, end int) *ListNode + ) + + merge = func(l1, l2 *ListNode) *ListNode { + if l1 == nil { + return l2 + } + + if l2 == nil { + return l1 + } + + if l1.Val < l2.Val { + l1.Next = merge(l1.Next, l2) + return l1 + } + + l2.Next = merge(l1, l2.Next) + return l2 + } + + partition = func(start, end int) *ListNode { + if start == end { + return lists[start] + } + + if start >= end { + return nil + } + + q := (start + end) / 2 + l1, l2 := partition(start, q), partition(q + 1, end) + + return merge(l1, l2) + } + + return partition(0, len(lists) - 1) +} diff --git a/Hard/L2360.go b/Hard/L2360.go new file mode 100644 index 0000000..13b279b --- /dev/null +++ b/Hard/L2360.go @@ -0,0 +1,42 @@ +package Hard + +func longestCycle(edges []int) int { + var exists struct{} + res, st := -1, make(map[int]struct{}) + + for _, e := range edges { + if e != -1 { + if _, contains := st[e]; !contains { + mp, pos := make(map[int]int), 0 + mp[e], st[e] = pos, exists + + for edges[e] != -1 { + e = edges[e] + + if _, contains = mp[e]; contains { + res = max(res, pos-mp[e]+1) + break + } + + if _, contains = st[e]; contains { + break + } + + pos++ + mp[e] = pos + st[e] = exists + } + } + } + } + + return res +} + +func max(a, b int) int { + if a > b { + return a + } + + return b +} diff --git a/Hard/L239.go b/Hard/L239.go new file mode 100644 index 0000000..2770efa --- /dev/null +++ b/Hard/L239.go @@ -0,0 +1,28 @@ +package Hard + +func maxSlidingWindow(nums []int, k int) []int { + if len(nums) == 0 || k <= 0 { + return []int{0} + } + + var ( + res, q []int + ) + n := len(nums) + + for i := 0; i < n; i++ { + for len(q) > 0 && q[0] < (i-k+1) { + q = q[1:] + } + for len(q) > 0 && nums[q[len(q)-1]] < nums[i] { + q = q[:len(q)-1] + } + q = append(q, i) + + if i >= k-1 { + res = append(res, nums[q[0]]) + } + } + + return res +} diff --git a/Hard/L2444.go b/Hard/L2444.go new file mode 100644 index 0000000..d5ca6b3 --- /dev/null +++ b/Hard/L2444.go @@ -0,0 +1,35 @@ +package Hard + +func countSubarrays(nums []int, minK int, maxK int) int64 { + var ( + res, start int64 + minStart, maxStart int64 + ) + minFound, maxFound := false, false + + for i := range nums { + n := nums[i] + if n < minK || n > maxK { + minFound, maxFound, start = false, false, int64(i+1) + } + if n == minK { + minFound, minStart = true, int64(i) + } + if n == maxK { + maxFound, maxStart = true, int64(i) + } + if minFound && maxFound { + res += min(minStart, maxStart) - start + 1 + } + } + + return res +} + +func min(a, b int64) int64 { + if a < b { + return a + } + + return b +} diff --git a/Hard/L2551.go b/Hard/L2551.go new file mode 100644 index 0000000..ca91af2 --- /dev/null +++ b/Hard/L2551.go @@ -0,0 +1,17 @@ +package Hard + +func putMarbles(weights []int, k int) int64 { + n, pairs := len(weights), make([]int, len(weights)-1) + + for i := 1; i < n; i++ { + pairs[i-1] = weights[i] + weights[i-1] + } + sort.Ints(pairs) + minScore, maxScore := 0, 0 + for i := 0; i < k-1; i++ { + minScore += pairs[i] + maxScore += pairs[n-i-2] + } + + return int64(maxScore - minScore) +} diff --git a/Hard/L514.go b/Hard/L514.go new file mode 100644 index 0000000..a9ff544 --- /dev/null +++ b/Hard/L514.go @@ -0,0 +1,43 @@ +package Hard + +func findRotateSteps(ring string, key string) int { + var solve func(keyIdx, ringIdx int) int + mp := make(map[string]int) + + solve = func(keyIdx, ringIdx int) int { + if keyIdx == len(key) { + return 0 + } + + mpKey := fmt.Sprintf("%s%d", keyIdx, ringIdx) + if v, ok := mp[mpKey]; ok { + return v + } + + size, stepsReq, tmp, cnt := len(ring), 1000000000, ringIdx, 0 + + for cnt < size { + if key[keyIdx] == ring[tmp] { + stepsReq = min(stepsReq, 1+cnt+solve(keyIdx+1, tmp)) + } + cnt, tmp = cnt+1, tmp+1 + + tmp %= size + } + + cnt, tmp = 0, ringIdx + for cnt < size { + if key[keyIdx] == ring[tmp] { + stepsReq = min(stepsReq, 1+cnt+solve(keyIdx+1, tmp)) + } + cnt, tmp = cnt+1, tmp-1 + tmp += size + tmp %= size + } + + mp[mpKey] = stepsReq + return stepsReq + } + + return solve(0, 0) +} diff --git a/Hard/L664.go b/Hard/L664.go new file mode 100644 index 0000000..a94af1f --- /dev/null +++ b/Hard/L664.go @@ -0,0 +1,39 @@ +package Hard + +func strangePrinter(s string) int { + var ( + solve func(left, right int) int + ) + mp := make(map[string]int) + + solve = func(left, right int) int { + if left == right { + return 1 + } + key := fmt.Sprintf("%d-%d", left, right) + if v, ok := mp[key]; ok { + return v + } + + res := math.MaxInt32 + for k := left; k < right; k++ { + res = min(res, solve(left, k)+solve(k+1, right)) + } + + if s[left] == s[right] { + res-- + } + mp[key] = res + return mp[key] + } + + return solve(0, len(s)-1) +} + +func min(a, b int) int { + if a < b { + return a + } + + return b +} diff --git a/Hard/L68.go b/Hard/L68.go new file mode 100644 index 0000000..8b362ff --- /dev/null +++ b/Hard/L68.go @@ -0,0 +1,89 @@ +package Hard + +func fullJustify(words []string, maxWidth int) []string { + var res []string + left := 0 + + for left < len(words) { + right := findRight(words, left, maxWidth) + res = append(res, justify(words, left, right, maxWidth)) + left = right + 1 + } + + return res +} + +func findRight(words []string, left, maxWidth int) int { + right := left + sum := len(words[right]) + right++ + + for right < len(words) && (sum + 1 + len(words[right])) <= maxWidth { + sum += 1 + len(words[right]) + right++ + } + + return right - 1 +} + +func justify(words []string, left, right, maxWidth int) string { + if right - left == 0 { + return padResult(words[left], maxWidth) + } + + lastLine := isLastLine(words, right) + numSpaces := right - left + totalSpace := maxWidth - wordsLength(words, left, right) + + space, remainder := " ", 0 + if !lastLine { + space = blank(totalSpace / numSpaces) + remainder = totalSpace % numSpaces + } + + var sb strings.Builder + for i := left; i <= right; i++ { + sb.WriteString(words[i]) + sb.WriteString(space) + + if remainder > 0 { + sb.WriteString(" ") + } + remainder-- + } + + return padResult(strings.Trim(sb.String(), " "), maxWidth) +} + +func isLastLine(words []string, right int) bool { + return right == len(words) - 1 +} + +func wordsLength(words []string, left, right int) int { + wordsLen := 0 + + for i := left; i <= right; i++ { + wordsLen += len(words[i]) + } + + return wordsLen +} + +func padResult(result string, maxWidth int) string { + var sb strings.Builder + + sb.WriteString(result) + sb.WriteString(blank(maxWidth - len(result))) + + return sb.String() +} + +func blank(length int) string { + var sb strings.Builder + + for i := 0; i < length; i++ { + sb.WriteString(" ") + } + + return sb.String() +} diff --git a/Hard/L834.go b/Hard/L834.go new file mode 100644 index 0000000..288194c --- /dev/null +++ b/Hard/L834.go @@ -0,0 +1,43 @@ +package Hard + +func sumOfDistancesInTree(n int, edges [][]int) []int { + var ( + dfs1 func(node, parent int) + dfs2 func(node, parent, dpVal int) + ) + adjList, sz, val, ans := make([][]int, n), make([]int, n), make([]int, n), make([]int, n) + for i := 0; i < n; i++ { + adjList[i] = make([]int, 0) + } + + for _, edge := range edges { + adjList[edge[0]] = append(adjList[edge[0]], edge[1]) + adjList[edge[1]] = append(adjList[edge[1]], edge[0]) + } + + dfs1 = func(node, parent int) { + for _, c := range adjList[node] { + if c != parent { + dfs1(c, node) + sz[node] += sz[c] + val[node] += val[c] + sz[c] + } + } + sz[node]++ + } + + dfs2 = func(node, parent, dpVal int) { + ans[node] = val[node] + dpVal + (n - sz[node]) + + for _, c := range adjList[node] { + if c != parent { + dfs2(c, node, ans[node]-val[c]-sz[c]) + } + } + } + + dfs1(0, 0) + dfs2(0, 0, 0) + + return ans +} diff --git a/Hard/L839.go b/Hard/L839.go new file mode 100644 index 0000000..de0db9e --- /dev/null +++ b/Hard/L839.go @@ -0,0 +1,51 @@ +package Hard + +func numSimilarGroups(strs []string) int { + n := len(strs) + parent := make([]int, n) + var ( + isSimilar func(s1, s2 string) bool + find func(x int) int + ) + + isSimilar = func(s1, s2 string) bool { + diff := 0 + for i := 0; i < len(s1); i++ { + if s1[i] != s2[i] { + diff++ + } + } + + return diff == 2 || diff == 0 + } + + find = func(x int) int { + if parent[x] != x { + parent[x] = find(parent[x]) + } + return parent[x] + } + + for i := 0; i < n; i++ { + parent[i] = i + } + for i := 0; i < n; i++ { + for j := i + 1; j < n; j++ { + if isSimilar(strs[i], strs[j]) { + p1, p2 := find(i), find(j) + if p1 != p2 { + parent[p2] = p1 + } + } + } + } + + res := 0 + for i := 0; i < n; i++ { + if parent[i] == i { + res++ + } + } + + return res +} diff --git a/Hard/L87.go b/Hard/L87.go new file mode 100644 index 0000000..301a4eb --- /dev/null +++ b/Hard/L87.go @@ -0,0 +1,45 @@ +package Hard + +func isScramble(s1 string, s2 string) bool { + var solve func(a, b string) bool + mp := make(map[string]bool) + + if s1 == s2 { + return true + } + if len(s1) != len(s2) { + return false + } + if len(s1) == 0 { + return true + } + + solve = func(a, b string) bool { + if a == b { + return true + } + if len(a) <= 1 { + return false + } + + key := fmt.Sprintf("%s-%s", a, b) + if v, ok := mp[key]; ok { + return v + } + + n, check := len(a), false + for i := 1; i < n; i++ { + swap := solve(a[:i], b[n-i:]) && solve(a[i:], b[0:n-i]) + unSwap := solve(a[0:i], b[0:i]) && solve(a[i:], b[i:]) + + if swap || unSwap { + check = true + break + } + } + mp[key] = check + return mp[key] + } + + return solve(s1, s2) +} diff --git a/Hard/L879.go b/Hard/L879.go new file mode 100644 index 0000000..d403e9e --- /dev/null +++ b/Hard/L879.go @@ -0,0 +1,51 @@ +package Hard + +func profitableSchemes(n int, minProfit int, group []int, profit []int) int { + mod := int64(1000000007) + mp := make(map[string]int64) + var solve func(n, i, minimumProfit int) int64 + + solve = func(n, i, minimumProfit int) int64 { + var ( + ways int64 + zeroProfitKey = fmt.Sprintf("%d-%d-0", n, i) + key = fmt.Sprintf("%d-%d-%d", n, i, minimumProfit) + ) + + if i == len(group) { + if minimumProfit <= 0 { + return 1 + } + + return 0 + } + + if minimumProfit <= 0 { + if v, ok := mp[zeroProfitKey]; ok { + return v + } + } else if minimumProfit > 0 { + if v, ok := mp[key]; ok { + return v + } + } + + ways += solve(n, i+1, minimumProfit) + ways %= mod + + if n >= group[i] { + ways += solve(n-group[i], i+1, minimumProfit-profit[i]) + ways %= mod + } + + if minimumProfit <= 0 { + mp[zeroProfitKey] = ways % mod + } else { + mp[key] = ways % mod + } + + return ways % mod + } + + return int(solve(n, 0, minProfit)) +} diff --git a/Medium.md b/Medium.md new file mode 100644 index 0000000..b14a62e --- /dev/null +++ b/Medium.md @@ -0,0 +1,350 @@ +## Medium +|LC #|Description| +|:-:|:-| +|[931](https://leetcode.com/problems/minimum-falling-path-sum/)| Minimum Falling Path Sum| +|[946](https://leetcode.com/problems/validate-stack-sequences/)| Validate Stack Sequences| +|[29](https://leetcode.com/problems/divide-two-integers/)| Divide Two Integers| +|[820](https://leetcode.com/problems/short-encoding-of-words/)| Short Encoding of Words| +|[1381](https://leetcode.com/problems/design-a-stack-with-increment-operation/)| Design a Stack With Increment Operation| +|[623](https://leetcode.com/problems/add-one-row-to-tree/)| Add One Row to Tree| +|[12](https://leetcode.com/problems/integer-to-roman/)| Integer to Roman| +|[1315](https://leetcode.com/problems/sum-of-nodes-with-even-valued-grandparent/)| Sum of Nodes with Even-Valued Grandparent| +|[1302](https://leetcode.com/problems/deepest-leaves-sum/)| Deepest Leaves Sum| +|[322](https://leetcode.com/problems/coin-change/)| Coin Change| +|[1305](https://leetcode.com/problems/all-elements-in-two-binary-search-trees/)| All Elements in Two Binary Search Trees| +|[1461](https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/)| Check If a String Contains All Binary Codes of Size K| +|[1721](https://leetcode.com/problems/swapping-nodes-in-a-linked-list/)| Swapping Nodes in a Linked List| +|[714](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/)| Best Time to Buy and Sell Stock with Transaction Fee| +|[478](https://leetcode.com/problems/generate-random-point-in-a-circle/)| Generate Random Point in a Circle| +|[208](https://leetcode.com/problems/implement-trie-prefix-tree/)| Implement Trie (Prefix Tree)| +|[376](https://leetcode.com/problems/wiggle-subsequence/)| Wiggle Subsequence| +|[38](https://leetcode.com/problems/count-and-say/)| Count and Say| +|[146](https://leetcode.com/problems/lru-cache/)| LRU Cache| +|[1583](https://leetcode.com/problems/count-unhappy-friends/)| Count Unhappy Friends| +|[729](https://leetcode.com/problems/my-calendar-i/)| My Calendar I| +|[841](https://leetcode.com/problems/keys-and-rooms/)| Keys And Rooms| +|[113](https://leetcode.com/problems/path-sum-ii/)| Path Sum II| +|[1398](https://leetcode.com/problems/design-underground-system/)| Design Underground System| +|[1797](https://leetcode.com/problems/design-authentication-manager/)| Design Authentication Manager| +|[1798](https://leetcode.com/problems/maximum-number-of-consecutive-values-you-can-make/)| Maximum Number of Consecutive Values You Can Make| +|[966](https://leetcode.com/problems/vowel-spellchecker/)| Vowel Spellchecker| +|[1689](https://leetcode.com/problems/partitioning-into-minimum-number-of-deci-binary-numbers/)| Partitioning Into Minimum Number Of Deci-Binary Numbers| +|[1764](https://leetcode.com/problems/form-array-by-concatenating-subarrays-of-another-array/)| Form Array by Concatenating Subarrays of Another Array| +|[923](https://leetcode.com/problems/3sum-with-multiplicity/)| 3Sum With Multiplicity| +|[417](https://leetcode.com/problems/pacific-atlantic-water-flow/)| Pacific Atlantic Water Flow| +|[916](https://leetcode.com/problems/word-subsets/)| Word Subsets| +|[5](https://leetcode.com/problems/longest-palindromic-substring/)| Longest Palindromic Substring| +|[647](https://leetcode.com/problems/palindromic-substrings/)| Palindromic Substrings| +|[971](https://leetcode.com/problems/flip-binary-tree-to-match-preorder-traversal/)| Flip Binary Tree To Match Preorder Traversal| +|[1726](https://leetcode.com/problems/tuple-with-same-product/)| Tuple with Same Product| +|[474](https://leetcode.com/problems/ones-and-zeroes/)| Ones and Zeroes| +|[1488](https://leetcode.com/problems/avoid-flood-in-the-city/)| Avoid Flood in The City| +|[947](https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/)| Most Stones Removed with Same Row or Column| +|[622](https://leetcode.com/problems/design-circular-queue/)| Design Circular Queue| +|[1670](https://leetcode.com/problems/design-front-middle-back-queue/)| Design Front Middle Back Queue| +|[494](https://leetcode.com/problems/target-sum/)| Target Sum| +|[17](https://leetcode.com/problems/letter-combinations-of-a-phone-number/)| Letter Combinations of a Phone Number| +|[638](https://leetcode.com/problems/shopping-offers/)| Shopping Offers| +|[667](https://leetcode.com/problems/beautiful-arrangement-ii/)| Beautiful Arrangement II| +|[650](https://leetcode.com/problems/2-keys-keyboard/)| 2 Keys Keyboard| +|[801](https://leetcode.com/problems/minimum-swaps-to-make-sequences-increasing/)| Minimum Swaps To Make Sequences Increasing| +|[341](https://leetcode.com/problems/flatten-nested-list-iterator/)| Flatten Nested List Iterator| +|[86](https://leetcode.com/problems/partition-list/)| Partition List| +|[91](https://leetcode.com/problems/decode-ways/)| Decode Ways| +|[62](https://leetcode.com/problems/unique-paths/)| Unique Paths| +|[1209](https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/)| Remove All Adjacent Duplicates in String II| +|[279](https://leetcode.com/problems/perfect-squares/)| Perfect Squares| +|[377](https://leetcode.com/problems/combination-sum-iv/)| Combination Sum IV| +|[120](https://leetcode.com/problems/triangle/)| Triangle| +|[554](https://leetcode.com/problems/brick-wall/)| Brick Wall| +|[48](https://leetcode.com/problems/rotate-image/)| Rotate Image| +|[935](https://leetcode.com/problems/knight-dialer/)| Knight Dialer| +|[740](https://leetcode.com/problems/delete-and-earn/)| Delete and Earn| +|[63](https://leetcode.com/problems/unique-paths-ii/)| Unique Paths II| +|[34](https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/)| Find First and Last Position of Element in Sorted Array| +|[970](https://leetcode.com/problems/powerful-integers/)| Powerful Integers| +|[665](https://leetcode.com/problems/non-decreasing-array/)| Non-decreasing Array| +|[1472](https://leetcode.com/problems/design-browser-history/)| Design Browser History| +|[109](https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/)| Convert Sorted List to Binary Search Tree| +|[583](https://leetcode.com/problems/delete-operation-for-two-strings/)| Delete Operation for Two Strings| +|[1423](https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/)| Maximum Points You Can Obtain from Cards| +|[304](https://leetcode.com/problems/range-sum-query-2d-immutable/)| Range Sum Query 2D - Immutable| +|[816](https://leetcode.com/problems/ambiguous-coordinates/)| Ambiguous Coordinates| +|[114](https://leetcode.com/problems/flatten-binary-tree-to-linked-list/)| Flatten Binary Tree to Linked List| +|[1048](https://leetcode.com/problems/longest-string-chain/)| Longest String Chain| +|[213](https://leetcode.com/problems/house-robber-ii/)| House Robber II| +|[462](https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/)| Minimum Moves to Equal Array Elements II| +|[890](https://leetcode.com/problems/find-and-replace-pattern/)| Find and Replace Pattern| +|[337](https://leetcode.com/problems/house-robber-iii/)| House Robber III| +|[921](https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/)| Minimum Add to Make Parentheses Valid| +|[1871](https://leetcode.com/problems/jump-game-vii/)| Jump Game VII| +|[150](https://leetcode.com/problems/evaluate-reverse-polish-notation/)| Evaluate Reverse Polish Notation| +|[318](https://leetcode.com/problems/maximum-product-of-word-lengths/)| Maximum Product of Word Lengths| +|[1695](https://leetcode.com/problems/maximum-erasure-value/)| Maximum Erasure Value| +|[1268](https://leetcode.com/problems/search-suggestions-system/)| Search Suggestions System| +|[695](https://leetcode.com/problems/max-area-of-island/)| Max Area of Island| +|[97](https://leetcode.com/problems/interleaving-string/)| Interleaving String| +|[1465](https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/)| Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts| +|[128](https://leetcode.com/problems/longest-consecutive-sequence/)| Longest Consecutive Sequence| +|[105](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/)| Construct Binary Tree from Preorder and Inorder Traversal| +|[1696](https://leetcode.com/problems/jump-game-vi/)| Jump Game VI| +|[698](https://leetcode.com/problems/partition-to-k-equal-sum-subsets/)| Partition to K Equal Sum Subsets| +|[22](https://leetcode.com/problems/generate-parentheses/)| Generate Parentheses| +|[795](https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/)| Number of Subarrays with Bounded Maximum| +|[118](https://leetcode.com/problems/pascals-triangle/)| Pascal's Triangle| +|[576](https://leetcode.com/problems/out-of-boundary-paths/)| Out of Boundary Paths| +|[684](https://leetcode.com/problems/redundant-connection/)| Redundant Connection| +|[1004](https://leetcode.com/problems/max-consecutive-ones-iii/)| Max Consecutive Ones III| +|[236](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/)| Lowest Common Ancestor of a Binary Tree| +|[89](https://leetcode.com/problems/gray-code/)| Gray Code| +|[378](https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/)| Kth Smallest Element in a Sorted Matrix| +|[718](https://leetcode.com/problems/maximum-length-of-repeated-subarray/)| Maximum Length of Repeated Subarray| +|[300](https://leetcode.com/problems/longest-increasing-subsequence/)| Longest Increasing Subsequence| +|[162](https://leetcode.com/problems/find-peak-element/)| Find Peak Element| +|[791](https://leetcode.com/problems/custom-sort-string/)| Custom Sort String| +|[611](https://leetcode.com/problems/valid-triangle-number/)| Valid Triangle Number| +|[235](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/)| Lowest Common Ancestor of a Binary Search Tree| +|[838](https://leetcode.com/problems/push-dominoes/)| Push Dominoes| +|[915](https://leetcode.com/problems/partition-array-into-disjoint-intervals/)| Partition Array into Disjoint Intervals| +|[814](https://leetcode.com/problems/binary-tree-pruning/)| Binary Tree Pruning| +|[90](https://leetcode.com/problems/subsets-ii/)| Subsets II| +|[877](https://leetcode.com/problems/stone-game/)| Stone Game| +|[429](https://leetcode.com/problems/n-ary-tree-level-order-traversal/)| N-ary Tree Level Order Traversal| +|[926](https://leetcode.com/problems/flip-string-to-monotone-increasing/)| Flip String to Monotone Increasing| +|[954](https://leetcode.com/problems/array-of-doubled-pairs/)| Array of Doubled Pairs| +|[49](https://leetcode.com/problems/group-anagrams/)| Group Anagrams| +|[73](https://leetcode.com/problems/set-matrix-zeroes/)| Set Matrix Zeroes| +|[1448](https://leetcode.com/problems/count-good-nodes-in-binary-tree/)| Count Good Nodes in Binary Tree| +|[36](https://leetcode.com/problems/valid-sudoku/)| Valid Sudoku| +|[153](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/)| Find Minimum in Rotated Sorted Array| +|[565](https://leetcode.com/problems/array-nesting/)| Array Nesting| +|[848](https://leetcode.com/problems/shifting-letters/)| Shifting Letters| +|[978](https://leetcode.com/problems/longest-turbulent-subarray/)| Longest Turbulent Subarray| +|[54](https://leetcode.com/problems/spiral-matrix/)| Spiral Matrix| +|[1239](https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/)| Maximum Length of a Concatenated String with Unique Characters| +|[725](https://leetcode.com/problems/split-linked-list-in-parts/)| Split Linked List in Parts| +|[473](https://leetcode.com/problems/matchsticks-to-square/)| Matchsticks to Square| +|[1143](https://leetcode.com/problems/longest-common-subsequence/)| Longest Common Subsequence| +|[55](https://leetcode.com/problems/jump-game/)| Jump Game| +|[442](https://leetcode.com/problems/find-all-duplicates-in-an-array/)| Find All Duplicates in an Array| +|[79](https://leetcode.com/problems/word-search/)| Word Search| +|[201](https://leetcode.com/problems/bitwise-and-of-numbers-range/)| Bitwise AND of Numbers Range| +|[1008](https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/)| Construct Binary Search Tree from Preorder Traversal| +|[309](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/)| Best Time to Buy and Sell Stock with Cooldown| +|[437](https://leetcode.com/problems/path-sum-iii/)| Path Sum III| +|[4511](https://leetcode.com/problems/sort-characters-by-frequency/)| Sort Characters By Frequency| +|[222](https://leetcode.com/problems/count-complete-tree-nodes/)| Count Complete Tree Nodes| +|[75](https://leetcode.com/problems/sort-colors/)| Sort Colors| +|[15](https://leetcode.com/problems/3sum/)| 3Sum| +|[994](https://leetcode.com/problems/rotting-oranges/)| Rotting Oranges| +|[430](https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/)| Flatten a Multilevel Doubly Linked List| +|[130](https://leetcode.com/problems/surrounded-regions/)| Surrounded Regions| +|[129](https://leetcode.com/problems/sum-root-to-leaf-numbers/)| Sum Root to Leaf Numbers| +|[260](https://leetcode.com/problems/single-number-iii/)| Single Number III| +|[43](https://leetcode.com/problems/multiply-strings/)| Multiply Strings| +|[96](https://leetcode.com/problems/unique-binary-search-trees/)| Unique Binary Search Trees| +|[122](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/)| Best Time to Buy and Sell Stock II| +|[739](https://leetcode.com/problems/daily-temperatures/)| Daily Temperatures| +|[368](https://leetcode.com/problems/largest-divisible-subset/)| Largest Divisible Subset| +|[540](https://leetcode.com/problems/single-element-in-a-sorted-array/)| Single Element in a Sorted Array| +|[106](https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/)| Construct Binary Tree from Inorder and Postorder Traversal| +|[450](https://leetcode.com/problems/delete-node-in-a-bst/)| Delete Node in a BST| +|[986](https://leetcode.com/problems/interval-list-intersections/)| Interval List Intersections| +|[238](https://leetcode.com/problems/product-of-array-except-self/)| Product of Array Except Self| +|[797](https://leetcode.com/problems/all-paths-from-source-to-target/)| All Paths From Source to Target| +|[721](https://leetcode.com/problems/accounts-merge/)| Accounts Merge| +|[198](https://leetcode.com/problems/house-robber/)| House Robber| +|[328](https://leetcode.com/problems/odd-even-linked-list/)| Odd Even Linked List| +|[152](https://leetcode.com/problems/maximum-product-subarray/)| Maximum Product Subarray| +|[1306](https://leetcode.com/problems/jump-game-iii/)| Jump Game III| +|[790](https://leetcode.com/problems/domino-and-tromino-tiling/)| Domino and Tromino Tiling| +|[416](https://leetcode.com/problems/partition-equal-subset-sum/)| Partition Equal Subset Sum| +|[310](https://leetcode.com/problems/minimum-height-trees/)| Minimum Height Trees| +|[221](https://leetcode.com/problems/maximal-square/)| Maximal Square| +|[394](https://leetcode.com/problems/decode-string/)| Decode String| +|[143](https://leetcode.com/problems/reorder-list/)| Reorder List| +|[210](https://leetcode.com/problems/course-schedule-ii/)| Course Schedule II| +|[56](https://leetcode.com/problems/merge-intervals/)| Merge Intervals| +|[227](https://leetcode.com/problems/basic-calculator-ii/)| Basic Calculator II| +|[973](https://leetcode.com/problems/k-closest-points-to-origin/)| K Closest Points to Origin| +|[116](https://leetcode.com/problems/populating-next-right-pointers-in-each-node/)| Populating Next Right Pointers in Each Node| +|[1015](https://leetcode.com/problems/smallest-integer-divisible-by-k/)| Smallest Integer Divisible by K| +|[1026](https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/)| Maximum Difference Between Node and Ancestor| +|[1010](https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/)| Pairs of Songs With Total Durations Divisible by 60| +|[131](https://leetcode.com/problems/palindrome-partitioning/)| Palindrome Partitioning| +|[382](https://leetcode.com/problems/linked-list-random-node/)| Linked List Random Node| +|[1041](https://leetcode.com/problems/robot-bounded-in-circle/)| Robot Bounded In Circle| +|[701](https://leetcode.com/problems/insert-into-a-binary-search-tree/)| Insert into a Binary Search Tree| +|[452](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/)| Minimum Number of Arrows to Burst Balloons| +|[8](https://leetcode.com/problems/string-to-integer-atoi/)| String to Integer (atoi)| +|[849](https://leetcode.com/problems/maximize-distance-to-closest-person/)| Maximize Distance to Closest Person| +|[142](https://leetcode.com/problems/linked-list-cycle-ii/)| Linked List Cycle II| +|[875](https://leetcode.com/problems/koko-eating-bananas/)| Koko Eating Bananas| +|[134](https://leetcode.com/problems/gas-station/)| Gas Station| +|[1291](https://leetcode.com/problems/sequential-digits/)| Sequential Digits| +|[421](https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/)| Maximum XOR of Two Numbers in an Array| +|[211](https://leetcode.com/problems/design-add-and-search-words-data-structure/)| Design Add and Search Words Data Structure| +|[438](https://leetcode.com/problems/find-all-anagrams-in-a-string/)| Find All Anagrams in a String| +|[454](https://leetcode.com/problems/4sum-ii/)| 4Sum II| +|[525](https://leetcode.com/problems/contiguous-array/)| Contiguous Array| +|[80](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/)| Remove Duplicates from Sorted Array II| +|[532](https://leetcode.com/problems/k-diff-pairs-in-an-array/)| K-diff Pairs in an Array| +|[560](https://leetcode.com/problems/subarray-sum-equals-k/)| Subarray Sum Equals K| +|[567](https://leetcode.com/problems/permutation-in-string/)| Permutation in String| +|[78](https://leetcode.com/problems/subsets/)| Subsets| +|[39](https://leetcode.com/problems/combination-sum/)| Combination Sum| +|[402](https://leetcode.com/problems/remove-k-digits/)| Remove K Digits| +|[133](https://leetcode.com/problems/clone-graph/)| Clone Graph| +|[148](https://leetcode.com/problems/sort-list/)| Sort List| +|[662](https://leetcode.com/problems/maximum-width-of-binary-tree/)| Maximum Width of Binary Tree| +|[413](https://leetcode.com/problems/arithmetic-slices/)| Arithmetic Slices| +|[799](https://leetcode.com/problems/champagne-tower/)| Champagne Tower| +|[82](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/)| Remove Duplicates from Sorted List II| +|[61](https://leetcode.com/problems/rotate-list/)| Rotate List| +|[138](https://leetcode.com/problems/copy-list-with-random-pointer/)| Copy List with Random Pointer| +|[71](https://leetcode.com/problems/simplify-path/)| Simplify Path| +|[1249](https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/)| Minimum Remove to Make Valid Parentheses| +|[856](https://leetcode.com/problems/score-of-parentheses/)| Score of Parentheses| +|[316](https://leetcode.com/problems/remove-duplicate-letters/)| Remove Duplicate Letters| +|[763](https://leetcode.com/problems/partition-labels/)| Partition Labels| +|[1663](https://leetcode.com/problems/smallest-string-with-a-given-numeric-value/)| Smallest String With A Given Numeric Value| +|[991](https://leetcode.com/problems/broken-calculator/)| Broken Calculator| +|[881](https://leetcode.com/problems/boats-to-save-people/)| Boats to Save People| +|[1024](https://leetcode.com/problems/two-city-scheduling/)| Two City Scheduling| +|[81](https://leetcode.com/problems/search-in-rotated-sorted-array-ii/)| Search in Rotated Sorted Array II| +|[287](https://leetcode.com/problems/find-the-duplicate-number/)| Find the Duplicate Number| +|[74](https://leetcode.com/problems/search-a-2d-matrix/)| Search a 2D Matrix| +|[11](https://leetcode.com/problems/container-with-most-water/)| Container With Most Water| +|[538](https://leetcode.com/problems/convert-bst-to-greater-tree/)| Convert BST to Greater Tree| +|[230](https://leetcode.com/problems/kth-smallest-element-in-a-bst/)| Kth Smallest Element in a BST| +|[284](https://leetcode.com/problems/peeking-iterator/)| Peeking Iterator| +|[216](https://leetcode.com/problems/combination-sum-iii/)| Combination Sum III| +|[47](https://leetcode.com/problems/permutations-ii/)| Permutations II| +|[117](https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/)| Populating Next Right Pointers in Each Node II| +|[743](https://leetcode.com/problems/network-delay-time/)| Network Delay Time| +|[474](https://leetcode.com/problems/ones-and-zeroes/)| Ones and Zeroes| +|[167](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/)| Two Sum II - Input Array Is Sorted| +|[3](https://leetcode.com/problems/longest-substring-without-repeating-characters/)| Longest Substring Without Repeating Characters| +|[1658](https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/)| Minimum Operations to Reduce X to Zero| +|[215](https://leetcode.com/problems/kth-largest-element-in-an-array/)| Kth Largest Element in an Array| +|[1570](https://leetcode.com/problems/dot-product-of-two-sparse-vectors/)| Dot Product of Two Sparse Vectors| +|[199](https://leetcode.com/problems/binary-tree-right-side-view/)| Binary Tree Right Side View| +|[92](https://leetcode.com/problems/reverse-linked-list-ii/)| Reverse Linked List II| +|[307](https://leetcode.com/problems/range-sum-query-mutable/)| Range Sum Query - Mutable| +|[240](https://leetcode.com/problems/search-a-2d-matrix-ii/)| Search a 2D Matrix II| +|[1457](https://leetcode.com/problems/pseudo-palindromic-paths-in-a-binary-tree/)| Pseudo-Palindromic Paths in a Binary Tree| +|[1770](https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/)| Maximum Score from Performing Multiplication Operations| +|[985](https://leetcode.com/problems/sum-of-even-numbers-after-queries/)| Sum of Even Numbers After Queries| +|[1680](https://leetcode.com/problems/concatenation-of-consecutive-binary-numbers/)| Concatenation of Consecutive Binary Numbers| +|[990](https://leetcode.com/problems/satisfiability-of-equality-equations/)| Satisfiability of Equality Equations| +|[658](https://leetcode.com/problems/find-k-closest-elements/description/)| Find K Closest Elements| +|[1578](https://leetcode.com/problems/minimum-time-to-make-rope-colorful/description/)| Minimum Time to Make Rope Colorful| +|[16](https://leetcode.com/problems/3sum-closest/description/)| 3Sum Closest| +|[334](https://leetcode.com/problems/increasing-triplet-subsequence/)| Increasing Triplet Subsequence| +|[2095](https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/)| Delete the Middle Node of a Linked List| +|[1662](https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/)| Check If Two String Arrays are Equivalent| +|[523](https://leetcode.com/problems/continuous-subarray-sum/)| Continuous Subarray Sum| +|[835](https://leetcode.com/problems/image-overlap/)| Image Overlap| +|[433](https://leetcode.com/problems/minimum-genetic-mutation/)| Minimum Genetic Mutation| +|[1926](https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/)| Nearest Exit from Entrance in Maze| +|[2225](https://leetcode.com/problems/find-players-with-zero-or-one-losses/)| Find Players With Zero or One Losses| +|[380](https://leetcode.com/problems/insert-delete-getrandom-o1/)| Insert Delete GetRandom O(1)| +|[1207](https://leetcode.com/problems/unique-number-of-occurrences/)| Unique Number of Occurrences| +|[45](https://leetcode.com/problems/jump-game-ii/)| Jump Game II| +|[1014](https://leetcode.com/problems/best-sightseeing-pair/)| Best Sightseeing Pair| +|[886](https://leetcode.com/problems/possible-bipartition/)| Possible Bipartition| +|[2279](https://leetcode.com/problems/maximum-bags-with-full-capacity-of-rocks/)| Maximum Bags With Full Capacity of Rocks| +|[343](https://leetcode.com/problems/integer-break/)| Integer Break| +|[256](https://leetcode.com/problems/paint-house/)| Paint House| +|[487](https://leetcode.com/problems/max-consecutive-ones-ii/)| Max Consecutive Ones II| +|[1746](https://leetcode.com/problems/maximum-subarray-sum-after-one-operation/)| Maximum Subarray Sum After One Operation| +|[1230](https://leetcode.com/problems/toss-strange-coins/)| Toss Strange Coins| +|[2498](https://leetcode.com/problems/frog-jump-ii/)| Frog Jump II| +|[2244](https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/)| Minimum Rounds to Complete All Tasks| +|[1749](https://leetcode.com/problems/maximum-absolute-sum-of-any-subarray/)| Maximum Absolute Sum of Any Subarray| +|[2186](https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram-ii/)| Minimum Number of Steps to Make Two Strings Anagram II| +|[2414](https://leetcode.com/problems/length-of-the-longest-alphabetical-continuous-substring/)| Length of the Longest Alphabetical Continuous Substring| +|[1519](https://leetcode.com/problems/number-of-nodes-in-the-sub-tree-with-the-same-label/)| Number of Nodes in the Sub-Tree With the Same Label| +|[1061](https://leetcode.com/problems/lexicographically-smallest-equivalent-string/)| Lexicographically Smallest Equivalent String| +|[1314](https://leetcode.com/problems/matrix-block-sum/)| Matrix Block Sum| +|[57](https://leetcode.com/problems/insert-interval/)| Insert Interval| +|[974](https://leetcode.com/problems/subarray-sums-divisible-by-k/)| Subarray Sums Divisible by K| +|[491](https://leetcode.com/problems/non-decreasing-subsequences/)| Non-decreasing Subsequences| +|[2359](https://leetcode.com/problems/find-closest-node-to-given-two-nodes/)| Find Closest Node to Given Two Nodes| +|[909](https://leetcode.com/problems/snakes-and-ladders/)| Snakes and Ladders| +|[787](https://leetcode.com/problems/cheapest-flights-within-k-stops/)| Cheapest Flights Within K Stops| +|[6](https://leetcode.com/problems/zigzag-conversion/)| Zigzag Conversion| +|[904](https://leetcode.com/problems/fruit-into-baskets/)| Fruit Into Baskets| +|[1162](https://leetcode.com/problems/as-far-from-land-as-possible/)| As Far from Land as Possible| +|[2477](https://leetcode.com/problems/minimum-fuel-cost-to-report-to-the-capital/)| Minimum Fuel Cost to Report to the Capital| +|[1129](https://leetcode.com/problems/shortest-path-with-alternating-colors/)| Shortest Path with Alternating Colors| +|[103](https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/)| Binary Tree Zigzag Level Order Traversal| +|[1011](https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/)| Capacity To Ship Packages Within D Days| +|[427](https://leetcode.com/problems/construct-quad-tree/)| Construct Quad Tree| +|[652](https://leetcode.com/problems/find-duplicate-subtrees/)| Find Duplicate Subtrees| +|[443](https://leetcode.com/problems/string-compression/)| String Compression| +|[2187](https://leetcode.com/problems/minimum-time-to-complete-trips/)| Minimum Time to Complete Trips| +|[958](https://leetcode.com/problems/check-completeness-of-a-binary-tree/)| Check Completeness of a Binary Tree| +|[2492](https://leetcode.com/problems/minimum-score-of-a-path-between-two-cities/)| Minimum Score of a Path Between Two Cities| +|[1466](https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/)| Reorder Routes to Make All Paths Lead to the City Zero| +|[2316](https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph/)| Count Unreachable Pairs of Nodes in an Undirected Graph| +|[2405](https://leetcode.com/problems/optimal-partition-of-string/)| Optimal Partition of String| +|[2300](https://leetcode.com/problems/successful-pairs-of-spells-and-potions/)| Successful Pairs of Spells and Potions| +|[2439](https://leetcode.com/problems/minimize-maximum-of-array/)| Minimize Maximum of Array| +|[516](https://leetcode.com/problems/longest-palindromic-subsequence/)| Longest Palindromic Subsequence| +|[319](https://leetcode.com/problems/bulb-switcher/)| Bulb Switcher| +|[649](https://leetcode.com/problems/dota2-senate/)| Dota2 Senate| +|[934](https://leetcode.com/problems/shortest-bridge/)| Shortest Bridge| +|[1318](https://leetcode.com/problems/minimum-flips-to-make-a-or-b-equal-to-c/)| Minimum Flips to Make a OR b Equal to c| +|[2352](https://leetcode.com/problems/equal-row-and-column-pairs/)| Equal Row and Column Pairs| +|[863](https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/)| All Nodes Distance K in Binary Tree| +|[207](https://leetcode.com/problems/course-schedule/)| Course Schedule| +|[1218](https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/)| Longest Arithmetic Subsequence of Given Difference| +|[735](https://leetcode.com/problems/asteroid-collision/)| Asteroid Collision| +|[673](https://leetcode.com/problems/number-of-longest-increasing-subsequence/)| Number of Longest Increasing Subsequence| +|[688](https://leetcode.com/problems/knight-probability-in-chessboard/)| Knight Probability in Chessboard| +|[852](https://leetcode.com/problems/peak-index-in-a-mountain-array/)| Peak Index in a Mountain Array| +|[852](https://leetcode.com/problems/minimum-speed-to-arrive-on-time/)| Minimum Speed to Arrive on Time| +|[486](https://leetcode.com/problems/predict-the-winner/)| Predict the Winner| +|[808](https://leetcode.com/problems/soup-servings/)| Soup Servings| +|[712](https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/)| Minimum ASCII Delete Sum for Two Strings| +|[77](https://leetcode.com/problems/combinations/)| Combinations| +|[46](https://leetcode.com/problems/permutations/)| Permutations| +|[33](https://leetcode.com/problems/search-in-rotated-sorted-array/)| Search in Rotated Sorted Array| +|[542](https://leetcode.com/problems/01-matrix/)| 01 Matrix| +|[1615](https://leetcode.com/problems/maximal-network-rank/)| Maximal Network Rank| +|[767](https://leetcode.com/problems/reorganize-string/)| Reorganize String| +|[1424](https://leetcode.com/problems/diagonal-traverse-ii/)| Diagonal Traverse II| +|[1814](https://leetcode.com/problems/count-nice-pairs-in-an-array/)| Count Nice Pairs in an Array| +|[1561](https://leetcode.com/problems/maximum-number-of-coins-you-can-get/)| Maximum Number of Coins You Can Get| +|[1630](https://leetcode.com/problems/arithmetic-subarrays/)| Arithmetic Subarrays| +|[1685](https://leetcode.com/problems/sum-of-absolute-differences-in-a-sorted-array/)| Sum of Absolute Differences in a Sorted Array| +|[1727](https://leetcode.com/problems/largest-submatrix-with-rearrangements/)| Largest Submatrix With Rearrangements| +|[2849](https://leetcode.com/problems/determine-if-a-cell-is-reachable-at-a-given-time/)| Determine if a Cell Is Reachable at a Given Time| +|[2842](https://leetcode.com/problems/difference-between-ones-and-zeros-in-row-and-column/)| Difference Between Ones and Zeroes in Row and Column| +|[2038](https://leetcode.com/problems/remove-colored-pieces-if-both-neighbors-are-the-same-color/)| Remove Colored Pieces if Both Neighbors are the Same Color | +|[1637](https://leetcode.com/problems/widest-vertical-area-between-two-points-containing-no-points/)| Widest Vertical Area Between Two Points Containing No Points | +|[2610](https://leetcode.com/problems/convert-an-array-into-a-2d-array-with-conditions/)| Convert an Array Into a 2D Array With Conditions | +|[907](https://leetcode.com/problems/sum-of-subarray-minimums/)| Sum of Subarray Minimums | +|[2125](https://leetcode.com/problems/number-of-laser-beams-in-a-bank/)| Number of Laser Beams in a Bank | +|[2870](https://leetcode.com/problems/minimum-number-of-operations-to-make-array-empty/)| Minimum Number of Operations to Make Array Empty | +|[2385](https://leetcode.com/problems/amount-of-time-for-binary-tree-to-be-infected/)| Amount of Time for Binary Tree to Be Infected | +|[1347](https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram/)| Minimum Number of Steps to Make Two Strings Anagram | +|[1657](https://leetcode.com/problems/determine-if-two-strings-are-close/)| Determine if Two Strings Are Close | +|[2966](https://leetcode.com/problems/divide-array-into-arrays-with-max-difference/)| Divide Array Into Arrays With Max Difference | +|[988](https://leetcode.com/problems/smallest-string-starting-from-leaf/)| Smallest String Starting From Leaf | +|[200](https://leetcode.com/problems/number-of-islands/)| Number of Islands | +|[1992](https://leetcode.com/problems/find-all-groups-of-farmland/)| Find All Groups of Farmland | +|[752](https://leetcode.com/problems/open-the-lock/)| Open the Lock | +|[2997](https://leetcode.com/problems/minimum-number-of-operations-to-make-array-xor-equal-to-k/)| Minimum Number of Operations to Make Array XOR Equal to K | +|[1915](https://leetcode.com/problems/number-of-wonderful-substrings/)| Number of Wonderful Substrings | +|[165](https://leetcode.com/problems/compare-version-numbers/)| Compare Version Numbers | +|[1492](https://leetcode.com/problems/the-kth-factor-of-n/)| The kth Factor of n | +|[861](https://leetcode.com/problems/score-after-flipping-matrix/)| Score After Flipping Matrix | +|[1219](https://leetcode.com/problems/path-with-maximum-gold/)| Path with Maximum Gold | +|[1325](https://leetcode.com/problems/delete-leaves-with-a-given-value/)| Delete Leaves With a Given Value | +|[1382](https://leetcode.com/problems/balance-a-binary-search-tree/)| Balance a Binary Search Tree | +|[2390](https://leetcode.com/problems/removing-stars-from-a-string/)| Removing Stars From a String | +|[1834](https://leetcode.com/problems/single-threaded-cpu/)| Single-Threaded CPU | +|[2](https://leetcode.com/problems/add-two-numbers/)| Add Two Numbers | +|[874](https://leetcode.com/problems/walking-robot-simulation/)| Walking Robot Simulation | diff --git a/Medium/L1011.go b/Medium/L1011.go new file mode 100644 index 0000000..054e35d --- /dev/null +++ b/Medium/L1011.go @@ -0,0 +1,54 @@ +package Medium + +func shipWithinDays(weights []int, days int) int { + if len(weights) == 0 { + return 0 + } + + maxi, sum := math.MinInt32, 0 + for _, w := range weights { + maxi = max(maxi, w) + sum += w + } + + if days == 1 { + return sum + } + + isFeasible := func(maxWeight int) bool { + cnt, maximum, day := 0, maxWeight, 0 + for _, w := range weights { + if w <= maximum { + cnt++ + } else { + cnt = 0 + maximum = maxWeight + day++ + } + maximum -= w + } + + return day+1 <= days + } + + low, high := maxi, sum + for low < high { + mid := low + (high-low)/2 + + if isFeasible(mid) { + high = mid + } else { + low = mid + 1 + } + } + + return low +} + +func max(a, b int) int { + if a > b { + return a + } + + return b +} diff --git a/Medium/L103.go b/Medium/L103.go new file mode 100644 index 0000000..5df5925 --- /dev/null +++ b/Medium/L103.go @@ -0,0 +1,46 @@ +package Medium + +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func zigzagLevelOrder(root *TreeNode) [][]int { + var res [][]int + if root == nil { + return res + } + + var q []*TreeNode + q = append(q, root) + normalOrder := false + + for len(q) > 0 { + size := len(q) + var lvlVals []int + normalOrder = !normalOrder + for i := 0; i < size; i++ { + cur := q[0] + q = q[1:] + + if normalOrder { + lvlVals = append(lvlVals, cur.Val) + } else { + lvlVals = append([]int{cur.Val}, lvlVals...) + } + + if cur.Left != nil { + q = append(q, cur.Left) + } + if cur.Right != nil { + q = append(q, cur.Right) + } + } + res = append(res, lvlVals) + } + + return res +} diff --git a/Medium/L1143.go b/Medium/L1143.go index f49c154..58589cd 100644 --- a/Medium/L1143.go +++ b/Medium/L1143.go @@ -1,40 +1,30 @@ package Medium func longestCommonSubsequence(text1 string, text2 string) int { + var ( + solve func(m, n int) int + ) m, n := len(text1), len(text2) - memo := make([][]int, m+1) - for i := 0; i < m+1; i++ { - memo[i] = make([]int, n+1) - for j := 0; j < n+1; j++ { - memo[i][j] = -1 - } - } - - return lcs(text1, text2, m, n, &memo) -} - -func lcs(s1, s2 string, m, n int, memo *[][]int) int { - if m == 0 || n == 0 { - return 0 - } + mp := make(map[string]int) - if (*memo)[m][n] != -1 { - return (*memo)[m][n] - } + solve = func(m, n int) int { + if m == 0 || n == 0 { + return 0 + } - if s1[m-1] == s2[n-1] { - (*memo)[m][n] = 1 + lcs(s1, s2, m-1, n-1, memo) - } else { - (*memo)[m][n] = max(lcs(s1, s2, m-1, n, memo), lcs(s1, s2, m, n-1, memo)) - } + key := fmt.Sprintf("%d#%d", m, n) + if v, ok := mp[key]; ok { + return v + } - return (*memo)[m][n] -} + if text1[m-1] == text2[n-1] { + mp[key] = 1 + solve(m-1, n-1) + } else { + mp[key] = max(solve(m-1, n), solve(m, n-1)) + } -func max(a, b int) int { - if a > b { - return a + return mp[key] } - return b + return solve(m, n) } diff --git a/Medium/L1161.go b/Medium/L1161.go new file mode 100644 index 0000000..d8f524c --- /dev/null +++ b/Medium/L1161.go @@ -0,0 +1,32 @@ +package Medium + +func maxLevelSum(root *TreeNode) int { + var q []*TreeNode + maximum, maxLevel, lvl := math.MinInt32, -1, 1 + + q = append(q, root) + for len(q) > 0 { + size := len(q) + sum := 0 + for i := 0; i < size; i++ { + node := q[0] + q = q[1:] + + sum += node.Val + + if node.Left != nil { + q = append(q, node.Left) + } + if node.Right != nil { + q = append(q, node.Right) + } + } + if sum > maximum { + maximum = sum + maxLevel = lvl + } + lvl++ + } + + return maxLevel +} diff --git a/Medium/L1218.go b/Medium/L1218.go new file mode 100644 index 0000000..5dcd61e --- /dev/null +++ b/Medium/L1218.go @@ -0,0 +1,25 @@ +package Medium + +func longestSubsequence(arr []int, difference int) int { + mp, ans := make(map[int]int), 0 + + for i := range arr { + if v, ok := mp[arr[i]-difference]; ok { + ans = max(ans, v+1) + mp[arr[i]] = v + 1 + } else { + ans = max(ans, 1) + mp[arr[i]] = 1 + } + } + + return ans +} + +func max(a, b int) int { + if a > b { + return a + } + + return b +} diff --git a/Medium/L1219.go b/Medium/L1219.go new file mode 100644 index 0000000..476733c --- /dev/null +++ b/Medium/L1219.go @@ -0,0 +1,40 @@ +package Medium + +func getMaximumGold(grid [][]int) int { + var ( + isValid func(x, y int) bool + solve func(x, y int) int + ) + m, n, res := len(grid), len(grid[0]), 0 + dirs := [][]int{{0, 1}, {1, 0}, {0, -1}, {-1, 0}} + + isValid = func(x, y int) bool { + return x >= 0 && x < m && y >= 0 && y < n && grid[x][y] != 0 + } + + solve = func(x, y int) int { + if !isValid(x, y) { + return 0 + } + + curr := grid[x][y] + grid[x][y] = 0 + maxGold := 0 + for _, d := range dirs { + maxGold = max(maxGold, solve(x+d[0], y+d[1])) + } + + grid[x][y] = curr + return curr + maxGold + } + + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if grid[i][j] != 0 { + res = max(res, solve(i, j)) + } + } + } + + return res +} diff --git a/Medium/L1318.go b/Medium/L1318.go new file mode 100644 index 0000000..316bb49 --- /dev/null +++ b/Medium/L1318.go @@ -0,0 +1,18 @@ +package Medium + +func minFlips(a int, b int, c int) int { + flips := 0 + for a > 0 || b > 0 || c > 0 { + bitA, bitB, bitC := a&1, b&1, c&1 + + if bitC == 0 { + flips += bitA + bitB + } else if bitA == 0 && bitB == 0 { + flips++ + } + + a, b, c = a>>1, b>>1, c>>1 + } + + return flips +} diff --git a/Medium/L1325.go b/Medium/L1325.go new file mode 100644 index 0000000..bf87c90 --- /dev/null +++ b/Medium/L1325.go @@ -0,0 +1,24 @@ +package Medium + +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func removeLeafNodes(root *TreeNode, target int) *TreeNode { + if root.Left != nil { + root.Left = removeLeafNodes(root.Left, target) + } + if root.Right != nil { + root.Right = removeLeafNodes(root.Right, target) + } + + if root.Left == root.Right && root.Val == target { + return nil + } + + return root +} diff --git a/Medium/L1347.go b/Medium/L1347.go new file mode 100644 index 0000000..22ba933 --- /dev/null +++ b/Medium/L1347.go @@ -0,0 +1,19 @@ +package Medium + +func minSteps(s string, t string) int { + cnt := make([]int, 26) + + for i := 0; i < len(s); i++ { + cnt[s[i]-'a']++ + cnt[t[i]-'a']-- + } + + steps := 0 + for _, count := range cnt { + if count > 0 { + steps += count + } + } + + return steps +} diff --git a/Medium/L1382.go b/Medium/L1382.go new file mode 100644 index 0000000..e320fd9 --- /dev/null +++ b/Medium/L1382.go @@ -0,0 +1,32 @@ +package Medium + +func balanceBST(root *TreeNode) *TreeNode { + var ( + sortedLst []*TreeNode + inorder func(node *TreeNode) + createTree func(start, end int) *TreeNode + ) + + inorder = func(node *TreeNode) { + if node == nil { + return + } + inorder(node.Left) + sortedLst = append(sortedLst, node) + inorder(node.Right) + } + + createTree = func(start, end int) *TreeNode { + if start > end { + return nil + } + mid := start + (end-start)/2 + newRoot := sortedLst[mid] + newRoot.Left = createTree(start, mid - 1) + newRoot.Right = createTree(mid + 1, end) + return newRoot + } + + inorder(root) + return createTree(0, len(sortedLst) - 1) +} diff --git a/Medium/L1424.go b/Medium/L1424.go new file mode 100644 index 0000000..179bb83 --- /dev/null +++ b/Medium/L1424.go @@ -0,0 +1,46 @@ +package Medium + +func findDiagonalOrder(nums [][]int) []int { + size, mp := 0, make(map[int][]int) + for i := 0; i < len(nums); i++ { + numList := make([]int, len(nums[i])) + copy(numList, nums[i]) + for j := 0; j < len(numList); j++ { + var lst []int + index := i + j + if _, ok := mp[index]; ok { + lst = mp[index] + } + lst = append([]int{numList[j]}, lst...) + mp[index] = lst + size++ + } + } + + maxLen := getMaxLen(mp) + var resultList []int + for i := 0; i <= maxLen; i++ { + diagVal := mp[i] + resultList = append(resultList, diagVal...) + } + + return resultList +} + +func getMaxLen(mp map[int][]int) int { + maxLen := math.MinInt32 + + for k, _ := range mp { + maxLen = max(maxLen, k) + } + + return maxLen +} + +func max(a, b int) int { + if a > b { + return a + } + + return b +} diff --git a/Medium/L1466.go b/Medium/L1466.go new file mode 100644 index 0000000..207b564 --- /dev/null +++ b/Medium/L1466.go @@ -0,0 +1,41 @@ +package Medium + +type pair struct { + neighbor, edgeWeight int +} + +func newPair(x, y int) pair { + return pair{ + neighbor: x, + edgeWeight: y, + } +} + +func minReorder(n int, connections [][]int) int { + mp, ans := make(map[int][]pair), 0 + var solve func(node, parent int) + + for _, c := range connections { + if _, ok := mp[c[0]]; !ok { + mp[c[0]] = make([]pair, 0) + } + mp[c[0]] = append(mp[c[0]], newPair(c[1], 1)) + + if _, ok := mp[c[1]]; !ok { + mp[c[1]] = make([]pair, 0) + } + mp[c[1]] = append(mp[c[1]], newPair(c[0], 0)) + } + + solve = func(node, parent int) { + for _, nei := range mp[node] { + if nei.neighbor != parent { + ans += nei.edgeWeight + solve(nei.neighbor, node) + } + } + } + + solve(0, -1) + return ans +} diff --git a/Medium/L1492.go b/Medium/L1492.go new file mode 100644 index 0000000..ce11cd8 --- /dev/null +++ b/Medium/L1492.go @@ -0,0 +1,25 @@ +package Medium + +func kthFactor(n int, k int) int { + root := math.Sqrt(float64(n)) + + for i := 1; i < int(math.Ceil(root)); i++ { + if n%i == 0 { + k-- + if k == 0 { + return i + } + } + } + + for i := int(root); i > 0; i-- { + if n%i == 0 { + k-- + if k == 0 { + return n / i + } + } + } + + return -1 +} diff --git a/Medium/L1561.go b/Medium/L1561.go new file mode 100644 index 0000000..a6bcd38 --- /dev/null +++ b/Medium/L1561.go @@ -0,0 +1,12 @@ +package Medium + +func maxCoins(piles []int) int { + sort.Ints(piles) + n, maximum := len(piles), 0 + + for i := n / 3; i < n-1; i += 2 { + maximum += piles[i] + } + + return maximum +} diff --git a/Medium/L1615.go b/Medium/L1615.go new file mode 100644 index 0000000..ae96757 --- /dev/null +++ b/Medium/L1615.go @@ -0,0 +1,35 @@ +package Medium + +func maximalNetworkRank(n int, roads [][]int) int { + connected, cnt := make([][]bool, n), make([]int, n) + for i := 0; i < n; i++ { + connected[i] = make([]bool, n) + } + + for _, r := range roads { + cnt[r[0]]++ + cnt[r[1]]++ + connected[r[0]][r[1]], connected[r[1]][r[0]] = true, true + } + + res := 0 + for i := 0; i < n; i++ { + for j := i + 1; j < n; j++ { + if connected[i][j] { + res = max(res, cnt[i]+cnt[j]-1) + } else { + res = max(res, cnt[i]+cnt[j]) + } + } + } + + return res +} + +func max(a, b int) int { + if a > b { + return a + } + + return b +} diff --git a/Medium/L1630.go b/Medium/L1630.go new file mode 100644 index 0000000..f5e5aed --- /dev/null +++ b/Medium/L1630.go @@ -0,0 +1,61 @@ +package Medium + +func checkArithmeticSubarrays(nums []int, l []int, r []int) []bool { + var res []bool + for i := 0; i < len(l); i++ { + res = append(res, isArithmetic(nums, l[i], r[i])) + } + + return res +} + +func isArithmetic(nums []int, l, r int) bool { + maximum, minimum := math.MinInt32, math.MaxInt32 + + for i := l; i <= r; i++ { + maximum = max(nums[i], maximum) + minimum = min(nums[i], minimum) + } + + length := r - l + 1 + visited := make([]bool, length) + if (maximum-minimum)%(length-1) != 0 { + return false + } + + diff := (maximum - minimum) / (length - 1) + if diff == 0 { + return true + } + + for i := l; i <= r; i++ { + val := nums[i] + if (val-minimum)%diff != 0 { + return false + } else { + pos := (val - minimum) / diff + if visited[pos] { + return false + } + visited[pos] = true + } + } + + return true +} + +func min(a, b int) int { + if a < b { + return a + } + + return b +} + +func max(a, b int) int { + if a > b { + return a + } + + return b +} diff --git a/Medium/L1637.go b/Medium/L1637.go new file mode 100644 index 0000000..dd45e2f --- /dev/null +++ b/Medium/L1637.go @@ -0,0 +1,33 @@ +package Medium + +func maxWidthOfVerticalArea(points [][]int) int { + xCoordMap := make(map[int]bool) + maxDiff, prevX := 0, math.MinInt32 + + for _, p := range points { + xCoordMap[p[0]] = true + } + + var keys []int + for k, _ := range xCoordMap { + keys = append(keys, k) + } + + sort.Ints(keys) + for _, k := range keys { + if prevX != math.MinInt32 { + maxDiff = max(maxDiff, k-prevX) + } + prevX = k + } + + return maxDiff +} + +func max(a, b int) int { + if a > b { + return a + } + + return b +} diff --git a/Medium/L165.go b/Medium/L165.go new file mode 100644 index 0000000..34e005c --- /dev/null +++ b/Medium/L165.go @@ -0,0 +1,27 @@ +package Medium + +func compareVersion(version1 string, version2 string) int { + tmp1, tmp2, len1, len2 := 0, 0, len(version1), len(version2) + i, j := 0, 0 + + for i < len1 || j < len2 { + tmp1, tmp2 = 0, 0 + for i < len1 && version1[i] != '.' { + tmp1 = tmp1*10 + int(version1[i]-'0') + i++ + } + for j < len2 && version2[j] != '.' { + tmp2 = tmp2*10 + int(version2[j]-'0') + j++ + } + if tmp1 > tmp2 { + return 1 + } else if tmp1 < tmp2 { + return -1 + } else { + i, j = i+1, j+1 + } + } + + return 0 +} diff --git a/Medium/L1657.go b/Medium/L1657.go new file mode 100644 index 0000000..fc7508d --- /dev/null +++ b/Medium/L1657.go @@ -0,0 +1,45 @@ +package Medium + +func closeStrings(word1 string, word2 string) bool { + if len(word1) != len(word2) { + return false + } + + solve := func(s string) []int{ + arr := make([]int, 26) + + for _, c := range s { + arr[c - 'a']++ + } + + return arr + } + + charCnt1, charCnt2 := solve(word1), solve(word2) + n := len(word1) + freqCnt1, freqCnt2 := make([]int, n + 1), make([]int, n + 1) + + for i := 0; i < 26; i++ { + if charCnt1[i] > 0 { + freqCnt1[charCnt1[i]]++ + if charCnt2[i] == 0 { + return false + } + } + + if charCnt2[i] > 0 { + freqCnt2[charCnt2[i]]++ + if charCnt1[i] == 0 { + return false + } + } + } + + for i := 0; i < n + 1; i++ { + if freqCnt1[i] != freqCnt2[i] { + return false + } + } + + return true +} diff --git a/Medium/L1685.go b/Medium/L1685.go new file mode 100644 index 0000000..0e1eabb --- /dev/null +++ b/Medium/L1685.go @@ -0,0 +1,19 @@ +package Medium + +func getSumAbsoluteDifferences(nums []int) []int { + result, prefixSum, suffixSum := make([]int, len(nums)), make([]int, len(nums)), make([]int, len(nums)) + + prefixSum[0], suffixSum[len(nums)-1] = nums[0], nums[len(nums)-1] + + for i := 1; i < len(nums); i++ { + prefixSum[i] = prefixSum[i-1] + nums[i] + suffixSum[len(nums)-i-1] = suffixSum[len(nums)-i] + nums[len(nums)-i-1] + } + + for i := 0; i < len(nums); i++ { + currAbsDiff := ((nums[i] * i) - prefixSum[i]) + (suffixSum[i] - (nums[i] * (len(nums) - i - 1))) + result[i] = currAbsDiff + } + + return result +} diff --git a/Medium/L1727.go b/Medium/L1727.go new file mode 100644 index 0000000..3bce886 --- /dev/null +++ b/Medium/L1727.go @@ -0,0 +1,31 @@ +package Medium + +func largestSubmatrix(matrix [][]int) int { + rn, cn := len(matrix), len(matrix[0]) + + for i := 1; i < rn; i++ { + for j := 0; j < cn; j++ { + if matrix[i][j] == 1 { + matrix[i][j] += matrix[i-1][j] + } + } + } + + res := 0 + for i := 0; i < rn; i++ { + sort.Ints(matrix[i]) + for j := 0; j < cn; j++ { + res = max(res, matrix[i][j] * (cn - j)) + } + } + + return res +} + +func max(a, b int) int { + if a > b { + return a + } + + return b +} diff --git a/Medium/L1814.go b/Medium/L1814.go new file mode 100644 index 0000000..80013d7 --- /dev/null +++ b/Medium/L1814.go @@ -0,0 +1,31 @@ +package Medium + +func countNicePairs(nums []int) int { + mp := make(map[int]int) + for i := 0; i < len(nums); i++ { + rev := revInt(nums[i]) + diff := nums[i] - rev + mp[diff]++ + } + + res, mod := 0, 1000000007 + for _, v := range mp { + if v == 1 { + continue + } + res = (res + v*(v-1)/2) % mod + } + + return res +} + +func revInt(n int) int { + newInt := 0 + for n > 0 { + remainder := n % 10 + newInt *= 10 + newInt += remainder + n /= 10 + } + return newInt +} diff --git a/Medium/L1834.go b/Medium/L1834.go new file mode 100644 index 0000000..69e9408 --- /dev/null +++ b/Medium/L1834.go @@ -0,0 +1,58 @@ +type Task struct { + processTime int + index int +} + +type TaskHeap []Task + +func (h TaskHeap) Len() int { return len(h) } +func (h TaskHeap) Less(i, j int) bool { return h[i].processTime < h[j].processTime || (h[i].processTime == h[j].processTime && h[i].index < h[j].index) } +func (h TaskHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } + +func (h *TaskHeap) Push(x interface{}) { + *h = append(*h, x.(Task)) +} + +func (h *TaskHeap) Pop() interface{} { + old := *h + n := len(old) + item := old[n-1] + *h = old[0 : n-1] + return item +} + +func getOrder(tasks [][]int) []int { + dic := make(map[int][]Task) + for i := 0; i < len(tasks); i++ { + dic[tasks[i][0]] = append(dic[tasks[i][0]], Task{tasks[i][1], i}) + } + + ans := []int{} + keys := []int{} + for k := range dic { + keys = append(keys, k) + } + sort.Ints(keys) + + for len(keys) > 0 { + k := keys[0] + keys = keys[1:] + pq := TaskHeap(dic[k]) + heap.Init(&pq) + time := k + + for pq.Len() > 0 { + task := heap.Pop(&pq).(Task) + ans = append(ans, task.index) + time += task.processTime + for len(keys) > 0 && keys[0] <= time { + for _, item := range dic[keys[0]] { + heap.Push(&pq, item) + } + keys = keys[1:] + } + } + } + + return ans +} diff --git a/Medium/L1870.go b/Medium/L1870.go new file mode 100644 index 0000000..d081ba2 --- /dev/null +++ b/Medium/L1870.go @@ -0,0 +1,34 @@ +package Medium + +func minSpeedOnTime(dist []int, hour float64) int { + var timeTaken func(speed int) float64 + left, right, res := 1, 10000007, -1 + + timeTaken = func(speed int) float64 { + var ans float64 + + for i := 0; i < len(dist); i++ { + if i == len(dist)-1 { + ans += float64(dist[i]) / float64(speed) + } else { + ans += math.Ceil(float64(dist[i]) / float64(speed)) + } + } + + return ans + } + + for left <= right { + mid := right - (right-left)/2 + dur := timeTaken(mid) + + if dur <= hour { + res = mid + right = mid - 1 + } else { + left = mid + 1 + } + } + + return res +} diff --git a/Medium/L1915.go b/Medium/L1915.go new file mode 100644 index 0000000..2d9376f --- /dev/null +++ b/Medium/L1915.go @@ -0,0 +1,21 @@ +package Medium + +func wonderfulSubstrings(word string) int64 { + var ( + res int64 + mask int + ) + cnt := make([]int64, 1024) + cnt[0] = 1 + + for i := 0; i < len(word); i++ { + mask ^= 1 << (word[i] - 'a') + res += cnt[mask] + for i := 0; i < 10; i++ { + res += cnt[mask ^ (1 << i)] + } + cnt[mask]++ + } + + return res +} diff --git a/Medium/L1992.go b/Medium/L1992.go new file mode 100644 index 0000000..adf482c --- /dev/null +++ b/Medium/L1992.go @@ -0,0 +1,41 @@ +package Medium + +func findFarmland(land [][]int) [][]int { + var ( + lst [][]int + solve func(x, y int) + ) + row, col := len(land), len(land[0]) + + solve = func(x, y int) { + endX, endY := x, y + + for endY+1 < len(land[0]) && land[x][endY+1] == 1 { + land[x][endY+1] = 0 + endY++ + } + + for endX+1 < len(land) && land[endX+1][y] == 1 { + land[endX+1][y] = 0 + endX++ + } + + for i := x; i <= endX; i++ { + for j := y; j <= endY; j++ { + land[i][j] = 0 + } + } + + lst = append(lst, []int{x, y, endX, endY}) + } + + for i := 0; i < row; i++ { + for j := 0; j < col; j++ { + if land[i][j] == 1 { + solve(i, j) + } + } + } + + return lst +} diff --git a/Medium/L2.go b/Medium/L2.go new file mode 100644 index 0000000..9a9135b --- /dev/null +++ b/Medium/L2.go @@ -0,0 +1,24 @@ +package Meidum + +func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { + dummy := &ListNode{} + current := dummy + carry := 0 + + for l1 != nil || l2 != nil || carry != 0 { + sum := carry + if l1 != nil { + sum += l1.Val + l1 = l1.Next + } + if l2 != nil { + sum += l2.Val + l2 = l2.Next + } + current.Next = &ListNode{Val: sum % 10} + current = current.Next + carry = sum / 10 + } + + return dummy.Next +} diff --git a/Medium/L200.go b/Medium/L200.go new file mode 100644 index 0000000..3d1ff24 --- /dev/null +++ b/Medium/L200.go @@ -0,0 +1,48 @@ +package Medium + +func numIslands(grid [][]byte) int { + dirs := [][]int{{0, 1}, {1, 0}, {0, -1}, {-1, 0}} + cnt, m, n, mp := 0, len(grid), len(grid[0]), make(map[string]bool) + var ( + getKey func(i, j int) string + isValid func(x, y int) bool + solve func(i, j int) + ) + + getKey = func(i, j int) string { + return fmt.Sprintf("%d,%d", i, j) + } + + isValid = func(x, y int) bool { + return x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1' + } + + solve = func(i, j int) { + if !isValid(i, j) { + return + } + + key := getKey(i, j) + if mp[key] { + return + } + mp[key] = true + + for _, d := range dirs { + solve(i+d[0], j+d[1]) + } + } + + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if grid[i][j] == '1' { + if _, ok := mp[getKey(i, j)]; !ok { + cnt++ + solve(i, j) + } + } + } + } + + return cnt +} diff --git a/Medium/L2038.go b/Medium/L2038.go new file mode 100644 index 0000000..e4dd2cf --- /dev/null +++ b/Medium/L2038.go @@ -0,0 +1,17 @@ +package Medium + +func winnerOfGame(colors string) bool { + a, b := 0, 0 + + for i := 1; i < len(colors)-1; i++ { + if colors[i] == colors[i-1] && colors[i] == colors[i+1] { + if colors[i] == 'A' { + a++ + } else { + b++ + } + } + } + + return a > b +} diff --git a/Medium/L207.go b/Medium/L207.go new file mode 100644 index 0000000..9bf8c34 --- /dev/null +++ b/Medium/L207.go @@ -0,0 +1,46 @@ +package Medium + +func canFinish(numCourses int, prerequisites [][]int) bool { + var exists struct{} + if numCourses == 0 { + return false + } + + inDegree, mp := make([]int, numCourses), make(map[int][]int) + for i := 0; i < numCourses; i++ { + mp[i] = make([]int, 0) + } + + for _, p := range prerequisites { + mp[p[1]] = append(mp[p[1]], p[0]) + inDegree[p[0]]++ + } + + var q []int + for i := 0; i < len(inDegree); i++ { + if inDegree[i] == 0 { + q = append(q, i) + } + } + st := make(map[int]struct{}) + for len(q) > 0 { + size := len(q) + for i := 0; i < size; i++ { + c := q[0] + q = q[1:] + + if _, ok := st[c]; ok { + continue + } + st[c] = exists + for _, n := range mp[c] { + inDegree[n]-- + if inDegree[n] == 0 { + q = append(q, n) + } + } + } + } + + return len(st) == numCourses +} diff --git a/Medium/L2125.go b/Medium/L2125.go new file mode 100644 index 0000000..1f74491 --- /dev/null +++ b/Medium/L2125.go @@ -0,0 +1,20 @@ +package Medium + +func numberOfBeams(bank []string) int { + res, prev := 0, 0 + + for _, s := range bank { + cnt := 0 + for i := 0; i < len(s); i++ { + if s[i] == '1' { + cnt++ + } + } + if cnt > 0 { + res += prev * cnt + prev = cnt + } + } + + return res +} diff --git a/Medium/L2187.go b/Medium/L2187.go new file mode 100644 index 0000000..9b18c29 --- /dev/null +++ b/Medium/L2187.go @@ -0,0 +1,47 @@ +package Medium + +func minimumTime(time []int, totalTrips int) int64 { + var ( + lowTime int64 + highTime int64 + ) + minTripTime := func() int64 { + mini := math.MaxInt32 + + for _, t := range time { + mini = min(mini, t) + } + + return int64(mini) + } + + numTripsForGivenTime := func(givenTime int64) int64 { + var totTrips int64 + for _, t := range time { + totTrips += givenTime / int64(t) + } + + return totTrips + } + lowTime, highTime = 1, minTripTime()*int64(totalTrips) + + for lowTime < highTime { + mid := lowTime + (highTime-lowTime)/2 + + if numTripsForGivenTime(mid) >= int64(totalTrips) { + highTime = mid + } else { + lowTime = mid + 1 + } + } + + return lowTime +} + +func min(a, b int) int { + if a < b { + return a + } + + return b +} diff --git a/Medium/L2300.go b/Medium/L2300.go new file mode 100644 index 0000000..c23e2e8 --- /dev/null +++ b/Medium/L2300.go @@ -0,0 +1,22 @@ +package Medium + +func successfulPairs(spells []int, potions []int, success int64) []int { + res := make([]int, len(spells)) + sort.Ints(potions) + + for i := 0; i < len(spells); i++ { + low, high := 0, len(potions) - 1 + for low <= high { + mid := low + (high - low) / 2 + + if int64(spells[i] * potions[mid]) >= success { + high = mid - 1 + } else { + low = mid + 1 + } + } + res[i] = len(potions) - 1 - high + } + + return res +} diff --git a/Medium/L2316.go b/Medium/L2316.go new file mode 100644 index 0000000..f1b3816 --- /dev/null +++ b/Medium/L2316.go @@ -0,0 +1,39 @@ +package Medium + +class Solution { +public: + void dfs(vectoradj[],int src,vector&vis,int &counter){ + if(vis[src]) return; + vis[src]=true; + counter++; + for(auto ele:adj[src]){ + if(!vis[ele]){ + dfs(adj,ele,vis,counter); + } + } + + } + long long countPairs(int n, vector>& edges) { + vectoradj[n]; + for(auto ele:edges){ + adj[ele[0]].push_back(ele[1]); + adj[ele[1]].push_back(ele[0]); + } + long long res = 0; + vectorvis(n,false); + vectortemp; + for(int i = 0;i= 0 && right >= 0 { + return max(left, right) + 1 + } + + *res = max(*res, abs(left-right)) + return min(left, right) - 1 + } + + solve(root, &amount) + return amount +} + +func abs(a int) int { + if a < 0 { + return -a + } + + return a +} diff --git a/Medium/L2390.py b/Medium/L2390.py new file mode 100644 index 0000000..4b085dd --- /dev/null +++ b/Medium/L2390.py @@ -0,0 +1,15 @@ +package Medium + +func removeStars(s string) string { + st := []rune{} + + for _, c := range s { + if c != '*' { + st = append(st, c) + } else if len(st) > 0 { + st = st[:len(st)-1] + } + } + + return string(st) +} diff --git a/Medium/L2405.go b/Medium/L2405.go new file mode 100644 index 0000000..55d64d9 --- /dev/null +++ b/Medium/L2405.go @@ -0,0 +1,18 @@ +package Medium + +func partitionString(s string) int { + var exists struct{} + idx, cnt := 0, 0 + mp := make(map[byte]struct{}) + + for i := range s { + if _, ok := mp[s[i]]; ok { + cnt++ + mp = make(map[byte]struct{}) + } + mp[s[i]] = exists + idx++ + } + + return cnt + 1 +} diff --git a/Medium/L2439.go b/Medium/L2439.go new file mode 100644 index 0000000..c9963a4 --- /dev/null +++ b/Medium/L2439.go @@ -0,0 +1,33 @@ +package Medium + +func minimizeArrayValue(nums []int) int { + low, high, res := 0, math.MaxInt32, 0 + + isPossible := func(maximum int) bool { + excess := 0 + for _, n := range nums { + if n > maximum { + candidate := n - maximum + if candidate > excess { + return false + } + excess -= candidate + } else { + excess += maximum - n + } + } + + return true + } + + for low <= high { + mid := low + (high-low)/2 + if isPossible(mid) { + high, res = mid-1, mid + } else { + low = mid + 1 + } + } + + return res +} diff --git a/Medium/L2482.go b/Medium/L2482.go new file mode 100644 index 0000000..3b6db3b --- /dev/null +++ b/Medium/L2482.go @@ -0,0 +1,25 @@ +package Medium + +func onesMinusZeros(grid [][]int) [][]int { + m, n := len(grid), len(grid[0]) + diff, rows, cols := make([][]int, m), make([]int, m), make([]int, n) + + for i := 0; i < m; i++ { + diff[i] = make([]int, n) + } + + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + rows[i] += grid[i][j] + cols[j] += grid[i][j] + } + } + + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + diff[i][j] = rows[i] + cols[j] - (n - rows[i]) - (m - cols[j]) + } + } + + return diff +} diff --git a/Medium/L2492.go b/Medium/L2492.go new file mode 100644 index 0000000..7a2cce9 --- /dev/null +++ b/Medium/L2492.go @@ -0,0 +1,47 @@ +package Medium + +type pair struct { + x, y int +} + +func newPair(x, y int) pair { + return pair{ + x: x, + y: y, + } +} + +func minScore(n int, roads [][]int) int { + adj, vis := make([][]pair, n+1), make([]bool, n+1) + for i := 0; i < n+1; i++ { + adj[i] = make([]pair, 0) + } + + for i := range roads { + adj[roads[i][0]] = append(adj[roads[i][0]], newPair(roads[i][1], roads[i][2])) + adj[roads[i][1]] = append(adj[roads[i][1]], newPair(roads[i][0], roads[i][2])) + } + + var q []int + q = append(q, 1) + vis[1] = true + for len(q) > 0 { + node := q[0] + q = q[1:] + for _, p := range adj[node] { + if !vis[p.x] { + q = append(q, p.x) + vis[p.x] = true + } + } + } + + minPath := math.MaxInt32 + for i := range roads { + if vis[roads[i][0]] && vis[roads[i][1]] && roads[i][2] < minPath { + minPath = roads[i][2] + } + } + + return minPath +} diff --git a/Medium/L2610.go b/Medium/L2610.go new file mode 100644 index 0000000..43ec419 --- /dev/null +++ b/Medium/L2610.go @@ -0,0 +1,17 @@ +package Medium + +func findMatrix(nums []int) [][]int { + var ans [][]int + freq := make([]int, len(nums) + 1) + + for _, n := range nums { + if freq[n] >= len(ans) { + ans = append(ans, []int{n}) + } else { + ans[freq[n]] = append(ans[freq[n]], n) + } + freq[n]++ + } + + return ans +} diff --git a/Medium/L2849.go b/Medium/L2849.go new file mode 100644 index 0000000..1543919 --- /dev/null +++ b/Medium/L2849.go @@ -0,0 +1,19 @@ +package Medium + +func isReachableAtTime(sx int, sy int, fx int, fy int, t int) bool { + xDist, yDist := abs(sx-fx), abs(sy-fy) + + if xDist == 0 && yDist == 0 { + return t != 1 + } + + return xDist <= t && yDist <= t +} + +func abs(a int) int { + if a < 0 { + return -a + } + + return a +} diff --git a/Medium/L2870.go b/Medium/L2870.go new file mode 100644 index 0000000..e7e62c8 --- /dev/null +++ b/Medium/L2870.go @@ -0,0 +1,22 @@ +package Medium + +func minOperations(nums []int) int { + mp, cnt := make(map[int]int), 0 + + for _, n := range nums { + mp[n]++ + } + + for _, v := range mp { + if v == 1 { + return -1 + } + + cnt += v / 3 + if v%3 != 0 { + cnt++ + } + } + + return cnt +} diff --git a/Medium/L2966.go b/Medium/L2966.go new file mode 100644 index 0000000..7a28841 --- /dev/null +++ b/Medium/L2966.go @@ -0,0 +1,21 @@ +package Medium + +func divideArray(nums []int, k int) [][]int { + var res [][]int + if len(nums)%3 != 0 { + return res + } + + sort.Ints(nums) + groupIdx := 0 + for i := 0; i < len(nums); i += 3 { + if i+2 < len(nums) && nums[i+2]-nums[i] <= k { + res = append(res, []int{nums[i], nums[i+1], nums[i+2]}) + groupIdx++ + } else { + return [][]int{} + } + } + + return res +} diff --git a/Medium/L2997.go b/Medium/L2997.go new file mode 100644 index 0000000..3846a53 --- /dev/null +++ b/Medium/L2997.go @@ -0,0 +1,20 @@ +package Medium + +func minOperations(nums []int, k int) int { + finalXor := 0 + for _, n := range nums { + finalXor ^= n + } + + cnt := 0 + for k > 0 || finalXor > 0 { + if (k % 2) != (finalXor % 2) { + cnt++ + } + + k /= 2 + finalXor /= 2 + } + + return cnt +} diff --git a/Medium/L319.go b/Medium/L319.go new file mode 100644 index 0000000..1dcc42e --- /dev/null +++ b/Medium/L319.go @@ -0,0 +1,19 @@ +package Medium + +func bulbSwitch(n int) int { + low, high := 0, n + + for low <= high { + mid := low + (high - low) / 2 + candidate := mid * mid + if candidate == n { + return mid + } else if candidate < n { + low = mid + 1 + } else { + high = mid - 1 + } + } + + return low - 1 +} diff --git a/Medium/L33.go b/Medium/L33.go new file mode 100644 index 0000000..7625c15 --- /dev/null +++ b/Medium/L33.go @@ -0,0 +1,45 @@ +package Medium + +func search(nums []int, target int) int { + if len(nums) == 0 { + return -1 + } + + var rotationCnt func() int + + rotationCnt = func() int { + l, r := 0, len(nums)-1 + + for l < r { + mid := l + (r-l)/2 + if mid < r && nums[mid] > nums[mid+1] { + return mid + 1 + } + if mid > l && nums[mid] < nums[mid-1] { + return mid + } + if nums[mid] < nums[r] { + r = mid - 1 + } else { + l = mid + 1 + } + } + + return l + } + rotCnt := rotationCnt() + low, high := 0, len(nums)-1 + for low <= high { + mid := low + (high-low)/2 + realMid := (mid + rotCnt) % len(nums) + if nums[realMid] == target { + return realMid + } else if nums[realMid] < target { + low = mid + 1 + } else { + high = mid - 1 + } + } + + return -1 +} diff --git a/Medium/L427.go b/Medium/L427.go new file mode 100644 index 0000000..1baa4bc --- /dev/null +++ b/Medium/L427.go @@ -0,0 +1,40 @@ +package Medium + +func construct(grid [][]int) *Node { + var solve func(x1, x2, y1, y2 int) *Node + solve = func(x1, x2, y1, y2 int) *Node { + if x1 == x2 { + val := false + if grid[x1][y1] == 1 { + val = true + } + return &Node{ + Val: val, + IsLeaf: true, + } + } + + rowMid, colMid := (x1+x2)/2, (y1+y2)/2 + topLeft := solve(x1, rowMid, y1, colMid) + topRight := solve(x1, rowMid, colMid+1, y2) + bottomLeft := solve(rowMid+1, x2, y1, colMid) + bottomRight := solve(rowMid+1, x2, colMid+1, y2) + + if topLeft.IsLeaf && topRight.IsLeaf && bottomLeft.IsLeaf && bottomRight.IsLeaf && + topRight.Val == topLeft.Val && topRight.Val == bottomLeft.Val && topRight.Val == bottomRight.Val { + return &Node{ + Val: topLeft.Val, + IsLeaf: true, + } + } else { + return &Node{ + TopLeft: topLeft, + TopRight: topRight, + BottomLeft: bottomLeft, + BottomRight: bottomRight, + } + } + } + + return solve(0, len(grid)-1, 0, len(grid[0])-1) +} diff --git a/Medium/L443.go b/Medium/L443.go new file mode 100644 index 0000000..7be4e6a --- /dev/null +++ b/Medium/L443.go @@ -0,0 +1,32 @@ +package Medium + +func compress(chars []byte) int { + index := 0 + + updateChars := func(freq int) { + arr := []byte(fmt.Sprintf("%d", freq)) + for i := range arr { + chars[index] = arr[i] + index++ + } + } + + for i := 0; i < len(chars); { + j := i + for j < len(chars) && chars[i] == chars[j] { + j++ + } + freq := j - i + chars[index] = chars[i] + index++ + if freq > 1 && freq < 10 { + chars[index] = byte(freq + '0') + index++ + } else if freq >= 10 { + updateChars(freq) + } + i = j + } + + return index +} diff --git a/Medium/L46.go b/Medium/L46.go new file mode 100644 index 0000000..072aaeb --- /dev/null +++ b/Medium/L46.go @@ -0,0 +1,37 @@ +package Medium + +func permute(nums []int) [][]int { + var ( + ans [][]int + tmp []int + solve func(tmp []int) + ) + if len(nums) == 0 { + return ans + } + + mp := make(map[int]bool) + solve = func(tmp []int) { + if len(tmp) == len(nums) { + tmpCopy := make([]int, len(tmp)) + copy(tmpCopy, tmp) + ans = append(ans, tmpCopy) + return + } + + for i := 0; i < len(nums); i++ { + if mp[nums[i]] { + continue + } + tmp = append(tmp, nums[i]) + mp[nums[i]] = true + solve(tmp) + delElem := tmp[len(tmp) - 1] + tmp = tmp[:len(tmp) - 1] + delete(mp, delElem) + } + } + + solve(tmp) + return ans +} diff --git a/Medium/L486.go b/Medium/L486.go new file mode 100644 index 0000000..b6e8406 --- /dev/null +++ b/Medium/L486.go @@ -0,0 +1,45 @@ +package Medium + +func PredictTheWinner(nums []int) bool { + var solve func(i, j, c int) int + mp := make(map[string]int) + + solve = func(i, j, c int) int { + if j < i { + return 0 + } + + key := fmt.Sprintf("%d-%d-%d", i, j, c) + if v, ok := mp[key]; ok { + return v + } + + res := 0 + if c == 0 { + res = max(solve(i+1, j, 1-c)+nums[i], solve(i, j-1, 1-c)+nums[j]) + } else { + res = min(solve(i+1, j, 1-c)-nums[i], solve(i, j-1, 1-c)-nums[j]) + } + + return res + } + + ans := solve(0, len(nums)-1, 0) + return ans >= 0 +} + +func min(a, b int) int { + if a < b { + return a + } + + return b +} + +func max(a, b int) int { + if a > b { + return a + } + + return b +} diff --git a/Medium/L516.go b/Medium/L516.go new file mode 100644 index 0000000..4a9e163 --- /dev/null +++ b/Medium/L516.go @@ -0,0 +1,37 @@ +func longestPalindromeSubseq(s string) int { + mp := make(map[string]int) + var solve func(left, right int) int + + solve = func(left, right int) int { + if left == right { + return 1 + } + + if left > right { + return 0 + } + + key := fmt.Sprintf("%d-%d", left, right) + if v, ok := mp[key]; ok { + return v + } + + if s[left] == s[right] { + mp[key] = 2 + solve(left+1, right-1) + } else { + mp[key] = max(solve(left+1, right), solve(left, right-1)) + } + + return mp[key] + } + + return solve(0, len(s) - 1) +} + +func max(a, b int) int { + if a > b { + return a + } + + return b +} diff --git a/Medium/L542.go b/Medium/L542.go new file mode 100644 index 0000000..d6e45c8 --- /dev/null +++ b/Medium/L542.go @@ -0,0 +1,61 @@ +package Medium + +func updateMatrix(mat [][]int) [][]int { + var ( + res, q [][]int + isValid func(x, y int) bool + ) + if len(mat) == 0 { + return res + } + + dirs := [][]int{{0, 1}, {1, 0}, {0, -1}, {-1, 0}} + m, n := len(mat), len(mat[0]) + vis := make([][]bool, m) + for i := 0; i < m; i++ { + vis[i] = make([]bool, n) + } + + isValid = func(x, y int) bool { + return x >= 0 && y >= 0 && x < m && y < n && mat[x][y] == math.MaxInt32 + } + + for i := 0; i < m; i++ { + for j := 0; j < n; j++ { + if mat[i][j] == 0 { + q = append(q, []int{i, j}) + } else { + mat[i][j] = math.MaxInt32 + } + } + } + + for len(q) > 0 { + c := q[0] + q = q[1:] + + if vis[c[0]][c[1]] { + continue + } + vis[c[0]][c[1]] = true + + for _, d := range dirs { + newX, newY := c[0]+d[0], c[1]+d[1] + if isValid(newX, newY) { + mat[newX][newY] = min(mat[newX][newY], mat[c[0]][c[1]]+1) + q = append(q, []int{newX, newY}) + } + } + } + + return mat +} + + +func min(a, b int) int { + if a < b { + return a + } + + return b +} diff --git a/Medium/L649.go b/Medium/L649.go new file mode 100644 index 0000000..9831a70 --- /dev/null +++ b/Medium/L649.go @@ -0,0 +1,29 @@ +package Medium + +func predictPartyVictory(senate string) string { + var q1, q2 []int + n := len(senate) + for i := 0; i < n; i++ { + if senate[i] == 'R' { + q1 = append(q1, i) + } else { + q2 = append(q2, i) + } + } + + for len(q1) > 0 && len(q2) > 0 { + rIndex, dIndex := q1[0], q2[0] + q1, q2 = q1[1:], q2[1:] + + if rIndex < dIndex { + q1 = append(q1, rIndex + n) + } else { + q2 = append(q2, dIndex + n) + } + } + if len(q1) > len(q2) { + return "Radiant" + } + + return "Dire" +} diff --git a/Medium/L652.go b/Medium/L652.go new file mode 100644 index 0000000..0bb4735 --- /dev/null +++ b/Medium/L652.go @@ -0,0 +1,35 @@ +package Medium + +func findDuplicateSubtrees(root *TreeNode) []*TreeNode { + curID := 1 + serialToID, idToCount := make(map[string]int), make(map[int]int) + var ( + res []*TreeNode + solve func(root *TreeNode) int + ) + solve = func(root *TreeNode) int { + if root == nil { + return 0 + } + + leftID, rightID := solve(root.Left), solve(root.Right) + curSerial := fmt.Sprintf("%d-%d-%d", leftID, root.Val, rightID) + serialID := curID + if v, ok := serialToID[curSerial]; ok { + serialID = v + } + if serialID == curID { + curID++ + } + serialToID[curSerial] = serialID + idToCount[serialID]++ + + if idToCount[serialID] == 2 { + res = append(res, root) + } + return serialID + } + + solve(root) + return res +} diff --git a/Medium/L673.go b/Medium/L673.go new file mode 100644 index 0000000..e019848 --- /dev/null +++ b/Medium/L673.go @@ -0,0 +1,62 @@ +package Medium + +type Pair struct { + l, c int +} + +func newPair(a, b int) *Pair { + return &Pair{ + l: a, + c: b, + } +} + +func findNumberOfLIS(nums []int) int { + var ( + solve func(idx int) *Pair + maxL, maxC int + ) + dp := make(map[int]*Pair) + + solve = func(idx int) *Pair { + if idx == len(nums) { + return newPair(0, 0) + } + if v, ok := dp[idx]; ok { + return v + } + + ml, mc := 0, 0 + for i := idx + 1; i < len(nums); i++ { + if nums[i] > nums[idx] { + tmp := solve(i) + if tmp.l > ml { + ml = tmp.l + mc = tmp.c + } else if tmp.l == ml { + mc += tmp.c + } + } + } + + if ml == 0 && mc == 0 { + dp[idx] = newPair(1, 1) + return dp[idx] + } + + dp[idx] = newPair(1+ml, mc) + return dp[idx] + } + + for i := range nums { + tmpPair := solve(i) + if tmpPair.l > maxL { + maxL = tmpPair.l + maxC = tmpPair.c + } else if tmpPair.l == maxL { + maxC += tmpPair.c + } + } + + return maxC +} diff --git a/Medium/L688.go b/Medium/L688.go new file mode 100644 index 0000000..9ee9ed2 --- /dev/null +++ b/Medium/L688.go @@ -0,0 +1,31 @@ +package Medium + +func knightProbability(n int, k int, row int, column int) float64 { + var ( + solve func(K, r, c int) float64 + dir = [][]int{{-2, -1}, {-1, -2}, {1, -2}, {2, -1}, {2, 1}, {1, 2}, {-1, 2}, {-2, 1}} + mp = make(map[string]float64) + ) + + solve = func(K, r, c int) float64 { + if r < 0 || r > n-1 || c < 0 || c > n-1 { + return 0 + } + if K == 0 { + return 1 + } + key := fmt.Sprintf("%d-%d-%d", r, c, K) + if v, ok := mp[key]; ok { + return v + } + var rate float64 + for _, d := range dir { + rate += 0.125 * solve(K - 1, r + d[0], c + d[1]) + } + + mp[key] = rate + return mp[key] + } + + return solve(k, row, column) +} diff --git a/Medium/L712.go b/Medium/L712.go new file mode 100644 index 0000000..c85636d --- /dev/null +++ b/Medium/L712.go @@ -0,0 +1,54 @@ +package Medium + +func minimumDeleteSum(s1 string, s2 string) int { + var ( + solve func(i, j int) int + deadEndSum func(str string, i int) int + ) + mp, m, n := make(map[string]int), len(s1), len(s2) + + deadEndSum = func(str string, i int) int { + sum := 0 + for ; i < len(str); i++ { + sum += int(str[i]) + } + + return sum + } + + solve = func(i, j int) int { + sum := 0 + if i == m && j == n { + return 0 + } + if i == m { + return deadEndSum(s2, j) + } else if j == n { + return deadEndSum(s1, i) + } + + key := fmt.Sprintf("%d-%d", i, j) + if v, ok := mp[key]; ok { + return v + } + + if s1[i] == s2[j] { + sum = solve(i+1, j+1) + } else { + sum = min(solve(i+1, j)+int(s1[i]), solve(i, j+1)+int(s2[j])) + } + + mp[key] = sum + return mp[key] + } + + return solve(0, 0) +} + +func min(a, b int) int { + if a < b { + return a + } + + return b +} diff --git a/Medium/L735.go b/Medium/L735.go new file mode 100644 index 0000000..96ff228 --- /dev/null +++ b/Medium/L735.go @@ -0,0 +1,27 @@ +package Medium + +func asteroidCollision(asteroids []int) []int { + var res []int + if len(asteroids) == 0 { + return res + } + + for _, a := range asteroids { + if a > 0 { + res = append(res, a) + } else { + for len(res) > 0 && + res[len(res) - 1] > 0 && + -a > res[len(res) - 1] { + res = res[:len(res) - 1] + } + if len(res) == 0 || res[len(res) - 1] < 0 { + res = append(res, a) + } else if res[len(res) - 1] == -a { + res = res[:len(res) - 1] + } + } + } + + return res +} diff --git a/Medium/L752.go b/Medium/L752.go new file mode 100644 index 0000000..5efd4a3 --- /dev/null +++ b/Medium/L752.go @@ -0,0 +1,48 @@ +package Medium + +func openLock(deadends []string, target string) int { + var ( + neighbors func(code string) []string + q []string + ) + deadSet := make(map[string]bool) + for _, dead := range deadends { + deadSet[dead] = true + } + if deadSet["0000"] { + return -1 + } + + neighbors = func(code string) []string { + var res []string + for i := 0; i < 4; i++ { + x := int(code[i] - '0') + for diff := -1; diff <= 1; diff += 2 { + y := (x + diff + 10) % 10 + res = append(res, fmt.Sprintf("%s\"\"%d%s", code[:i], y, code[i+1:])) + } + } + + return res + } + + q = append(q, "0000") + for steps := 0; len(q) > 0; steps++ { + for i := len(q); i > 0; i-- { + curr := q[0] + q = q[1:] + if curr == target { + return steps + } + for _, nei := range neighbors(curr) { + if deadSet[nei] { + continue + } + deadSet[nei] = true + q = append(q, nei) + } + } + } + + return -1 +} diff --git a/Medium/L767.go b/Medium/L767.go new file mode 100644 index 0000000..bbb2787 --- /dev/null +++ b/Medium/L767.go @@ -0,0 +1,51 @@ +package Medium + +type Pair struct { + Key byte + Value int +} + +type PairList []Pair + +func (p PairList) Len() int { return len(p) } +func (p PairList) Swap(i, j int) { p[i], p[j] = p[j], p[i] } +func (p PairList) Less(i, j int) bool { return p[i].Value > p[j].Value } + +func reorganizeString(s string) string { + freqMap, res := make(map[byte]int), make([]byte, len(s)) + for _, ch := range s { + freqMap[byte(ch)]++ + } + + getSortedChars := func() PairList { + p := make(PairList, len(freqMap)) + i := 0 + for k, v := range freqMap { + p[i] = Pair{ + Key: k, + Value: v, + } + i++ + } + sort.Sort(p) + + return p + } + + sortedChars := getSortedChars() + if freqMap[sortedChars[0].Key] > ((len(s) + 1) / 2) { + return "" + } + + idx := 0 + for _, pair := range sortedChars { + for j := 0; j < freqMap[pair.Key]; j++ { + if idx >= len(s) { + idx = 1 + } + res[idx] = pair.Key + idx += 2 + } + } + return string(res) +} diff --git a/Medium/L77.go b/Medium/L77.go new file mode 100644 index 0000000..5ae99a4 --- /dev/null +++ b/Medium/L77.go @@ -0,0 +1,27 @@ +package Medium + +func combine(n int, k int) [][]int { + var ( + solve func(tmp *[]int, start, k int) + res [][]int + tmp []int + ) + + solve = func(tmp *[]int, start, k int) { + if k == 0 { + tmpCopy := make([]int, len(*tmp)) + copy(tmpCopy, *tmp) + res = append(res, tmpCopy) + return + } + + for i := start; i <= n; i++ { + *tmp = append(*tmp, i) + solve(tmp, i+1, k-1) + *tmp = (*tmp)[:len(*tmp)-1] + } + } + + solve(&tmp, 1, k) + return res +} diff --git a/Medium/L808.go b/Medium/L808.go new file mode 100644 index 0000000..99c5811 --- /dev/null +++ b/Medium/L808.go @@ -0,0 +1,34 @@ +package Medium + +func soupServings(n int) float64 { + if n >= 5000 { + return 1.0 + } + + var solve func(a, b int) float64 + mp := make(map[string]float64) + + solve = func(a, b int) float64 { + if a <= 0 && b > 0 { + return 1.0 + } + + if a <= 0 && b <= 0 { + return 0.5 + } + + if a > 0 && b <= 0 { + return 0.0 + } + + key := fmt.Sprintf("%d-%d", a, b) + if v, ok := mp[key]; ok { + return v + } + + mp[key] = 0.25 * (solve(a-100, b) + solve(a-75, b-25) + solve(a-50, b-50) + solve(a-25, b-75)) + return mp[key] + } + + return solve(n, n) +} diff --git a/Medium/L852.go b/Medium/L852.go new file mode 100644 index 0000000..008d975 --- /dev/null +++ b/Medium/L852.go @@ -0,0 +1,16 @@ +package Medium + +func peakIndexInMountainArray(arr []int) int { + low, high := 0, len(arr)-1 + + for low <= high { + mid := low + (high-low)/2 + if arr[mid] < arr[mid+1] { + low = mid + 1 + } else { + high = mid - 1 + } + } + + return low +} diff --git a/Medium/L861.go b/Medium/L861.go new file mode 100644 index 0000000..06c031a --- /dev/null +++ b/Medium/L861.go @@ -0,0 +1,19 @@ +package Medium + +func matrixScore(grid [][]int) int { + m, n, res := len(grid), len(grid[0]), 0 + + res += (1 << (n - 1)) * m + + for j := 1; j < n; j++ { + same := 0 + for i := 0; i < m; i++ { + if grid[i][0] == grid[i][j] { + same++ + } + } + res += (1 << (n - 1 - j))*max(same, m - same) + } + + return res +} diff --git a/Medium/L863.go b/Medium/L863.go new file mode 100644 index 0000000..9c4931f --- /dev/null +++ b/Medium/L863.go @@ -0,0 +1,55 @@ +package Medium + +func distanceK(root *TreeNode, target *TreeNode, k int) []int { + var ( + res []int + find func(root, target *TreeNode) + search func(root *TreeNode, distance int) + ) + mp := make(map[*TreeNode]int) + + find = func(root, target *TreeNode) { + if root == nil { + return + } + + if root == target { + mp[root] = 0 + return + } + + find(root.Left, target) + if val, ok := mp[root.Left]; ok { + mp[root] = val + 1 + return + } + + find(root.Right, target) + if val, ok := mp[root.Right]; ok { + mp[root] = val + 1 + return + } + } + + search = func(root *TreeNode, distance int) { + if root == nil { + return + } + + if val, ok := mp[root]; ok { + distance = val + } + + if distance == k { + res = append(res, root.Val) + } + + search(root.Left, distance+1) + search(root.Right, distance+1) + } + + find(root, target) + search(root, 0) + + return res +} diff --git a/Medium/L874.py b/Medium/L874.py new file mode 100644 index 0000000..66f4f60 --- /dev/null +++ b/Medium/L874.py @@ -0,0 +1,25 @@ +class Solution: + def robotSim(self, commands, obstacles): + obstacle_set = set() + for obs in obstacles: + obstacle_set.add(f"{obs[0]} {obs[1]}") + + directions = [[0, 1], [1, 0], [0, -1], [-1, 0]] # north, east, south, west + d = 0 # direction index + x, y = 0, 0 # initial position + result = 0 + + for command in commands: + if command == -1: # turn right + d = (d + 1) % 4 + elif command == -2: # turn left + d = (d - 1) % 4 + else: + for _ in range(command): + next_x = x + directions[d][0] + next_y = y + directions[d][1] + if f"{next_x} {next_y}" not in obstacle_set: + x, y = next_x, next_y + result = max(result, x * x + y * y) + + return result diff --git a/Medium/L907.go b/Medium/L907.go new file mode 100644 index 0000000..9b51891 --- /dev/null +++ b/Medium/L907.go @@ -0,0 +1,32 @@ +package Medium + +func sumSubarrayMins(arr []int) int { + var ( + res int64 + st []int + mod = int64(1000000007) + + ) + st = append(st, -1) + + for i := 0; i < len(arr) + 1; i++ { + currVal := 0 + if i < len(arr) { + currVal = arr[i] + } + + for st[len(st) - 1] != -1 && currVal < arr[st[len(st) - 1]] { + index := st[len(st) - 1] + st = st[:len(st) - 1] + newTop := st[len(st) - 1] + left, right := index - newTop, i - index + add := int64(left * right * arr[index]) % mod + res += add + res %= mod + } + + st = append(st, i) + } + + return int(res) +} diff --git a/Medium/L931.go b/Medium/L931.go index e326189..82b428a 100644 --- a/Medium/L931.go +++ b/Medium/L931.go @@ -1,36 +1,32 @@ package Medium func minFallingPathSum(matrix [][]int) int { - rows, cols := len(matrix), len(matrix[0]) - mp, ans := make(map[string]int), math.MaxInt32 + var ( + solve func(row, col int) int + ) + cols, mp, res := len(matrix[0]), make(map[string]int), math.MaxInt32 - for c := 0; c < cols; c++ { - ans = min(ans, solve(matrix, rows-1, c, mp)) - } + solve = func(row, col int) int { + if col >= cols || col < 0 { + return math.MaxInt32 + } - return ans -} + key := fmt.Sprintf("%d#%d", row, col) + if v, ok := mp[key]; ok { + return v + } -func solve(matrix [][]int, r, c int, mp map[string]int) int { - if r == 0 && c < len(matrix[0]) && c >= 0 { - return matrix[r][c] - } - if c >= len(matrix[0]) || c < 0 { - return math.MaxInt32 - } - key := fmt.Sprintf("%d-%d", r, c) - if v, ok := mp[key]; ok { - return v - } + if row == len(matrix)-1 && col < cols { + return matrix[row][col] + } - mp[key] = matrix[r][c] + min(min(solve(matrix, r-1, c+1, mp), solve(matrix, r-1, c, mp)), solve(matrix, r-1, c-1, mp)) - return mp[key] -} + mp[key] = matrix[row][col] + min(solve(row+1, col-1), min(solve(row+1, col), solve(row+1, col+1))) + return mp[key] + } -func min(a, b int) int { - if a < b { - return a + for i := 0; i < cols; i++ { + res = min(res, solve(0, i)) } - return b + return res } diff --git a/Medium/L934.go b/Medium/L934.go new file mode 100644 index 0000000..848751f --- /dev/null +++ b/Medium/L934.go @@ -0,0 +1,69 @@ +package Medium + +func shortestBridge(grid [][]int) int { + m, n := len(grid), len(grid[0]) + dirs := [][]int{{0, 1}, {1, 0}, {0, -1}, {-1, 0}} + visited := make([][]bool, m) + for i := 0; i < m; i++ { + visited[i] = make([]bool, n) + } + var ( + found bool + q [][]int + dfs func(x, y int) + isValid func(x, y int) bool + ) + + isValid = func(x, y int) bool { + return x >= 0 && x < m && y >= 0 && y < n && !visited[x][y] && grid[x][y] != 0 + } + + dfs = func(x, y int) { + if !isValid(x, y) { + return + } + + visited[x][y] = true + q = append(q, []int{x, y}) + for _, d := range dirs { + dfs(x+d[0], y+d[1]) + } + } + + for i := 0; i < m; i++ { + if found { + break + } + for j := 0; j < n; j++ { + if grid[i][j] == 1 { + dfs(i, j) + found = true + break + } + } + } + + step := 0 + for len(q) > 0 { + size := len(q) + for size > 0 { + cur := q[0] + q = q[1:] + size-- + + for _, d := range dirs { + x, y := cur[0]+d[0], cur[1]+d[1] + if x >= 0 && y >= 0 && x < m && y < n && !visited[x][y] { + if grid[x][y] == 1 { + return step + } + q = append(q, []int{x, y}) + visited[x][y] = true + } + } + } + step++ + } + + return -1 +} diff --git a/Medium/L958.go b/Medium/L958.go new file mode 100644 index 0000000..ff58d6b --- /dev/null +++ b/Medium/L958.go @@ -0,0 +1,25 @@ +package Medium + +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def isCompleteTree(self, root: Optional[TreeNode]) -> bool: + end, q = False, deque() + q.append(root) + + while q: + curr = q.popleft() + + if not curr: + end = True + else: + if end: + return False + q.append(curr.left) + q.append(curr.right) + + return True diff --git a/Medium/L988.go b/Medium/L988.go new file mode 100644 index 0000000..ac64e51 --- /dev/null +++ b/Medium/L988.go @@ -0,0 +1,37 @@ +package Medium + +func smallestFromLeaf(root *TreeNode) string { + var ( + tmp string + isLeaf func(node *TreeNode) bool + solve func(node *TreeNode, s string) string + ) + + isLeaf = func(node *TreeNode) bool { + if node == nil { + return false + } + + return node.Left == nil && node.Right == nil + } + + solve = func(node *TreeNode, res string) string { + if node == nil { + return "|" + } + + res = fmt.Sprintf("%c", byte('a'+node.Val)) + res + if isLeaf(node) { + return res + } + + left, right := solve(node.Left, res), solve(node.Right, res) + if strings.Compare(left, right) < 0 { + return left + } + + return right + } + + return solve(root, tmp) +} diff --git a/README.md b/README.md index bc75098..5c4bcf9 100644 --- a/README.md +++ b/README.md @@ -3,487 +3,8 @@ Leetcode Solutions in Go Please give this repo a ⭐ if it inspires you. -## Easy -|LC #|Description| -|:-:|:-| -|[1480](https://leetcode.com/problems/running-sum-of-1d-array/)| Running Sum of 1d Array| -|[1431](https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/)| Kids With the Greatest Number of Candies| -|[1](https://leetcode.com/problems/two-sum/)| Two Sum| -|[575](https://leetcode.com/problems/distribute-candies/)| Distribute Candies| -|[1365](https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/)| How Many Numbers Are Smaller Than the Current Number| -|[1773](https://leetcode.com/problems/count-items-matching-a-rule/)| Count Items Matching a Rule| -|[645](https://leetcode.com/problems/set-mismatch/)| Set Mismatch| -|[268](https://leetcode.com/problems/missing-number/)| Missing Number| -|[160](https://leetcode.com/problems/intersection-of-two-linked-lists/)| Intersection of Two Linked Lists| -|[637](https://leetcode.com/problems/average-of-levels-in-binary-tree/)| Average of Levels in Binary Tree| -|[559](https://leetcode.com/problems/maximum-depth-of-n-ary-tree/)| Maximum Depth of N-ary Tree| -|[690](https://leetcode.com/problems/employee-importance/)| Employee Importance| -|[993](https://leetcode.com/problems/cousins-in-binary-tree/)| Cousins in Binary Tree| -|[1748](https://leetcode.com/problems/sum-of-unique-elements/)| Sum of Unique Elements| -|[232](https://leetcode.com/problems/implement-queue-using-stacks/)| Implement Queue using Stacks| -|[1332](https://leetcode.com/problems/remove-palindromic-subsequences/)| Remove Palindromic Subsequences| -|[1678](https://leetcode.com/problems/goal-parser-interpretation/)| Goal Parser Interpretation| -|[1022](https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/)| Sum of Root To Leaf Binary Numbers| -|[404](https://leetcode.com/problems/sum-of-left-leaves/)| Sum of Left Leaves| -|[112](https://leetcode.com/problems/path-sum/)| Path Sum| -|[535](https://leetcode.com/problems/encode-and-decode-tinyurl/)| Encode and Decode TinyURL| -|[1560](https://leetcode.com/problems/most-visited-sector-in-a-circular-track/)| Most Visited Sector in a Circular Track| -|[598](https://leetcode.com/problems/range-addition-ii/)| Range Addition II| -|[762](https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/)| Prime Number of Set Bits in Binary Representation| -|[500](https://leetcode.com/problems/keyboard-row/)| Keyboard Row| -|[1656](https://leetcode.com/problems/design-an-ordered-stream/)| Design an Ordered Stream| -|[234](https://leetcode.com/problems/palindrome-linked-list/)| Palindrome Linked List| -|[1614](https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/)| Maximum Nesting Depth of the Parentheses| -|[1668](https://leetcode.com/problems/maximum-repeating-substring/)| Maximum Repeating Substring| -|[1704](https://leetcode.com/problems/determine-if-string-halves-are-alike/)| Determine if String Halves Are Alike| -|[953](https://leetcode.com/problems/verifying-an-alien-dictionary/)| Verifying an Alien Dictionary| -|[509](https://leetcode.com/problems/fibonacci-number/)| Fibonacci Number| -|[589](https://leetcode.com/problems/n-ary-tree-preorder-traversal/)| N-ary Tree Preorder Traversal| -|[696](https://leetcode.com/problems/count-binary-substrings/)| Count Binary Substrings| -|[326](https://leetcode.com/problems/power-of-three/)| Power of Three| -|[703](https://leetcode.com/problems/kth-largest-element-in-a-stream/)| Kth Largest Element in a Stream| -|[204](https://leetcode.com/problems/count-primes/)| Count Primes| -|[453](https://leetcode.com/problems/minimum-moves-to-equal-array-elements/)| Minimum Moves to Equal Array Elements| -|[709](https://leetcode.com/problems/to-lower-case/)| To Lower Case| -|[1710](https://leetcode.com/problems/maximum-units-on-a-truck/)| Maximum Units on a Truck| -|[1047](https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/)| Remove All Adjacent Duplicates In String| -|[108](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/)| Convert Sorted Array to Binary Search Tree| -|[415](https://leetcode.com/problems/add-strings/)| Add Strings| -|[653](https://leetcode.com/problems/two-sum-iv-input-is-a-bst/)| Two Sum IV - Input is a BST| -|[1629](https://leetcode.com/problems/slowest-key/)| Slowest Key| -|[206](https://leetcode.com/problems/reverse-linked-list/)| Reverse Linked List| -|[1189](https://leetcode.com/problems/maximum-number-of-balloons/)| Maximum Number of Balloons| -|[350](https://leetcode.com/problems/intersection-of-two-arrays-ii/)| Intersection of Two Arrays II| -|[1275](https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/)| Find Winner on a Tic Tac Toe Game| -|[485](https://leetcode.com/problems/max-consecutive-ones/)| Max Consecutive Ones| -|[929](https://leetcode.com/problems/unique-email-addresses/)| Unique Email Addresses| -|[922](https://leetcode.com/problems/sort-array-by-parity-ii/)| Sort Array By Parity II| -|[463](https://leetcode.com/problems/island-perimeter/)| Island Perimeter| -|[70](https://leetcode.com/problems/climbing-stairs/)| Climbing Stairs| -|[543](https://leetcode.com/problems/diameter-of-binary-tree/)| Diameter of Binary Tree| -|[374](https://leetcode.com/problems/guess-number-higher-or-lower/)| Guess Number Higher or Lower| -|[496](https://leetcode.com/problems/next-greater-element-i/)| Next Greater Element I| -|[155](https://leetcode.com/problems/min-stack/)| Min Stack| -|[226](https://leetcode.com/problems/invert-binary-tree/)| Invert Binary Tree| -|[441](https://leetcode.com/problems/arranging-coins/)| Arranging Coins| -|[1413](https://leetcode.com/problems/minimum-value-to-get-positive-step-by-step-sum/)| Minimum Value to Get Positive Step by Step Sum| -|[203](https://leetcode.com/problems/remove-linked-list-elements/)| Remove Linked List Elements| -|[448](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/)| Find All Numbers Disappeared in an Array| -|[461](https://leetcode.com/problems/hamming-distance/)| Hamming Distance| -|[53](https://leetcode.com/problems/maximum-subarray/)| Maximum Subarray| -|[35](https://leetcode.com/problems/search-insert-position/)| Search Insert Position| -|[1217](https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/)| Minimum Cost to Move Chips to The Same Position| -|[563](https://leetcode.com/problems/binary-tree-tilt/)| Binary Tree Tilt| -|[1446](https://leetcode.com/problems/consecutive-characters/)| Consecutive Characters| -|[938](https://leetcode.com/problems/range-sum-of-bst/)| Range Sum of BST| -|[1200](https://leetcode.com/problems/minimum-absolute-difference/)| Minimum Absolute Difference| -|[231](https://leetcode.com/problems/power-of-two/)| Power of Two| -|[476](https://leetcode.com/problems/number-complement/)| Number Complement| -|[876](https://leetcode.com/problems/middle-of-the-linked-list/)| Middle of the Linked List| -|[997](https://leetcode.com/problems/find-the-town-judge/)| Find the Town Judge| -|[1009](https://leetcode.com/problems/complement-of-base-10-integer/)| Complement of Base 10 Integer| -|[67](https://leetcode.com/problems/add-binary/)| Add Binary| -|[290](https://leetcode.com/problems/word-pattern/)| Word Pattern| -|[605](https://leetcode.com/problems/can-place-flowers/)| Can Place Flowers| -|[520](https://leetcode.com/problems/detect-capital/)| Detect Capital| -|[941](https://leetcode.com/problems/valid-mountain-array/)| Valid Mountain Array| -|[389](https://leetcode.com/problems/find-the-difference/)| Find the Difference| -|[258](https://leetcode.com/problems/add-digits/)| Add Digits| -|[1108](https://leetcode.com/problems/defanging-an-ip-address/)| Defanging an IP Address| -|[1832](https://leetcode.com/problems/check-if-the-sentence-is-pangram/)| Check if the Sentence Is Pangram| -|[104](https://leetcode.com/problems/maximum-depth-of-binary-tree/)| Maximum Depth of Binary Tree| -|[136](https://leetcode.com/problems/single-number/)| Single Number| -|[171](https://leetcode.com/problems/excel-sheet-column-number/)| Excel Sheet Column Number| -|[228](https://leetcode.com/problems/summary-ranges/)| Summary Ranges| -|[338](https://leetcode.com/problems/counting-bits/)| Counting Bits| -|[392](https://leetcode.com/problems/is-subsequence/)| Is Subsequence| -|[21](https://leetcode.com/problems/merge-two-sorted-lists/)| Merge Two Sorted Lists| -|[141](https://leetcode.com/problems/linked-list-cycle/)| Linked List Cycle| -|[617](https://leetcode.com/problems/merge-two-binary-trees/)| Merge Two Binary Trees| -|[20](https://leetcode.com/problems/valid-parentheses/)| Valid Parentheses| -|[1351](https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix/)| Count Negative Numbers in a Sorted Matrix| -|[905](https://leetcode.com/problems/sort-array-by-parity/)| Sort Array By Parity| -|[344](https://leetcode.com/problems/reverse-string/)| Reverse String| -|[1460](https://leetcode.com/problems/make-two-arrays-equal-by-reversing-sub-arrays/)| Make Two Arrays Equal by Reversing Sub-arrays| -|[977](https://leetcode.com/problems/squares-of-a-sorted-array/)| Squares of a Sorted Array| -|[349](https://leetcode.com/problems/intersection-of-two-arrays/)| Intersection of Two Arrays| -|[1002](https://leetcode.com/problems/find-common-characters/)| Find Common Characters| -|[766](https://leetcode.com/problems/toeplitz-matrix/)| Toeplitz Matrix| -|[704](https://leetcode.com/problems/binary-search/)| Binary Search| -|[1160](https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/)| Find Words That Can Be Formed by Characters| -|[412](https://leetcode.com/problems/fizz-buzz/)| Fizz Buzz| -|[266](https://leetcode.com/problems/palindrome-permutation/)| Palindrome Permutation| -|[145](https://leetcode.com/problems/binary-tree-postorder-traversal/)| Binary Tree Postorder Traversal| -|[169](https://leetcode.com/problems/majority-element/)| Majority Element| -|[242](https://leetcode.com/problems/valid-anagram/)| Valid Anagram| -|[217](https://leetcode.com/problems/contains-duplicate/)| Contains Duplicate| -|[283](https://leetcode.com/problems/move-zeroes/)| Move Zeroes| -|[1260](https://leetcode.com/problems/shift-2d-grid/)| Shift 2D Grid| -|[700](https://leetcode.com/problems/search-in-a-binary-search-tree/)| Search in a Binary Search Tree| -|[844](https://leetcode.com/problems/backspace-string-compare/)| Backspace String Compare| -|[88](https://leetcode.com/problems/merge-sorted-array/)| Merge Sorted Array| -|[859](https://leetcode.com/problems/buddy-strings/)| Buddy Strings| -|[557](https://leetcode.com/problems/reverse-words-in-a-string-iii/)| Reverse Words in a String III| -|[976](https://leetcode.com/problems/largest-perimeter-triangle/)| Largest Perimeter Triangle| -|[219](https://leetcode.com/problems/contains-duplicate-ii/)| Contains Duplicate II| -|[1544](https://leetcode.com/problems/make-the-string-great/)| Make The String Great| -|[1323](https://leetcode.com/problems/maximum-69-number/)| Maximum 69 Number| -|[2325](https://leetcode.com/problems/decode-the-message/)| Decode the Message| -|[121](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/)| Best Time to Buy and Sell Stock| -|[1971](https://leetcode.com/problems/find-if-path-exists-in-graph/)| Find if Path Exists in Graph| -|[2389](https://leetcode.com/problems/longest-subsequence-with-limited-sum/)| Longest Subsequence With Limited Sum| -|[2073](https://leetcode.com/problems/time-needed-to-buy-tickets/)| Time Needed to Buy Tickets| -|[697](https://leetcode.com/problems/degree-of-an-array/)| Degree of an Array| -|[1071](https://leetcode.com/problems/greatest-common-divisor-of-strings/)| Greatest Common Divisor of Strings| -|[1470](https://leetcode.com/problems/shuffle-the-array/)| Shuffle the Array| -|[1523](https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/)| Count Odd Numbers in an Interval Range| -|[989](https://leetcode.com/problems/add-to-array-form-of-integer/)| Add to Array-Form of Integer| +## [Easy Problems](Easy.md) -## Medium -|LC #|Description| -|:-:|:-| -|[931](https://leetcode.com/problems/minimum-falling-path-sum/)| Minimum Falling Path Sum| -|[946](https://leetcode.com/problems/validate-stack-sequences/)| Validate Stack Sequences| -|[29](https://leetcode.com/problems/divide-two-integers/)| Divide Two Integers| -|[820](https://leetcode.com/problems/short-encoding-of-words/)| Short Encoding of Words| -|[1381](https://leetcode.com/problems/design-a-stack-with-increment-operation/)| Design a Stack With Increment Operation| -|[623](https://leetcode.com/problems/add-one-row-to-tree/)| Add One Row to Tree| -|[12](https://leetcode.com/problems/integer-to-roman/)| Integer to Roman| -|[1315](https://leetcode.com/problems/sum-of-nodes-with-even-valued-grandparent/)| Sum of Nodes with Even-Valued Grandparent| -|[1302](https://leetcode.com/problems/deepest-leaves-sum/)| Deepest Leaves Sum| -|[322](https://leetcode.com/problems/coin-change/)| Coin Change| -|[1305](https://leetcode.com/problems/all-elements-in-two-binary-search-trees/)| All Elements in Two Binary Search Trees| -|[1461](https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/)| Check If a String Contains All Binary Codes of Size K| -|[1721](https://leetcode.com/problems/swapping-nodes-in-a-linked-list/)| Swapping Nodes in a Linked List| -|[714](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/)| Best Time to Buy and Sell Stock with Transaction Fee| -|[478](https://leetcode.com/problems/generate-random-point-in-a-circle/)| Generate Random Point in a Circle| -|[208](https://leetcode.com/problems/implement-trie-prefix-tree/)| Implement Trie (Prefix Tree)| -|[376](https://leetcode.com/problems/wiggle-subsequence/)| Wiggle Subsequence| -|[38](https://leetcode.com/problems/count-and-say/)| Count and Say| -|[146](https://leetcode.com/problems/lru-cache/)| LRU Cache| -|[1583](https://leetcode.com/problems/count-unhappy-friends/)| Count Unhappy Friends| -|[729](https://leetcode.com/problems/my-calendar-i/)| My Calendar I| -|[841](https://leetcode.com/problems/keys-and-rooms/)| Keys And Rooms| -|[113](https://leetcode.com/problems/path-sum-ii/)| Path Sum II| -|[1398](https://leetcode.com/problems/design-underground-system/)| Design Underground System| -|[1797](https://leetcode.com/problems/design-authentication-manager/)| Design Authentication Manager| -|[1798](https://leetcode.com/problems/maximum-number-of-consecutive-values-you-can-make/)| Maximum Number of Consecutive Values You Can Make| -|[966](https://leetcode.com/problems/vowel-spellchecker/)| Vowel Spellchecker| -|[1689](https://leetcode.com/problems/partitioning-into-minimum-number-of-deci-binary-numbers/)| Partitioning Into Minimum Number Of Deci-Binary Numbers| -|[1764](https://leetcode.com/problems/form-array-by-concatenating-subarrays-of-another-array/)| Form Array by Concatenating Subarrays of Another Array| -|[923](https://leetcode.com/problems/3sum-with-multiplicity/)| 3Sum With Multiplicity| -|[417](https://leetcode.com/problems/pacific-atlantic-water-flow/)| Pacific Atlantic Water Flow| -|[916](https://leetcode.com/problems/word-subsets/)| Word Subsets| -|[5](https://leetcode.com/problems/longest-palindromic-substring/)| Longest Palindromic Substring| -|[647](https://leetcode.com/problems/palindromic-substrings/)| Palindromic Substrings| -|[971](https://leetcode.com/problems/flip-binary-tree-to-match-preorder-traversal/)| Flip Binary Tree To Match Preorder Traversal| -|[1726](https://leetcode.com/problems/tuple-with-same-product/)| Tuple with Same Product| -|[474](https://leetcode.com/problems/ones-and-zeroes/)| Ones and Zeroes| -|[1488](https://leetcode.com/problems/avoid-flood-in-the-city/)| Avoid Flood in The City| -|[947](https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/)| Most Stones Removed with Same Row or Column| -|[622](https://leetcode.com/problems/design-circular-queue/)| Design Circular Queue| -|[1670](https://leetcode.com/problems/design-front-middle-back-queue/)| Design Front Middle Back Queue| -|[494](https://leetcode.com/problems/target-sum/)| Target Sum| -|[17](https://leetcode.com/problems/letter-combinations-of-a-phone-number/)| Letter Combinations of a Phone Number| -|[638](https://leetcode.com/problems/shopping-offers/)| Shopping Offers| -|[667](https://leetcode.com/problems/beautiful-arrangement-ii/)| Beautiful Arrangement II| -|[650](https://leetcode.com/problems/2-keys-keyboard/)| 2 Keys Keyboard| -|[801](https://leetcode.com/problems/minimum-swaps-to-make-sequences-increasing/)| Minimum Swaps To Make Sequences Increasing| -|[341](https://leetcode.com/problems/flatten-nested-list-iterator/)| Flatten Nested List Iterator| -|[86](https://leetcode.com/problems/partition-list/)| Partition List| -|[91](https://leetcode.com/problems/decode-ways/)| Decode Ways| -|[62](https://leetcode.com/problems/unique-paths/)| Unique Paths| -|[1209](https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/)| Remove All Adjacent Duplicates in String II| -|[279](https://leetcode.com/problems/perfect-squares/)| Perfect Squares| -|[377](https://leetcode.com/problems/combination-sum-iv/)| Combination Sum IV| -|[120](https://leetcode.com/problems/triangle/)| Triangle| -|[554](https://leetcode.com/problems/brick-wall/)| Brick Wall| -|[48](https://leetcode.com/problems/rotate-image/)| Rotate Image| -|[935](https://leetcode.com/problems/knight-dialer/)| Knight Dialer| -|[740](https://leetcode.com/problems/delete-and-earn/)| Delete and Earn| -|[63](https://leetcode.com/problems/unique-paths-ii/)| Unique Paths II| -|[34](https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/)| Find First and Last Position of Element in Sorted Array| -|[970](https://leetcode.com/problems/powerful-integers/)| Powerful Integers| -|[665](https://leetcode.com/problems/non-decreasing-array/)| Non-decreasing Array| -|[1472](https://leetcode.com/problems/design-browser-history/)| Design Browser History| -|[109](https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/)| Convert Sorted List to Binary Search Tree| -|[583](https://leetcode.com/problems/delete-operation-for-two-strings/)| Delete Operation for Two Strings| -|[1423](https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/)| Maximum Points You Can Obtain from Cards| -|[304](https://leetcode.com/problems/range-sum-query-2d-immutable/)| Range Sum Query 2D - Immutable| -|[816](https://leetcode.com/problems/ambiguous-coordinates/)| Ambiguous Coordinates| -|[114](https://leetcode.com/problems/flatten-binary-tree-to-linked-list/)| Flatten Binary Tree to Linked List| -|[1048](https://leetcode.com/problems/longest-string-chain/)| Longest String Chain| -|[213](https://leetcode.com/problems/house-robber-ii/)| House Robber II| -|[462](https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/)| Minimum Moves to Equal Array Elements II| -|[890](https://leetcode.com/problems/find-and-replace-pattern/)| Find and Replace Pattern| -|[337](https://leetcode.com/problems/house-robber-iii/)| House Robber III| -|[921](https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/)| Minimum Add to Make Parentheses Valid| -|[1871](https://leetcode.com/problems/jump-game-vii/)| Jump Game VII| -|[150](https://leetcode.com/problems/evaluate-reverse-polish-notation/)| Evaluate Reverse Polish Notation| -|[318](https://leetcode.com/problems/maximum-product-of-word-lengths/)| Maximum Product of Word Lengths| -|[1695](https://leetcode.com/problems/maximum-erasure-value/)| Maximum Erasure Value| -|[1268](https://leetcode.com/problems/search-suggestions-system/)| Search Suggestions System| -|[695](https://leetcode.com/problems/max-area-of-island/)| Max Area of Island| -|[97](https://leetcode.com/problems/interleaving-string/)| Interleaving String| -|[1465](https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/)| Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts| -|[128](https://leetcode.com/problems/longest-consecutive-sequence/)| Longest Consecutive Sequence| -|[105](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/)| Construct Binary Tree from Preorder and Inorder Traversal| -|[1696](https://leetcode.com/problems/jump-game-vi/)| Jump Game VI| -|[698](https://leetcode.com/problems/partition-to-k-equal-sum-subsets/)| Partition to K Equal Sum Subsets| -|[22](https://leetcode.com/problems/generate-parentheses/)| Generate Parentheses| -|[795](https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/)| Number of Subarrays with Bounded Maximum| -|[118](https://leetcode.com/problems/pascals-triangle/)| Pascal's Triangle| -|[576](https://leetcode.com/problems/out-of-boundary-paths/)| Out of Boundary Paths| -|[684](https://leetcode.com/problems/redundant-connection/)| Redundant Connection| -|[1004](https://leetcode.com/problems/max-consecutive-ones-iii/)| Max Consecutive Ones III| -|[236](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/)| Lowest Common Ancestor of a Binary Tree| -|[89](https://leetcode.com/problems/gray-code/)| Gray Code| -|[378](https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/)| Kth Smallest Element in a Sorted Matrix| -|[718](https://leetcode.com/problems/maximum-length-of-repeated-subarray/)| Maximum Length of Repeated Subarray| -|[300](https://leetcode.com/problems/longest-increasing-subsequence/)| Longest Increasing Subsequence| -|[162](https://leetcode.com/problems/find-peak-element/)| Find Peak Element| -|[791](https://leetcode.com/problems/custom-sort-string/)| Custom Sort String| -|[611](https://leetcode.com/problems/valid-triangle-number/)| Valid Triangle Number| -|[235](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/)| Lowest Common Ancestor of a Binary Search Tree| -|[838](https://leetcode.com/problems/push-dominoes/)| Push Dominoes| -|[915](https://leetcode.com/problems/partition-array-into-disjoint-intervals/)| Partition Array into Disjoint Intervals| -|[814](https://leetcode.com/problems/binary-tree-pruning/)| Binary Tree Pruning| -|[90](https://leetcode.com/problems/subsets-ii/)| Subsets II| -|[877](https://leetcode.com/problems/stone-game/)| Stone Game| -|[429](https://leetcode.com/problems/n-ary-tree-level-order-traversal/)| N-ary Tree Level Order Traversal| -|[926](https://leetcode.com/problems/flip-string-to-monotone-increasing/)| Flip String to Monotone Increasing| -|[954](https://leetcode.com/problems/array-of-doubled-pairs/)| Array of Doubled Pairs| -|[49](https://leetcode.com/problems/group-anagrams/)| Group Anagrams| -|[73](https://leetcode.com/problems/set-matrix-zeroes/)| Set Matrix Zeroes| -|[1448](https://leetcode.com/problems/count-good-nodes-in-binary-tree/)| Count Good Nodes in Binary Tree| -|[36](https://leetcode.com/problems/valid-sudoku/)| Valid Sudoku| -|[153](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/)| Find Minimum in Rotated Sorted Array| -|[565](https://leetcode.com/problems/array-nesting/)| Array Nesting| -|[848](https://leetcode.com/problems/shifting-letters/)| Shifting Letters| -|[978](https://leetcode.com/problems/longest-turbulent-subarray/)| Longest Turbulent Subarray| -|[54](https://leetcode.com/problems/spiral-matrix/)| Spiral Matrix| -|[1239](https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/)| Maximum Length of a Concatenated String with Unique Characters| -|[725](https://leetcode.com/problems/split-linked-list-in-parts/)| Split Linked List in Parts| -|[473](https://leetcode.com/problems/matchsticks-to-square/)| Matchsticks to Square| -|[1143](https://leetcode.com/problems/longest-common-subsequence/)| Longest Common Subsequence| -|[55](https://leetcode.com/problems/jump-game/)| Jump Game| -|[442](https://leetcode.com/problems/find-all-duplicates-in-an-array/)| Find All Duplicates in an Array| -|[79](https://leetcode.com/problems/word-search/)| Word Search| -|[201](https://leetcode.com/problems/bitwise-and-of-numbers-range/)| Bitwise AND of Numbers Range| -|[1008](https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/)| Construct Binary Search Tree from Preorder Traversal| -|[309](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/)| Best Time to Buy and Sell Stock with Cooldown| -|[437](https://leetcode.com/problems/path-sum-iii/)| Path Sum III| -|[4511](https://leetcode.com/problems/sort-characters-by-frequency/)| Sort Characters By Frequency| -|[222](https://leetcode.com/problems/count-complete-tree-nodes/)| Count Complete Tree Nodes| -|[75](https://leetcode.com/problems/sort-colors/)| Sort Colors| -|[15](https://leetcode.com/problems/3sum/)| 3Sum| -|[994](https://leetcode.com/problems/rotting-oranges/)| Rotting Oranges| -|[430](https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/)| Flatten a Multilevel Doubly Linked List| -|[130](https://leetcode.com/problems/surrounded-regions/)| Surrounded Regions| -|[129](https://leetcode.com/problems/sum-root-to-leaf-numbers/)| Sum Root to Leaf Numbers| -|[260](https://leetcode.com/problems/single-number-iii/)| Single Number III| -|[43](https://leetcode.com/problems/multiply-strings/)| Multiply Strings| -|[96](https://leetcode.com/problems/unique-binary-search-trees/)| Unique Binary Search Trees| -|[122](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/)| Best Time to Buy and Sell Stock II| -|[739](https://leetcode.com/problems/daily-temperatures/)| Daily Temperatures| -|[368](https://leetcode.com/problems/largest-divisible-subset/)| Largest Divisible Subset| -|[540](https://leetcode.com/problems/single-element-in-a-sorted-array/)| Single Element in a Sorted Array| -|[106](https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/)| Construct Binary Tree from Inorder and Postorder Traversal| -|[450](https://leetcode.com/problems/delete-node-in-a-bst/)| Delete Node in a BST| -|[986](https://leetcode.com/problems/interval-list-intersections/)| Interval List Intersections| -|[238](https://leetcode.com/problems/product-of-array-except-self/)| Product of Array Except Self| -|[797](https://leetcode.com/problems/all-paths-from-source-to-target/)| All Paths From Source to Target| -|[721](https://leetcode.com/problems/accounts-merge/)| Accounts Merge| -|[198](https://leetcode.com/problems/house-robber/)| House Robber| -|[328](https://leetcode.com/problems/odd-even-linked-list/)| Odd Even Linked List| -|[152](https://leetcode.com/problems/maximum-product-subarray/)| Maximum Product Subarray| -|[1306](https://leetcode.com/problems/jump-game-iii/)| Jump Game III| -|[790](https://leetcode.com/problems/domino-and-tromino-tiling/)| Domino and Tromino Tiling| -|[416](https://leetcode.com/problems/partition-equal-subset-sum/)| Partition Equal Subset Sum| -|[310](https://leetcode.com/problems/minimum-height-trees/)| Minimum Height Trees| -|[221](https://leetcode.com/problems/maximal-square/)| Maximal Square| -|[394](https://leetcode.com/problems/decode-string/)| Decode String| -|[143](https://leetcode.com/problems/reorder-list/)| Reorder List| -|[210](https://leetcode.com/problems/course-schedule-ii/)| Course Schedule II| -|[56](https://leetcode.com/problems/merge-intervals/)| Merge Intervals| -|[227](https://leetcode.com/problems/basic-calculator-ii/)| Basic Calculator II| -|[973](https://leetcode.com/problems/k-closest-points-to-origin/)| K Closest Points to Origin| -|[116](https://leetcode.com/problems/populating-next-right-pointers-in-each-node/)| Populating Next Right Pointers in Each Node| -|[1015](https://leetcode.com/problems/smallest-integer-divisible-by-k/)| Smallest Integer Divisible by K| -|[1026](https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/)| Maximum Difference Between Node and Ancestor| -|[1010](https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/)| Pairs of Songs With Total Durations Divisible by 60| -|[131](https://leetcode.com/problems/palindrome-partitioning/)| Palindrome Partitioning| -|[382](https://leetcode.com/problems/linked-list-random-node/)| Linked List Random Node| -|[1041](https://leetcode.com/problems/robot-bounded-in-circle/)| Robot Bounded In Circle| -|[701](https://leetcode.com/problems/insert-into-a-binary-search-tree/)| Insert into a Binary Search Tree| -|[452](https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/)| Minimum Number of Arrows to Burst Balloons| -|[8](https://leetcode.com/problems/string-to-integer-atoi/)| String to Integer (atoi)| -|[849](https://leetcode.com/problems/maximize-distance-to-closest-person/)| Maximize Distance to Closest Person| -|[142](https://leetcode.com/problems/linked-list-cycle-ii/)| Linked List Cycle II| -|[875](https://leetcode.com/problems/koko-eating-bananas/)| Koko Eating Bananas| -|[134](https://leetcode.com/problems/gas-station/)| Gas Station| -|[1291](https://leetcode.com/problems/sequential-digits/)| Sequential Digits| -|[421](https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/)| Maximum XOR of Two Numbers in an Array| -|[211](https://leetcode.com/problems/design-add-and-search-words-data-structure/)| Design Add and Search Words Data Structure| -|[438](https://leetcode.com/problems/find-all-anagrams-in-a-string/)| Find All Anagrams in a String| -|[454](https://leetcode.com/problems/4sum-ii/)| 4Sum II| -|[525](https://leetcode.com/problems/contiguous-array/)| Contiguous Array| -|[80](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/)| Remove Duplicates from Sorted Array II| -|[532](https://leetcode.com/problems/k-diff-pairs-in-an-array/)| K-diff Pairs in an Array| -|[560](https://leetcode.com/problems/subarray-sum-equals-k/)| Subarray Sum Equals K| -|[567](https://leetcode.com/problems/permutation-in-string/)| Permutation in String| -|[78](https://leetcode.com/problems/subsets/)| Subsets| -|[39](https://leetcode.com/problems/combination-sum/)| Combination Sum| -|[402](https://leetcode.com/problems/remove-k-digits/)| Remove K Digits| -|[133](https://leetcode.com/problems/clone-graph/)| Clone Graph| -|[148](https://leetcode.com/problems/sort-list/)| Sort List| -|[662](https://leetcode.com/problems/maximum-width-of-binary-tree/)| Maximum Width of Binary Tree| -|[413](https://leetcode.com/problems/arithmetic-slices/)| Arithmetic Slices| -|[799](https://leetcode.com/problems/champagne-tower/)| Champagne Tower| -|[82](https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/)| Remove Duplicates from Sorted List II| -|[61](https://leetcode.com/problems/rotate-list/)| Rotate List| -|[138](https://leetcode.com/problems/copy-list-with-random-pointer/)| Copy List with Random Pointer| -|[71](https://leetcode.com/problems/simplify-path/)| Simplify Path| -|[1249](https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/)| Minimum Remove to Make Valid Parentheses| -|[856](https://leetcode.com/problems/score-of-parentheses/)| Score of Parentheses| -|[316](https://leetcode.com/problems/remove-duplicate-letters/)| Remove Duplicate Letters| -|[763](https://leetcode.com/problems/partition-labels/)| Partition Labels| -|[1663](https://leetcode.com/problems/smallest-string-with-a-given-numeric-value/)| Smallest String With A Given Numeric Value| -|[991](https://leetcode.com/problems/broken-calculator/)| Broken Calculator| -|[881](https://leetcode.com/problems/boats-to-save-people/)| Boats to Save People| -|[1024](https://leetcode.com/problems/two-city-scheduling/)| Two City Scheduling| -|[81](https://leetcode.com/problems/search-in-rotated-sorted-array-ii/)| Search in Rotated Sorted Array II| -|[287](https://leetcode.com/problems/find-the-duplicate-number/)| Find the Duplicate Number| -|[74](https://leetcode.com/problems/search-a-2d-matrix/)| Search a 2D Matrix| -|[11](https://leetcode.com/problems/container-with-most-water/)| Container With Most Water| -|[538](https://leetcode.com/problems/convert-bst-to-greater-tree/)| Convert BST to Greater Tree| -|[230](https://leetcode.com/problems/kth-smallest-element-in-a-bst/)| Kth Smallest Element in a BST| -|[284](https://leetcode.com/problems/peeking-iterator/)| Peeking Iterator| -|[216](https://leetcode.com/problems/combination-sum-iii/)| Combination Sum III| -|[47](https://leetcode.com/problems/permutations-ii/)| Permutations II| -|[117](https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/)| Populating Next Right Pointers in Each Node II| -|[743](https://leetcode.com/problems/network-delay-time/)| Network Delay Time| -|[474](https://leetcode.com/problems/ones-and-zeroes/)| Ones and Zeroes| -|[167](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/)| Two Sum II - Input Array Is Sorted| -|[3](https://leetcode.com/problems/longest-substring-without-repeating-characters/)| Longest Substring Without Repeating Characters| -|[1658](https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/)| Minimum Operations to Reduce X to Zero| -|[215](https://leetcode.com/problems/kth-largest-element-in-an-array/)| Kth Largest Element in an Array| -|[1570](https://leetcode.com/problems/dot-product-of-two-sparse-vectors/)| Dot Product of Two Sparse Vectors| -|[199](https://leetcode.com/problems/binary-tree-right-side-view/)| Binary Tree Right Side View| -|[92](https://leetcode.com/problems/reverse-linked-list-ii/)| Reverse Linked List II| -|[307](https://leetcode.com/problems/range-sum-query-mutable/)| Range Sum Query - Mutable| -|[240](https://leetcode.com/problems/search-a-2d-matrix-ii/)| Search a 2D Matrix II| -|[1457](https://leetcode.com/problems/pseudo-palindromic-paths-in-a-binary-tree/)| Pseudo-Palindromic Paths in a Binary Tree| -|[1770](https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/)| Maximum Score from Performing Multiplication Operations| -|[985](https://leetcode.com/problems/sum-of-even-numbers-after-queries/)| Sum of Even Numbers After Queries| -|[1680](https://leetcode.com/problems/concatenation-of-consecutive-binary-numbers/)| Concatenation of Consecutive Binary Numbers| -|[990](https://leetcode.com/problems/satisfiability-of-equality-equations/)| Satisfiability of Equality Equations| -|[658](https://leetcode.com/problems/find-k-closest-elements/description/)| Find K Closest Elements| -|[1578](https://leetcode.com/problems/minimum-time-to-make-rope-colorful/description/)| Minimum Time to Make Rope Colorful| -|[16](https://leetcode.com/problems/3sum-closest/description/)| 3Sum Closest| -|[334](https://leetcode.com/problems/increasing-triplet-subsequence/)| Increasing Triplet Subsequence| -|[2095](https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/)| Delete the Middle Node of a Linked List| -|[1662](https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/)| Check If Two String Arrays are Equivalent| -|[523](https://leetcode.com/problems/continuous-subarray-sum/)| Continuous Subarray Sum| -|[835](https://leetcode.com/problems/image-overlap/)| Image Overlap| -|[433](https://leetcode.com/problems/minimum-genetic-mutation/)| Minimum Genetic Mutation| -|[1926](https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/)| Nearest Exit from Entrance in Maze| -|[2225](https://leetcode.com/problems/find-players-with-zero-or-one-losses/)| Find Players With Zero or One Losses| -|[380](https://leetcode.com/problems/insert-delete-getrandom-o1/)| Insert Delete GetRandom O(1)| -|[1207](https://leetcode.com/problems/unique-number-of-occurrences/)| Unique Number of Occurrences| -|[45](https://leetcode.com/problems/jump-game-ii/)| Jump Game II| -|[1014](https://leetcode.com/problems/best-sightseeing-pair/)| Best Sightseeing Pair| -|[886](https://leetcode.com/problems/possible-bipartition/)| Possible Bipartition| -|[2279](https://leetcode.com/problems/maximum-bags-with-full-capacity-of-rocks/)| Maximum Bags With Full Capacity of Rocks| -|[343](https://leetcode.com/problems/integer-break/)| Integer Break| -|[256](https://leetcode.com/problems/paint-house/)| Paint House| -|[487](https://leetcode.com/problems/max-consecutive-ones-ii/)| Max Consecutive Ones II| -|[1746](https://leetcode.com/problems/maximum-subarray-sum-after-one-operation/)| Maximum Subarray Sum After One Operation| -|[1230](https://leetcode.com/problems/toss-strange-coins/)| Toss Strange Coins| -|[2498](https://leetcode.com/problems/frog-jump-ii/)| Frog Jump II| -|[2244](https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/)| Minimum Rounds to Complete All Tasks| -|[1749](https://leetcode.com/problems/maximum-absolute-sum-of-any-subarray/)| Maximum Absolute Sum of Any Subarray| -|[2186](https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram-ii/)| Minimum Number of Steps to Make Two Strings Anagram II| -|[2414](https://leetcode.com/problems/length-of-the-longest-alphabetical-continuous-substring/)| Length of the Longest Alphabetical Continuous Substring| -|[1519](https://leetcode.com/problems/number-of-nodes-in-the-sub-tree-with-the-same-label/)| Number of Nodes in the Sub-Tree With the Same Label| -|[1061](https://leetcode.com/problems/lexicographically-smallest-equivalent-string/)| Lexicographically Smallest Equivalent String| -|[1314](https://leetcode.com/problems/matrix-block-sum/)| Matrix Block Sum| -|[57](https://leetcode.com/problems/insert-interval/)| Insert Interval| -|[974](https://leetcode.com/problems/subarray-sums-divisible-by-k/)| Subarray Sums Divisible by K| -|[491](https://leetcode.com/problems/non-decreasing-subsequences/)| Non-decreasing Subsequences| -|[2359](https://leetcode.com/problems/find-closest-node-to-given-two-nodes/)| Find Closest Node to Given Two Nodes| -|[909](https://leetcode.com/problems/snakes-and-ladders/)| Snakes and Ladders| -|[787](https://leetcode.com/problems/cheapest-flights-within-k-stops/)| Cheapest Flights Within K Stops| -|[6](https://leetcode.com/problems/zigzag-conversion/)| Zigzag Conversion| -|[904](https://leetcode.com/problems/fruit-into-baskets/)| Fruit Into Baskets| -|[1162](https://leetcode.com/problems/as-far-from-land-as-possible/)| As Far from Land as Possible| -|[2477](https://leetcode.com/problems/minimum-fuel-cost-to-report-to-the-capital/)| Minimum Fuel Cost to Report to the Capital| -|[1129](https://leetcode.com/problems/shortest-path-with-alternating-colors/)| Shortest Path with Alternating Colors| +## [Medium Problems](Medium.md) -## Hard -|LC #|Description| -|:-:|:-| -|[354](https://leetcode.com/problems/russian-doll-envelopes/)| Russian Doll Envelopes| -|[936](https://leetcode.com/problems/stamping-the-sequence/)| Stamping The Sequence| -|[32](https://leetcode.com/problems/longest-valid-parentheses/)| Longest Valid Parentheses| -|[1559](https://leetcode.com/problems/detect-cycles-in-2d-grid/)| Detect Cycles in 2D Grid| -|[329](https://leetcode.com/problems/longest-increasing-path-in-a-matrix/)| Longest Increasing Path in a Matrix| -|[1192](https://leetcode.com/problems/critical-connections-in-a-network/)| Critical Connections in a Network| -|[980](https://leetcode.com/problems/unique-paths-iii/)| Unique Paths III| -|[745](https://leetcode.com/problems/prefix-and-suffix-search/)| Prefix and Suffix Search| -|[630](https://leetcode.com/problems/course-schedule-iii/)| Course Schedule III| -|[65](https://leetcode.com/problems/valid-number/)| Valid Number| -|[968](https://leetcode.com/problems/binary-tree-cameras/)| Binary Tree Cameras| -|[1473](https://leetcode.com/problems/paint-house-iii/)| Paint House III| -|[51](https://leetcode.com/problems/n-queens/)| N-Queens| -|[52](https://leetcode.com/problems/n-queens-ii/)| N-Queens II| -|[778](https://leetcode.com/problems/swim-in-rising-water/)| Swim in Rising Water| -|[315](https://leetcode.com/problems/count-of-smaller-numbers-after-self/)| Count of Smaller Numbers After Self| -|[135](https://leetcode.com/problems/candy/)| Candy| -|[927](https://leetcode.com/problems/three-equal-parts/)| Three Equal Parts| -|[25](https://leetcode.com/problems/reverse-nodes-in-k-group/)| Reverse Nodes in k-Group| -|[233](https://leetcode.com/problems/number-of-digit-one/)| Number of Digit One| -|[42](https://leetcode.com/problems/trapping-rain-water/)| Trapping Rain Water| -|[132](https://leetcode.com/problems/palindrome-partitioning-ii/)| Palindrome Partitioning II| -|[546](https://leetcode.com/problems/remove-boxes/)| Remove Boxes| -|[37](https://leetcode.com/problems/sudoku-solver/)| Sudoku Solver| -|[850](https://leetcode.com/problems/rectangle-area-ii/)| Rectangle Area II| -|[330](https://leetcode.com/problems/patching-array//)| Patching Array| -|[899](https://leetcode.com/problems/orderly-queue/)| Orderly Queue| -|[224](https://leetcode.com/problems/basic-calculator/)| Basic Calculator| -|[782](https://leetcode.com/problems/transform-to-chessboard/)| Transform to Chessboard| -|[174](https://leetcode.com/problems/dungeon-game/)| Dungeon Game| -|[123](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/)| Best Time to Buy and Sell Stock III| -|[154](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/)| Find Minimum in Rotated Sorted Array II| -|[668](https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/)| Kth Smallest Number in Multiplication Table| -|[952](https://leetcode.com/problems/largest-component-size-by-common-factor/)| Largest Component Size by Common Factor| -|[85](https://leetcode.com/problems/maximal-rectangle/)| Maximal Rectangle| -|[1032](https://leetcode.com/problems/stream-of-characters/)| Stream of Characters| -|[878](https://leetcode.com/problems/nth-magical-number/)| Nth Magical Number| -|[902](https://leetcode.com/problems/numbers-at-most-n-given-digit-set/)| Numbers At Most N Given Digit Set| -|[1463](https://leetcode.com/problems/cherry-pickup-ii/)| Cherry Pickup II| -|[1345](https://leetcode.com/problems/jump-game-iv/)| Jump Game IV| -|[1510](https://leetcode.com/problems/stone-game-iv/)| Stone Game IV| -|[127](https://leetcode.com/problems/word-ladder/)| Word Ladder| -|[410](https://leetcode.com/problems/split-array-largest-sum/)| Split Array Largest Sum| -|[629](https://leetcode.com/problems/k-inverse-pairs-array/)| K Inverse Pairs Array| -|[1074](https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/)| Number of Submatrices That Sum to Target| -|[1531](https://leetcode.com/problems/string-compression-ii/)| String Compression II| -|[1335](https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/)| Minimum Difficulty of a Job Schedule| -|[76](https://leetcode.com/problems/minimum-window-substring/)| Minimum Window Substring| -|[2136](https://leetcode.com/problems/earliest-possible-day-of-full-bloom/)| Earliest Possible Day of Full Bloom| -|[2193](https://leetcode.com/problems/minimum-number-of-moves-to-make-palindrome/)| Minimum Number of Moves to Make Palindrome| -|[1235](https://leetcode.com/problems/maximum-profit-in-job-scheduling/)| Maximum Profit in Job Scheduling| -|[446](https://leetcode.com/problems/arithmetic-slices-ii-subsequence/)| Arithmetic Slices II - Subsequence| -|[124](https://leetcode.com/problems/binary-tree-maximum-path-sum/)| Binary Tree Maximum Path Sum| -|[600](https://leetcode.com/problems/non-negative-integers-without-consecutive-ones/)| Non-negative Integers without Consecutive Ones| -|[72](https://leetcode.com/problems/edit-distance/)| Edit Distance| -|[1340](https://leetcode.com/problems/jump-game-v/)| Jump Game V| -|[403](https://leetcode.com/problems/frog-jump/)| Frog Jump| -|[188](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/)| Best Time to Buy and Sell Stock IV| -|[149](https://leetcode.com/problems/max-points-on-a-line/)| Max Points on a Line| -|[140](https://leetcode.com/problems/word-break-ii/)| Word Break II| -|[1289](https://leetcode.com/problems/minimum-falling-path-sum-ii/)| Minimum Falling Path Sum II| -|[2246](https://leetcode.com/problems/longest-path-with-different-adjacent-characters/)| Longest Path With Different Adjacent Characters| -|[2421](https://leetcode.com/problems/number-of-good-paths/)| Number of Good Paths| -|[472](https://leetcode.com/problems/concatenated-words/description/)| Concatenated Words| +## [Hard Problems](Hard.md)