├── CODE_OF_CONDUCT.md ├── Contest.go ├── LICENSE ├── Problems ├── 1009. Complement of Base 10 Integer │ └── 1009. Complement of Base 10 Integer.go ├── 1015. Smallest Integer Divisible by K │ └── 1015. Smallest Integer Divisible by K.go ├── 1017. Convert to Base -2 │ └── 1017. Convert to Base -2.go ├── 1021. Remove Outermost Parentheses │ └── 1021. Remove Outermost Parentheses.go ├── 1024. Video Stitching │ └── 1024. Video Stitching.go ├── 1031. Maximum Sum of Two Non-Overlapping Subarrays │ └── 1031. Maximum Sum of Two Non-Overlapping Subarrays.go ├── 1033. Moving Stones Until Consecutive │ └── 1033. Moving Stones Until Consecutive.go ├── 1040. Moving Stones Until Consecutive II │ └── 1040. Moving Stones Until Consecutive II.go ├── 1057. Campus Bikes │ └── 1057. Campus Bikes.go ├── 1066. Campus Bikes II │ └── 1066. Campus Bikes II.go ├── 1073. Adding Two Negabinary Numbers │ └── 1073. Adding Two Negabinary Numbers.go ├── 1086. High Five │ └── 1086. High Five.go ├── 1093. Statistics from a Large Sample │ └── 1093. Statistics from a Large Sample.go ├── 1103. Distribute Candies to People │ └── 1103. Distribute Candies to People.go ├── 1130. Minimum Cost Tree From Leaf Values │ └── 1130. Minimum Cost Tree From Leaf Values.go ├── 1151. Minimum Swaps to Group All 1's Together │ └── Minimum Swaps to Group All 1's Together.go ├── 1153. String Transforms Into Another String │ └── 1153. String Transforms Into Another String.go ├── 1169. Invalid Transactions │ └── 1169. Invalid Trasactions.go ├── 1175. Prime Arrangements │ └── 1175. Prime Arrangements.go ├── 1178. Number of Valid Words for Each Puzzle │ └── 1178. Number of Valid Words for Each Puzzle.go ├── 1201. Ugly Number III │ └── 1201. Ugly Number III.go ├── 1218. Longest Arithmetic Subsequence of Given Difference │ └── 1218. Longest Arithmetic Subsequence of Given Difference.go ├── 1220. Count Vowels Permutation │ └── 1220. Count Vowels Permutation.go ├── 1223. Dice Roll Simulation │ └── 1223. Dice Roll Simulation.go ├── 1224. Maximum Equal Frequency │ └── 1224. Maximum Equal Frequency.go ├── 1238. Circular Permutation in Binary Representation │ └── 1238. Circular Permutation in Binary Representation.go ├── 1250. Check If It Is a Good Array │ └── 1250. Check If It Is a Good Array.go ├── 1253. Reconstruct a 2-Row Binary Matrix │ └── 1253. Reconstruct a 2-Row Binary Matrix.go ├── 126. Word Ladder II │ └── 126. Word Ladder II.go ├── 1262. Greatest Sum Divisible by Three │ └── 1262. Greatest Sum Divisible by Three.go ├── 1263. Minimum Moves to Move a Box to Their Target Location │ └── 1263. Minimum Moves to Move a Box to Their Target Location.go ├── 1269. Number of Ways to Stay In the Same Place After Some Steps │ └── 1269. Number of Ways to Stay In the Same Place After Some Steps.go ├── 127. Word Ladder │ └── 127. Word Ladder.go ├── 1278. Palindrome Partitioning III │ └── 1278. Palindrome Partitioning III.go ├── 128. Longest Consecutive Sequence │ └── 128. Longest Consecutive Sequence.go ├── 1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix │ └── 1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix.go ├── 1286. Iterator for Combination │ └── 1286. Iterator for Combination.go ├── 1289. Minimum Falling Path Sum II │ └── 1289. Minimum Falling Path Sum II.go ├── 1291. Sequential Digits │ └── 1291. Sequential Digits.go ├── 1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold │ └── 1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold.go ├── 1293. Shortest Path in a Grid with Obstacles Elimination │ └── 1293. Shortest Path in a Grid with Obstacles Elimination.go ├── 1297. Maximum Number of Occurrences of a Substring │ └── 1297. Maximum Number of Occurrences of a Substring.go ├── 1298. Maximum Candies You Can Get from Boxes │ └── 1298. Maximum Candies You Can Get from Boxes.go ├── 130. Surrounded Regions │ └── 130. Surrounded Regions.go ├── 1300. Sum of Mutated Array Closest to Target │ └── 1300. Sum of Mutated Array Closest to Target.go ├── 1301. Number of Paths with Max Score │ └── 1301. Number of Paths with Max Score.go ├── 1307. Verbal Arithmetic Puzzle │ └── 1307. Verbal Arithmetic Puzzle.go ├── 131. Palindrome Partitioning │ └── 131. Palindrome Partitioning.go ├── 1310. XOR Queries of a Subarray │ └── 1310. XOR Queries of a Subarray.go ├── 1311. Get Watched Videos by Your Friends │ └── 1311. Get Watched Videos by Your Friends.go ├── 1312. Minimum Insertion Steps to Make a String Palindrome │ └── 1312. Minimum Insertion Steps to Make a String Palindrome.go ├── 1314. Matrix Block Sum │ └── 1314. Matrix Blcok Sum.go ├── 1315. Sum of Nodes with Even-Valued Grandparent │ └── 1315. Sum of Nodes with Even-Valued Grandparent.go ├── 1316. Distinct Echo Substrings │ └── 1316. Distinct Echo Substrings.go ├── 1318. Minimum Flips to Make a OR b Equal to c │ └── 1318. Minimum Flips to Make a OR b Equal to c.go ├── 1319. Number of Operations to Make Network Connected │ └── 1319. Number of Operations to Make Network Connected.go ├── 132. Palindrome Partitioning II │ └── 132. Palindrome Partitioning II.go ├── 1320. Minimum Distance to Type a Word Using Two Fingers │ └── 1320. Minimum Distance to Type a Word Using Two Fingers.go ├── 1325. Delete Leaves With a Given Value │ └── 1325. Delete Leaves With a Given Value.go ├── 1326. Minimum Number of Taps to Open to Water a Garden │ └── 1326. Minimum Number of Taps to Open to Water a Garden.go ├── 1328. Break a Palindrome │ └── 1328. Break a Palindrome.go ├── 1329. Sort the Matrix Diagonally │ └── 1329. Sort the Matrix Diagonally.go ├── 1330. Reverse Subarray To Maximize Array Value │ └── 1330. Reverse Subarray To Maximize Array Value.go ├── 1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance │ └── 1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance.go ├── 1335. Minimum Difficulty of a Job Schedule │ └── 1335. Minimum Difficulty of a Job Schedule.go ├── 1339. Maximum Product of Splitted Binary Tree │ └── 1339. Maximum Product of Splitted Binary Tree.go ├── 1340. Jump Game V │ └── 1340. Jump Game V.go ├── 1342. Number of Steps to Reduce a Number to Zero │ └── 1342. Number of Steps to Reduce a Number to Zero.go ├── 1344. Angle Between Hands of a Clock │ └── 1344. Angle Between Hands of a Clock.go ├── 1345. Jump Game IV │ └── 1345. Jump Game IV.go ├── 1349. Maximum Students Taking Exam │ └── 1349. Maximum Students Taking Exam.go ├── 1352. Product of the Last K Numbers │ └── 1352. Product of the Last K Numbers.go ├── 1353. Maximum Number of Events That Can Be Attended │ └── 1353. Maximum Number of Events That Can Be Attended.go ├── 1354. Construct Target Array With Multiple Sums │ └── 1354. Construct Target Arrays With Multiple Sums.go ├── 1358. Number of Substrings Containing All Three Characters │ └── 1358. Number of Substrings Containing All Three Characters.go ├── 1359. Count All Valid Pickup and Delivery Options │ └── 1359. Count All Valid Pickup and Delivery Options.go ├── 1366. Rank Teams by Votes │ └── 1366. Rank Teams by Votes.go ├── 1368. Minimum Cost to Make at Least One Valid Path in a Grid │ └── 1368. Minimum Cost to Make at Least One Valid Path in a Grid.go ├── 1373. Maximum Sum BST in Binary Tree │ └── 1373. Maximu Sum BST in Binary Tree.go ├── 1383. Maximum Performance of a Team │ └── 1383. Maximu, Performance of a Team.go ├── 1388. Pizza WIth 3n Slices │ └── 1388. Pizza With 3n Slices.go ├── 1391. Check if There is a Valid Path in a Grid │ └── 1391. Check if There is a Valid Path in a Grid.go ├── 1392. Longest Happy Prefix │ └── 1392. Longest Happy Prefix.go ├── 1400. Construct K Palindrome Strings │ └── 1400. Construct K Palindrome Strings.go ├── 1401. Circle and Rectangle Overlapping │ └── 1401. Circle and Rectangle Overlapping.go ├── 1402. Reducing Dishes │ └── 1402. Reducing Dishes.go ├── 1404. Number of Steps to Reduce a Number in Binary Representation to One │ └── 1404. Number of Steps to Reduce a Number in Binary Representation to One.go ├── 1405. Longest Happy String │ └── 1405. Longest Happy String.go ├── 1406. Stone Game III │ └── 1406. Stone Game III.go ├── 1411. Number of Ways to Paint N * 3 Grid │ └── 1411. Number of Ways to Paint N * 3 Grid.go ├── 1419. Minimu Number of Frogs Croaking │ └── 1419. Minimum Number of Frogs Croaking.go ├── 1420. Build Array Where You Can FInd the Maximum Exactly K Comparisons │ └── 1420. Build Array Where You Can FInd The Maximum Exactly K Comparisons.go ├── 1424. Diagonal Traversal II │ └── 1424. Diagonal Traversal II.go ├── 1434. Number of Ways to Wear Different Hats to Each Other │ └── 1434. Number of Ways to Wear Different Hats to Each Other.go ├── 1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit │ └── 1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit.go ├── 149. Max Points on a Line │ └── 149. Max Points on a Line.go ├── 166. Fraction to Recurring Decimal │ └── 166. Fraction to Recurring Decimal.go ├── 17. Letter Combinations of a Phone Number │ └── 17. Letter Combinations of a Phone Number.go ├── 174. Dungeon Game │ └── 174. Dungeon Game.go ├── 189. Rotate Array │ └── 189. Rotate Array.go ├── 202. Happy Number │ └── 202. Happy Number.go ├── 206. Reverse Linked List │ └── 206. Reverse LInked List.go ├── 215. Kth Largest Element in an Array │ └── 215. Kth Largest Element in an Array.go ├── 223. Rectangle Area │ └── 223. Rectangle Area.go ├── 23. Merge k Sorted Lists │ └── 23. Merge k Sorted Lists.go ├── 233. Number of Digit One │ └── 233. Number of Digit One.go ├── 264. Ugly Number II │ └── 264. Ugly Number II.go ├── 287. Find the Duplicate Number │ └── 287. Find the Duplicate Number.go ├── 300. Longest Increasing Subsequence │ └── 300. Longest Increasing Subsequence.go ├── 31. Next Permutation │ └── 31. Next Permutation.go ├── 312. Burst Balloons │ └── 312. Burst Balloons.go ├── 329. Longest Increasing Path │ └── 329. Longest Increasing Path.go ├── 335. Self Crossing │ └── 335. Self Crossing.go ├── 365. Water and Jug Problem │ └── 365. Water and Jug Problem.go ├── 368. Largest Divisble Subset │ └── 368. Largest Divisble Subset.go ├── 369. Plus One Linked List │ └── Plus One Linked List.go ├── 375. Guess Number Higher or Lower II │ └── 375. Guess Number Higher or Lower II.go ├── 396. Rotate Function │ └── 396. Rotate Function.go ├── 40. Combination Sum II │ └── 40. Combination Sum II.go ├── 40. Permutations II │ └── 40. Permutations II.go ├── 400. Nth Digit │ └── 400. Nth Digit.go ├── 446. Arithmetic Slices II - Subsequene │ └── 446. Arithmetic Subsequence II - Subsequence.go ├── 458. Poor Pigs │ └── 458. Poor Pigs.go ├── 474. Ones and Zeroes │ └── 474. Ones and Zeroes.go ├── 483. Smallest Good Base │ └── 483. Smallest Good Base.go ├── 498. Diagonal Traversal │ └── 498. Diagonal Traversal.go ├── 514. Freedom Trail │ └── 514. Freedom Trail.go ├── 517. Super Washing Machines │ └── 517. Super Washing Machines.go ├── 518. Coin Change 2 │ └── 518. Coin Change 2.go ├── 523. Continuous Subarray Sum │ └── 523. Continuous Subarray Sum.go ├── 546. Remove Boxes │ └── 546. Remove Boxes.go ├── 567. Permutation in String │ └── 567. Permutation in String.go ├── 576. Out of Boundary Paths │ └── 576. Out of Boundary Paths.go ├── 593. Valid Square │ └── 593. Valid Square.go ├── 60. Permutation Sequence │ └── 60. Permutation Sequence.go ├── 634. Find the Derangement of An Array │ └── 634. Find the Derangement of An Array.go ├── 664. Strange Printer │ └── 664. Strange Printer.go ├── 67. Add Binary │ └── 67. Add BInary.go ├── 670. Maximum Swap │ └── 670. Maximum Swap.go ├── 678. Valid Parenthesis String │ └── 678. Valid Parenthesis String.go ├── 727. Minimum Window Subsequence │ └── 727. Minimum Window Subsequence.go ├── 744. Find Smallest Letter Greater Than Target │ └── 744. Find Smallest Letter Greater Than Target.go ├── 753. Cracking the Safe │ └── 753. Cracking the Safe.go ├── 754. Reach a Number │ └── 754. Reach a Number.go ├── 765. Couples Holding Hands │ └── 765. Couples Holding Hands.go ├── 775. Global and Local Inversions │ └── 775. Global and Local Inversions.go ├── 780. Reaching Points │ └── 780. Reaching Points.go ├── 789. Escape The Ghosts │ └── 789. Escape The Ghosts.go ├── 805. Split Array With Same Average │ └── 805. Split Array With Same Average.go ├── 810. Chalkboard XOR Game │ └── 810. Chalkboard XOR Game.go ├── 813. Largest Sum of Averages │ └── 813. Largest Sum of Averages.go ├── 828. Count Unique Characters of All Substrings of a Given String │ └── 828. Count Unique Character of All Substrings of a Given String.go ├── 829. Consecutive Numbers Sum │ └── 829. Consecutive Numbers Sum.go ├── 836. Rectangle Overlap │ └── 836. Rectangle Overlap.go ├── 837. New 21 Game │ └── 837. New 21 Game.go ├── 847. Shortest Path Visiting All Nodes │ └── 847. Shortest Path Visiting All Nodes.go ├── 858. Mirror Reflection │ └── 858. Mirror Reflection.go ├── 861. Score After Flipping Matrix │ └── 861. Score After Flipping Matrix.go ├── 864. Shortest Path to Get All Keys │ └── 864. Shortest Path to Get All Keys.go ├── 869. Reordered Power of 2 │ └── 869. Reordered Power of 2.go ├── 887. Super Egg Drop │ └── 887. Super Egg Drop.go ├── 89. Gray Code │ └── 89. Gray Code.go ├── 891. Sum of Subsequence Widths │ └── 891. Sum of Subsequence Widths.go ├── 899. Orderly Queue │ └── 899. Orderly Queue.go ├── 902. Numbers At Most N Given Digit Set │ └── 902. Numbers At Most N Given Digit Set.go ├── 903. Valid Permutations for DI Sequence │ └── 903. Valid Permutations for DI Sequence.go ├── 906. Super Palindromes │ └── 906. Super Palindromes.go ├── 910. Smallest Range II │ └── 910. Smallest Range II.go ├── 913. Cat and Mouse │ └── 913. Cat and Mouse.go ├── 914. X of a Kind in a Deck of Cards │ └── 914. X of a Kind in a Deck of Cards.go ├── 924. Minimize Malware Spread │ └── 924. Minimize Malware Spread.go ├── 927. Three Equal Parts │ └── 927. Three Equal Parts.go ├── 935. Knight Dialer │ └── 935. Knight Dialer.go ├── 943. Find the Shortest Superstring │ └── 943. Find the Shortest Superstring.go ├── 947. Most Stones Removed with Same Row or Column │ └── 947. Most Stones Removed with Same Row or Column.go ├── 949. Largest Time for Given Digits │ └── 949. Largest Time for Given Digits.go ├── 956. Tallest Billboard │ └── 956. Tallest Billboard.go ├── 959. Regions Cut By Slashes │ └── 959. Regions Cut By Slashes.go ├── 964. Least Operators to Express Number │ └── 964. Least Operators to Express Number.go ├── 972. Equal Rational Numbers │ └── 972. Equal Rational Numbers.go ├── 973. K Closest Points to Origin │ └── 973. K Closest Points to Origin.go ├── 984. String Without AAA or BBB │ └── 984. String Without AAA or BBB.go ├── 990. Satisfiability of Equality Equations │ └── 990. Satisfiability of Equality Equations.go ├── 991. Broken Calculator │ └── 991. Broken Calculator.go └── 994. Rotting Oranges │ └── 994. Rotting Oranges.go ├── README.md └── Utils └── LCDS.go /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at weezyin@hotmail.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /Contest.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "container/list" 5 | ) 6 | 7 | func longestSubarray(nums []int, limit int) int { 8 | res := 1 9 | n := len(nums) 10 | mn := list.New() 11 | mx := list.New() 12 | mn.PushBack(0) 13 | mx.PushBack(0) 14 | l := 0 15 | r := 1 16 | for r < n { 17 | cur := nums[r] 18 | for mn.Len() > 0 && nums[mn.Back().Value.(int)] >= cur { 19 | mn.Remove(mn.Back()) 20 | } 21 | for mx.Len() > 0 && nums[mx.Back().Value.(int)] <= cur { 22 | mx.Remove(mx.Back()) 23 | } 24 | mn.PushBack(r) 25 | mx.PushBack(r) 26 | for nums[mx.Front().Value.(int)]-nums[mn.Front().Value.(int)] > limit { 27 | l++ 28 | for mx.Front().Value.(int) < l { 29 | mx.Remove(mx.Front()) 30 | } 31 | for mn.Front().Value.(int) < l { 32 | mn.Remove(mn.Front()) 33 | } 34 | } 35 | res = max(res, r-l+1) 36 | r++ 37 | } 38 | return res 39 | } 40 | 41 | func main() { 42 | longestSubarray([]int{8, 2, 4, 7}, 4) 43 | } 44 | 45 | func abs(a int) int { 46 | if a < 0 { 47 | return -a 48 | } 49 | return a 50 | } 51 | 52 | func max(a, b int) int { 53 | if a > b { 54 | return a 55 | } 56 | return b 57 | } 58 | 59 | func min(a, b int) int { 60 | if a > b { 61 | return b 62 | } 63 | return a 64 | } 65 | 66 | func gcd(a, b int) int { 67 | if b == 0 { 68 | return a 69 | } 70 | return gcd(b, a%b) 71 | } 72 | 73 | func twodarray(m, n int) [][]int { 74 | res := make([][]int, m) 75 | for i := range res { 76 | res[i] = make([]int, n) 77 | } 78 | return res 79 | } 80 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Shawn Yin 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Problems/1009. Complement of Base 10 Integer/1009. Complement of Base 10 Integer.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func bitwiseComplement(N int) int { 4 | xor := 1 5 | for xor < N { 6 | xor = (xor << 1) + 1 7 | } 8 | return N ^ xor 9 | } 10 | -------------------------------------------------------------------------------- /Problems/1015. Smallest Integer Divisible by K/1015. Smallest Integer Divisible by K.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func smallestRepunitDivByK(K int) int { 4 | if K%2 == 0 || K%5 == 0 { 5 | return -1 6 | } 7 | //the last digit is one and the multiple of 2 or 5 will never end with 1 8 | r := 0 9 | //the possible length must be within K 10 | //because there are only K-1 remainder, from length 1 to N, there must be a repeat remainder 11 | //and the remainder start to appear in circle 12 | //because currR = (prevR*10+1)%K 13 | for i := 1; i <= K; i++ { 14 | r = (r*10 + 1) % K 15 | if r == 0 { 16 | return i 17 | } 18 | } 19 | return -1 20 | } 21 | -------------------------------------------------------------------------------- /Problems/1017. Convert to Base -2/1017. Convert to Base -2.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "strconv" 4 | 5 | func baseNeg2(N int) string { 6 | res := "" 7 | for N > 0 { 8 | c := strconv.Itoa(N & 1) 9 | res = res + string(c) 10 | N = -(N >> 1) 11 | } 12 | if len(res) == 0 { 13 | return "0" 14 | } else { 15 | return reverse(res) 16 | } 17 | } 18 | 19 | func base2(N int) string { 20 | res := "" 21 | for N > 0 { 22 | c := strconv.Itoa(N & 1) 23 | res = res + string(c) 24 | N >>= 1 25 | } 26 | if len(res) == 0 { 27 | return "0" 28 | } else { 29 | return reverse(res) 30 | } 31 | } 32 | 33 | func reverse(s string) string { 34 | chars := []byte(s) 35 | for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { 36 | chars[i], chars[j] = chars[j], chars[i] 37 | } 38 | return string(chars) 39 | } 40 | -------------------------------------------------------------------------------- /Problems/1021. Remove Outermost Parentheses/1021. Remove Outermost Parentheses.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func removeOuterParentheses(S string) string { 4 | res := "" 5 | cur := 0 6 | for i := 0; i < len(S); i++ { 7 | if S[i] == ')' { 8 | cur-- 9 | } 10 | if cur != 0 { 11 | res += S[i : i+1] 12 | } 13 | if S[i] == '(' { 14 | cur++ 15 | } 16 | } 17 | return res 18 | } 19 | -------------------------------------------------------------------------------- /Problems/1024. Video Stitching/1024. Video Stitching.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "sort" 4 | 5 | func videoStitching(clips [][]int, T int) int { 6 | sort.Slice(clips, func(i, j int) bool { 7 | if clips[i][0] == clips[j][0] { 8 | return clips[j][1] < clips[i][1] 9 | } else { 10 | return clips[i][0] < clips[j][0] 11 | } 12 | }) 13 | if clips[0][0] > 0 { 14 | return -1 15 | } 16 | cur := 0 17 | end := clips[0][1] 18 | for i := range clips { 19 | cur++ 20 | if end >= T { 21 | return cur 22 | } 23 | nextEnd := end 24 | for j := i + 1; j < len(clips); j++ { 25 | if clips[j][0] <= end && clips[j][1] > nextEnd { 26 | nextEnd = clips[j][1] 27 | i = j 28 | } 29 | } 30 | if nextEnd == end { 31 | return -1 32 | } 33 | i-- 34 | end = nextEnd 35 | } 36 | return -1 37 | } 38 | -------------------------------------------------------------------------------- /Problems/1031. Maximum Sum of Two Non-Overlapping Subarrays/1031. Maximum Sum of Two Non-Overlapping Subarrays.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func maxSumTwoNoOverlap(A []int, L, M int) int { 4 | prefix := make([]int, len(A)+1) 5 | for i := 1; i < len(prefix); i++ { 6 | prefix[i] = prefix[i-1] + A[i-1] 7 | } 8 | return max(find(prefix, L, M), find(prefix, M, L)) 9 | } 10 | 11 | func find(prefix []int, L, M int) int { 12 | maxL := 0 13 | maxTotal := 0 14 | for i := L + M; i < len(prefix); i++ { 15 | //fix M length subarray at the last M elements of current subarray 16 | //L might be just on the left of M, or may be several step more to the left 17 | maxL = max(maxL, prefix[i-M]-prefix[i-M-L]) 18 | maxTotal = max(maxTotal, maxL+prefix[i]-prefix[i-M]) 19 | } 20 | return maxTotal 21 | } 22 | 23 | func max(a, b int) int { 24 | if a > b { 25 | return a 26 | } 27 | return b 28 | } 29 | -------------------------------------------------------------------------------- /Problems/1033. Moving Stones Until Consecutive/1033. Moving Stones Until Consecutive.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "math" 5 | "sort" 6 | ) 7 | 8 | func numMovesStones(a int, b int, c int) []int { 9 | arr := []int{a, b, c} 10 | sort.Ints(arr) 11 | if arr[2]-arr[0] == 2 { 12 | return []int{2, 2} 13 | } 14 | dist1 := arr[2] - arr[1] 15 | dist2 := arr[1] - arr[0] 16 | min := 1 17 | max := dist1 + dist2 - 2 18 | if math.Min(float64(dist1), float64(dist2)) <= float64(2) { 19 | //e.g. 2,3,6; 2,4,6 20 | min = 1 21 | } else { 22 | min = 2 23 | } 24 | return []int{min, max} 25 | } 26 | -------------------------------------------------------------------------------- /Problems/1040. Moving Stones Until Consecutive II/1040. Moving Stones Until Consecutive II.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "math" 5 | "sort" 6 | ) 7 | 8 | func numMovesStonesII(stones []int) []int { 9 | sort.Ints(stones) 10 | // Upper bound: 11 | // 1, move the first stone A[0] to A[n-1]-n+1 12 | // the total number between new left bound and A[1] is the steps to take 13 | // A[n-1]-n+1-A[1]+1 14 | // 2, or move the last stone A[n-1] to A[0]+n-1 15 | // the total number between new right bound and A[n-2] is the steps to take 16 | // A[n-2]-(A[0]+n-1)+1 17 | // 18 | // Lower bound: 19 | // Sliding window size of len(stones), find vacancy in the current window, and the number of vacancy is the number 20 | // of steps 21 | // Edge Case: A[j]-A[i]==n-2 && j-i+1==n-1 22 | // e.g. 1,2,3,4,10: we need to move 1 to 6, then 10 to 5 23 | n := len(stones) 24 | i := 0 25 | min := float64(n) 26 | max := 0 27 | if stones[n-1]-n+1-stones[1]+1 < stones[n-2]-stones[0]-n+2 { 28 | max = stones[n-2] - stones[0] - n + 2 29 | } else { 30 | max = stones[n-1] - stones[1] - n + 2 31 | } 32 | for j := 0; j < n; j++ { 33 | for stones[j]-stones[i] >= n { 34 | i++ 35 | } 36 | if stones[j]-stones[i] == n-2 && j-i == n-2 { 37 | min = math.Min(min, float64(2)) 38 | } else { 39 | min = math.Min(min, float64(n-(j-i+1))) 40 | } 41 | } 42 | return []int{int(min), max} 43 | } 44 | -------------------------------------------------------------------------------- /Problems/1057. Campus Bikes/1057. Campus Bikes.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "container/heap" 5 | "math" 6 | ) 7 | 8 | type Assignment struct { 9 | worker int 10 | bike int 11 | distance float64 12 | } 13 | type MinHeap []Assignment 14 | 15 | func (pq MinHeap) Len() int { 16 | return len(pq) 17 | } 18 | 19 | func (pq MinHeap) Less(i, j int) bool { 20 | if pq[i].distance == pq[j].distance { 21 | if pq[i].worker == pq[j].worker { 22 | return pq[i].bike < pq[j].bike 23 | } 24 | return pq[i].worker < pq[j].worker 25 | } 26 | return pq[i].distance < pq[j].distance 27 | } 28 | 29 | func (pq MinHeap) Swap(i, j int) { 30 | pq[i], pq[j] = pq[j], pq[i] 31 | } 32 | 33 | func (pq *MinHeap) Push(x interface{}) { 34 | *pq = append(*pq, x.(Assignment)) 35 | } 36 | 37 | func (pq *MinHeap) Pop() interface{} { 38 | x := (*pq)[len(*pq)-1] 39 | *pq = (*pq)[0 : len(*pq)-1] 40 | return x 41 | } 42 | 43 | func assignBikes(workers [][]int, bikes [][]int) []int { 44 | mh := MinHeap{} 45 | l := len(workers) 46 | b := len(bikes) 47 | for i := 0; i < l; i++ { 48 | for j := 0; j < b; j++ { 49 | dist := math.Abs(float64(workers[i][0]-bikes[j][0])) + math.Abs(float64(workers[i][1]-bikes[j][1])) 50 | cur := Assignment{worker: i, bike: j, distance: dist} 51 | heap.Push(&mh, cur) 52 | } 53 | } 54 | usedWorkers := make([]bool, l) 55 | usedBikes := make([]bool, b) 56 | res := make([]int, l) 57 | for mh.Len() > 0 { 58 | top := heap.Pop(&mh).(Assignment) 59 | if !usedBikes[top.bike] && !usedWorkers[top.worker] { 60 | res[top.worker] = top.bike 61 | usedWorkers[top.worker] = true 62 | usedBikes[top.bike] = true 63 | } 64 | } 65 | return res 66 | } 67 | -------------------------------------------------------------------------------- /Problems/1066. Campus Bikes II/1066. Campus Bikes II.go: -------------------------------------------------------------------------------- 1 | package _066__Campus_Bikes_II 2 | -------------------------------------------------------------------------------- /Problems/1073. Adding Two Negabinary Numbers/1073. Adding Two Negabinary Numbers.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func addNegabinary(a []int, b []int) []int { 4 | i := len(a) - 1 5 | j := len(b) - 1 6 | res := make([]int, 0) 7 | carry := 0 8 | for i >= 0 || j >= 0 || carry != 0 { 9 | if i >= 0 && a[i] == 1 { 10 | carry += 1 11 | } 12 | if j >= 0 && b[j] == 1 { 13 | carry += 1 14 | } 15 | res = append(res, carry&1) 16 | //if the current digit is 2 then, it equals to add -1 to the next digit 17 | carry = -(carry >> 1) 18 | i-- 19 | j-- 20 | } 21 | reverse(res) 22 | for len(res) > 1 && res[0] == 0 { 23 | //there might be leading zero in this situation 24 | //e.g. [1,0,1] + [1,1,1,1] = [0,0,0,0] 25 | res = res[1:] 26 | } 27 | return res 28 | } 29 | 30 | func reverse(arr []int) []int { 31 | i := 0 32 | j := len(arr) - 1 33 | for i < j { 34 | arr[i], arr[j] = arr[j], arr[i] 35 | i++ 36 | j-- 37 | } 38 | return arr 39 | } 40 | -------------------------------------------------------------------------------- /Problems/1086. High Five/1086. High Five.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "sort" 4 | 5 | func highFive(items [][]int) [][]int { 6 | res := make([][]int, 0) 7 | sort.Slice(items, func(a int, b int) bool { 8 | if items[a][0] != items[b][0] { 9 | return items[a][0] < items[b][0] 10 | } else { 11 | return items[a][1] >= items[b][1] 12 | } 13 | }) 14 | prev := 0 15 | sum := 0 16 | cnt := 0 17 | for _, scores := range items { 18 | if scores[0] != prev { 19 | cnt = 0 20 | prev = scores[0] 21 | sum = 0 22 | } 23 | sum += scores[1] 24 | cnt++ 25 | if cnt == 5 { 26 | avg := sum / cnt 27 | res = append(res, []int{scores[0], avg}) 28 | } 29 | } 30 | return res 31 | } 32 | -------------------------------------------------------------------------------- /Problems/1093. Statistics from a Large Sample/1093. Statistics from a Large Sample.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "math" 5 | ) 6 | 7 | func sampleStats(count []int) []float64 { 8 | res := make([]float64, 5, 5) 9 | var sum = float64(0) 10 | var cnt = 0 11 | var min = float64(math.MaxInt32) 12 | var max = float64(0) 13 | maxCount := 0 14 | mode := -1 15 | for i := 0; i <= 255; i++ { 16 | if count[i] != 0 { 17 | min = math.Min(min, float64(i)) 18 | max = math.Max(max, float64(i)) 19 | sum += float64(i * count[i]) 20 | cnt += count[i] 21 | if count[i] > maxCount { 22 | mode = i 23 | maxCount = count[i] 24 | } 25 | } 26 | } 27 | res[0] = min 28 | res[1] = max 29 | res[2] = sum / float64(cnt) 30 | res[4] = float64(mode) 31 | half := cnt / 2 32 | if cnt%2 == 1 { 33 | halfCnt := 0 34 | for i := 0; i <= 255; i++ { 35 | halfCnt += count[i] 36 | if halfCnt > half { 37 | res[3] = float64(i) 38 | break 39 | } 40 | } 41 | } else { 42 | halfCnt := 0 43 | l := 0 44 | r := 0 45 | for i := 0; i <= 255; i++ { 46 | if halfCnt < half { 47 | l = i 48 | } 49 | halfCnt += count[i] 50 | if halfCnt > half { 51 | r = i 52 | break 53 | } 54 | } 55 | res[3] = float64(l+r) / float64(2) 56 | } 57 | return res 58 | } 59 | -------------------------------------------------------------------------------- /Problems/1103. Distribute Candies to People/1103. Distribute Candies to People.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func distributeCandies(candies int, num_people int) []int { 4 | res := make([]int, num_people, num_people) 5 | i := 1 6 | for candies > i { 7 | res[(i-1)%num_people] += i 8 | candies -= i 9 | i++ 10 | } 11 | res[(i-1)%num_people] += candies 12 | return res 13 | } 14 | -------------------------------------------------------------------------------- /Problems/1130. Minimum Cost Tree From Leaf Values/1130. Minimum Cost Tree From Leaf Values.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "math" 4 | 5 | func mctFromLeafValues(arr []int) int { 6 | n := len(arr) 7 | mx := make([][]int, n) 8 | for i := range mx { 9 | mx[i] = make([]int, n) 10 | } 11 | for i := range arr { 12 | cur := arr[i] 13 | for j := i; j < n; j++ { 14 | if arr[j] > cur { 15 | cur = arr[j] 16 | } 17 | mx[i][j] = cur 18 | } 19 | } 20 | dp := make([][]int, n) 21 | for i := range dp { 22 | dp[i] = make([]int, n) 23 | } 24 | for j := 1; j < n; j++ { 25 | for i := j - 1; i >= 0; i-- { 26 | if i+1 == j { 27 | dp[i][j] = arr[i] * arr[j] 28 | } else { 29 | dp[i][j] = math.MaxInt32 30 | for k := i; k < j; k++ { 31 | dp[i][j] = Min(dp[i][j], dp[i][k]+dp[k+1][j]+mx[i][k]*mx[k+1][j]) 32 | } 33 | } 34 | } 35 | } 36 | return dp[0][n-1] 37 | } 38 | 39 | func Min(a, b int) int { 40 | if a < b { 41 | return a 42 | } 43 | return b 44 | } 45 | -------------------------------------------------------------------------------- /Problems/1151. Minimum Swaps to Group All 1's Together/Minimum Swaps to Group All 1's Together.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "math" 4 | 5 | func minSwaps(data []int) int { 6 | cnt := 0 7 | for _, i := range data { 8 | if i == 1 { 9 | cnt++ 10 | } 11 | } 12 | l := 0 13 | r := 0 14 | curr := 0 15 | for ; r < cnt-1; r++ { 16 | if data[r] == 1 { 17 | curr++ 18 | } 19 | } 20 | res := math.MaxInt32 21 | for r < len(data) { 22 | if data[r] == 1 { 23 | curr++ 24 | } 25 | temp := cnt - curr 26 | if temp < res { 27 | res = temp 28 | } 29 | if data[l] == 1 { 30 | curr-- 31 | } 32 | l++ 33 | r++ 34 | } 35 | return res 36 | } 37 | -------------------------------------------------------------------------------- /Problems/1153. String Transforms Into Another String/1153. String Transforms Into Another String.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func canConvert(str1 string, str2 string) bool { 4 | if str1 == str2 { 5 | return true 6 | } 7 | mapping := make(map[byte]byte, 0) 8 | if len(str1) != len(str2) { 9 | return false 10 | } 11 | set := make(map[byte]bool, 0) 12 | for i := range str1 { 13 | if c, ok := mapping[str1[i]]; ok { 14 | if c != str2[i] { 15 | return false 16 | } 17 | } else { 18 | mapping[str1[i]] = str2[i] 19 | set[str2[i]] = true 20 | } 21 | } 22 | //note: we cannot just return true here 23 | //corner case: 24 | //"abcdefghijklmnopqrstuvwxyz" 25 | //"bcdefghijklmnopqrstuvwxyza" 26 | //we need to ensure that the total mapping characters appeared in str2 is at most 25 27 | //otherwise for the above example, we will run into a situation that 28 | //when we map the last character, there is another already transformed character in str1 to be changed 29 | //e.g. str1 = .....zz, str2 = .....za, the last step will transform two z at the end 30 | return len(set) <= 25 31 | } 32 | 33 | func main() { 34 | canConvert( 35 | "abcdefghijklmnopqrstuvwxyz", 36 | "bcdefghijklmnopqrstuvwxyzq") 37 | } 38 | -------------------------------------------------------------------------------- /Problems/1169. Invalid Transactions/1169. Invalid Trasactions.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "strconv" 5 | "strings" 6 | ) 7 | 8 | func invalidTransactions(transactions []string) []string { 9 | res := make([]string, 0) 10 | tb := make(map[string]map[int]string) 11 | for i := range transactions { 12 | ss := strings.Split(transactions[i], ",") 13 | name := ss[0] 14 | time, _ := strconv.Atoi(ss[1]) 15 | location := ss[3] 16 | if _, ok := tb[name]; !ok { 17 | tb[name] = make(map[int]string) 18 | } 19 | if _, ok := tb[name][time]; ok { 20 | tb[name][time] = "xx" 21 | } else { 22 | tb[name][time] = location 23 | } 24 | } 25 | for i := range transactions { 26 | ss := strings.Split(transactions[i], ",") 27 | name := ss[0] 28 | time, _ := strconv.Atoi(ss[1]) 29 | amount, _ := strconv.Atoi(ss[2]) 30 | location := ss[3] 31 | if amount > 1000 { 32 | res = append(res, transactions[i]) 33 | continue 34 | } 35 | v := tb[name] 36 | added := false 37 | for j := time - 60; j < time+61; j++ { 38 | if added { 39 | break 40 | } 41 | if _, ok := v[j]; ok && j != time && v[j] != location { 42 | added = true 43 | res = append(res, transactions[i]) 44 | } 45 | if v[j] == "xx" && j == time { 46 | added = true 47 | res = append(res, transactions[i]) 48 | } 49 | } 50 | } 51 | return res 52 | } 53 | -------------------------------------------------------------------------------- /Problems/1175. Prime Arrangements/1175. Prime Arrangements.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func numPrimeArrangements(n int) int { 4 | mod := int(1e9 + 7) 5 | cnt := 0 6 | for i := 2; i <= n; i++ { 7 | if isPrime(i) { 8 | cnt++ 9 | } 10 | } 11 | np := n - cnt 12 | res := 1 13 | for i := 1; i <= np; i++ { 14 | res *= i 15 | res %= mod 16 | } 17 | for i := 1; i <= cnt; i++ { 18 | res *= i 19 | res %= mod 20 | } 21 | return res 22 | } 23 | 24 | func isPrime(n int) bool { 25 | for i := 2; i <= n/2; i++ { 26 | if n%i == 0 { 27 | return false 28 | } 29 | } 30 | return true 31 | } 32 | -------------------------------------------------------------------------------- /Problems/1178. Number of Valid Words for Each Puzzle/1178. Number of Valid Words for Each Puzzle.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func findNumOfValidWords(words []string, puzzles []string) []int { 4 | mp := make(map[int]int) 5 | for i := range words { 6 | c := 0 7 | for j := range words[i] { 8 | c |= 1 << uint(words[i][j]-'a') 9 | } 10 | mp[c]++ 11 | } 12 | res := make([]int, len(puzzles)) 13 | for i := range puzzles { 14 | cp := puzzles[i] 15 | cnt := 0 16 | for j := range cp { 17 | cnt |= 1 << uint(cp[j]-'a') 18 | } 19 | sub := cnt 20 | first := 1 << uint(cp[0]-'a') 21 | for sub != 0 { 22 | if sub&first == first { 23 | // make sure that words contain the first character of current puzzle 24 | res[i] += mp[sub] 25 | } 26 | sub = (sub - 1) & cnt //this will generate every subset of cnt! 27 | } 28 | } 29 | return res 30 | } 31 | -------------------------------------------------------------------------------- /Problems/1201. Ugly Number III/1201. Ugly Number III.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "math" 4 | 5 | /* 6 | Divisible by a or b or c, equals to 7 | divisible by a + divisible by b + divisible by c - divisible by lcm(a, b) - divisible by lcm(a, c) -divisible by lcm(b, c) + divisible by lcm(a,b,c) 8 | */ 9 | 10 | func nthUglyNumber(n int, a int, b int, c int) int { 11 | l := 1 12 | r := math.MaxInt32 13 | for l < r { 14 | m := l + (r-l)/2 15 | if count(a, b, c, m) < n { 16 | l = m + 1 17 | } else { 18 | r = m 19 | } 20 | } 21 | return l 22 | } 23 | 24 | func gcd(a, b int) int { 25 | if b == 0 { 26 | return a 27 | } 28 | return gcd(b, a%b) 29 | } 30 | 31 | func lcm(a, b int) int { 32 | return a * b / gcd(a, b) 33 | } 34 | 35 | func count(a, b, c, num int) int { 36 | return num/a + num/b + num/c - num/lcm(a, b) - num/lcm(a, c) - num/lcm(b, c) + num/lcm(c, lcm(a, b)) 37 | } 38 | -------------------------------------------------------------------------------- /Problems/1218. Longest Arithmetic Subsequence of Given Difference/1218. Longest Arithmetic Subsequence of Given Difference.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func longestSubsequence(arr []int, difference int) int { 4 | ht := make(map[int]int) 5 | max := 1 6 | for i := range arr { 7 | if num, ok := ht[arr[i]-difference]; ok { 8 | ht[arr[i]] = num + 1 9 | if ht[arr[i]] > max { 10 | max = ht[arr[i]] 11 | } 12 | } else { 13 | ht[arr[i]] = 1 14 | } 15 | } 16 | return max 17 | } 18 | -------------------------------------------------------------------------------- /Problems/1220. Count Vowels Permutation/1220. Count Vowels Permutation.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func countVowelPermutation(n int) int { 4 | ht := make(map[int][]int) 5 | ht[0] = []int{0, 1, 0, 0, 0} 6 | ht[1] = []int{1, 0, 1, 0, 0} 7 | ht[2] = []int{1, 1, 0, 1, 1} 8 | ht[3] = []int{0, 0, 1, 0, 1} 9 | ht[4] = []int{1, 0, 0, 0, 0} 10 | dp := make([][]int, n) 11 | mod := int(1e9) + 7 12 | for i := range dp { 13 | dp[i] = make([]int, 5) 14 | } 15 | for i := range dp[0] { 16 | dp[0][i] = 1 17 | } 18 | for i := 1; i < n; i++ { 19 | for j := 0; j < 5; j++ { 20 | for k := 0; k < 5; k++ { 21 | if ht[k][j] == 1 { 22 | dp[i][j] += dp[i-1][k] 23 | dp[i][j] %= mod 24 | } 25 | } 26 | } 27 | } 28 | res := 0 29 | for i := 0; i < 5; i++ { 30 | res += dp[n-1][i] 31 | res %= mod 32 | } 33 | return res 34 | } 35 | -------------------------------------------------------------------------------- /Problems/1223. Dice Roll Simulation/1223. Dice Roll Simulation.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "math" 4 | 5 | //dp[i][j] = number of results with i dices and the last number is j 6 | //two situation 7 | //1. i==rollMax[j]+1, e.g. i = 4, rollMax[0]=3, so 1111 is not allowed, then 1111 should be removed from the current result => dp[3][0]-=1 8 | //2. i>rollMax[j]+1, e.g. i = 4, rollMax[0]=2, then x111(except 1111) should be removed from the current result 9 | // which is dp[4][0] -= (dp[4-rollMax[0]]-1][0~5]-dp[4-rollMax[0]-1][0]) 10 | 11 | func dieSimulator(n int, rollMax []int) int { 12 | mod := int(math.Pow(10, 9)) + 7 13 | dp := make([][]int, n+1) 14 | for i := range dp { 15 | dp[i] = make([]int, 7) 16 | } 17 | for i := range dp[1] { 18 | dp[1][i] = 1 19 | } 20 | dp[1][6] = 6 //use dp[i][6] as sum of all results of i indices 21 | for i := 2; i <= n; i++ { 22 | sum := 0 23 | for j := 0; j <= 5; j++ { 24 | dp[i][j] = dp[i-1][6] 25 | if i == rollMax[j]+1 { 26 | dp[i][j] -= 1 27 | } else if i > rollMax[j]+1 { 28 | dp[i][j] -= dp[i-rollMax[j]-1][6] - dp[i-rollMax[j]-1][j] 29 | dp[i][j] = (dp[i][j] + mod) % mod 30 | } 31 | sum += dp[i][j] 32 | sum %= mod 33 | } 34 | dp[i][6] = sum 35 | } 36 | return dp[n][6] 37 | } 38 | -------------------------------------------------------------------------------- /Problems/1224. Maximum Equal Frequency/1224. Maximum Equal Frequency.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | //there are only two situations to update the result 4 | //1. [1,1,2,2,3], when i=3, frq(2)=2, 2*2==i+1, then update result to max(result, i+2) 5 | // means remove 3 6 | //2. [1,1,1,2,2,3], when i=4, frq(2)=2, 2*2==i, then update result to max(result, i+1) 7 | // means remove 1 8 | func maxEqualFreq(nums []int) int { 9 | cnt := make(map[int]int) //count of a number 10 | frq := make(map[int]int) //frequency of the counts 11 | res := 0 12 | for i := range nums { 13 | cnt[nums[i]] = cnt[nums[i]] + 1 14 | frq[cnt[nums[i]]] = frq[cnt[nums[i]]] + 1 15 | total := frq[cnt[nums[i]]] * cnt[nums[i]] 16 | if i == total { 17 | res = max(res, i+1) 18 | } else if total == i+1 && i != len(nums)-1 { 19 | //i cannot be the last index 20 | res = max(res, i+2) 21 | } 22 | } 23 | return res 24 | } 25 | 26 | func max(a, b int) int { 27 | if a > b { 28 | return a 29 | } 30 | return b 31 | } 32 | -------------------------------------------------------------------------------- /Problems/1238. Circular Permutation in Binary Representation/1238. Circular Permutation in Binary Representation.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func circularPermutation(n int, start int) []int { 4 | res := grayCode(n) 5 | i := 0 6 | for res[i] != start { 7 | i++ 8 | } 9 | rotate(i, res) 10 | return res 11 | } 12 | 13 | func grayCode(n int) []int { 14 | res := make([]int, 0, 0) 15 | res = append(res, 0) 16 | for i := 0; i < n; i++ { 17 | size := len(res) 18 | for j := size - 1; j >= 0; j-- { 19 | res = append(res, res[j]|1< 0 { 20 | upper-- 21 | res[0][i] = 1 22 | } else if lower > 0 { 23 | lower-- 24 | res[1][i] = 1 25 | } else { 26 | return make([][]int, 0) 27 | } 28 | } 29 | } 30 | if upper != 0 || lower != 0 { 31 | return make([][]int, 0) 32 | } 33 | return res 34 | } 35 | -------------------------------------------------------------------------------- /Problems/126. Word Ladder II/126. Word Ladder II.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | var set map[string]bool 4 | var graph map[string][]string 5 | var res [][]string 6 | var dist map[string]int 7 | 8 | func findLadders(beginWord string, endWord string, wordList []string) [][]string { 9 | set = make(map[string]bool) 10 | graph = make(map[string][]string) 11 | dist = make(map[string]int) 12 | for _, s := range wordList { 13 | set[s] = true 14 | } 15 | set[beginWord] = true 16 | if !set[endWord] { 17 | 18 | return res 19 | } 20 | buildGraph() 21 | reverseBFS(beginWord, endWord) 22 | dfs(&[]string{}, beginWord, endWord) 23 | return res 24 | } 25 | 26 | func dfs(temp *[]string, cur string, target string) { 27 | *temp = append(*temp, cur) 28 | if cur == target { 29 | var copy []string 30 | copy = append(copy, *temp...) 31 | res = append(res, copy) 32 | } else { 33 | if next, ok := graph[cur]; ok { 34 | for _, neighbor := range next { 35 | if dist[neighbor] == dist[cur]-1 { 36 | dfs(temp, neighbor, target) 37 | } 38 | } 39 | } 40 | } 41 | *temp = (*temp)[:len(*temp)-1] 42 | } 43 | 44 | func reverseBFS(begin string, end string) { 45 | queue := make([]string, 0) 46 | queue = append(queue, end) 47 | visited := map[string]bool{} 48 | visited[end] = true 49 | step := 0 50 | dist[end] = 0 51 | for len(queue) > 0 { 52 | size := len(queue) 53 | step++ 54 | for i := 0; i < size; i++ { 55 | cur := queue[i] 56 | for _, neighbor := range graph[cur] { 57 | if !visited[neighbor] { 58 | visited[neighbor] = true 59 | dist[neighbor] = step 60 | queue = append(queue, neighbor) 61 | } 62 | } 63 | } 64 | queue = queue[size:] 65 | } 66 | } 67 | 68 | func buildGraph() { 69 | for s := range set { 70 | next := make([]string, 0) 71 | for i := range s { 72 | for c := 'a'; c <= 'z'; c++ { 73 | if byte(c) != s[i] { 74 | neighbor := s[:i] + string(c) + s[i+1:] 75 | if set[neighbor] { 76 | next = append(next, neighbor) 77 | } 78 | } 79 | } 80 | } 81 | graph[s] = next 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /Problems/1262. Greatest Sum Divisible by Three/1262. Greatest Sum Divisible by Three.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func maxSumDivThree(nums []int) int { 4 | return maxSumDivK(nums, 3) 5 | } 6 | 7 | func maxSumDivK(nums []int, k int) int { 8 | if k == 0 { 9 | return -1 10 | } 11 | n := len(nums) 12 | dp := make([][]int, n) 13 | for i := range dp { 14 | dp[i] = make([]int, k) 15 | } 16 | //dp[i][j] is with 0-jth number, the max sum with mod k = i 17 | m := nums[0] % k 18 | dp[0][m] = nums[0] 19 | //dp[0][nums[0]%k] is the base case, in which case there is only one number with mod = nums[0]%k 20 | for j := 1; j < n; j++ { 21 | for i := range dp[j-1] { 22 | n := nums[j] + dp[j-1][i] 23 | dp[j][n%k] = max(n, dp[j][n%k]) //if we add the current number 24 | dp[j][i] = max(dp[j][i], dp[j-1][i]) //if we don't add current number 25 | } 26 | } 27 | return dp[len(nums)-1][0] 28 | } 29 | 30 | func maxSumDivK2(nums []int, k int) int { 31 | if k == 0 { 32 | return -1 33 | } 34 | dp := make([]int, k) 35 | //the max sum with mod 0 to k-1 36 | for _, v := range nums { 37 | //to prevent repeat addition of the same number 38 | temp := make([]int, 0) 39 | temp = append(temp, dp...) 40 | for i := range dp { 41 | n := v + temp[i] 42 | dp[n%k] = max(n, dp[n%k]) 43 | } 44 | } 45 | return dp[0] 46 | } 47 | 48 | func max(a, b int) int { 49 | if a > b { 50 | return a 51 | } 52 | return b 53 | } 54 | -------------------------------------------------------------------------------- /Problems/1263. Minimum Moves to Move a Box to Their Target Location/1263. Minimum Moves to Move a Box to Their Target Location.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "math" 5 | ) 6 | 7 | func minPushBox(grid [][]byte) int { 8 | mv := [5]int{0, 1, 0, -1, 0} 9 | res := math.MaxInt32 10 | m := len(grid) 11 | n := len(grid[0]) 12 | queue := make([]int, 0, m*n) 13 | mem := make(map[int]int) 14 | target, st, box := [2]int{}, [2]int{}, [2]int{} 15 | for i := 0; i < m; i++ { 16 | for j := 0; j < n; j++ { 17 | switch grid[i][j] { 18 | case 'B': 19 | box = [2]int{i, j} 20 | case 'T': 21 | target = [2]int{i, j} 22 | case 'S': 23 | st = [2]int{i, j} 24 | } 25 | } 26 | } 27 | start := encode(box[0], box[1], st[0], st[1]) 28 | queue = append(queue, start) 29 | mem[start] = 0 30 | for len(queue) > 0 { 31 | cur := queue[0] 32 | queue = queue[1:] 33 | if mem[cur] > res { 34 | continue 35 | } 36 | pos := decode(cur) 37 | if pos[0] == target[0] && pos[1] == target[1] { 38 | if mem[cur] < res { 39 | res = mem[cur] 40 | } 41 | continue 42 | } 43 | b := [2]int{pos[0], pos[1]} 44 | s := [2]int{pos[2], pos[3]} 45 | for i := 0; i < 4; i++ { 46 | sx := s[0] + mv[i] 47 | sy := s[1] + mv[i+1] 48 | if sx >= 0 && sx < m && sy >= 0 && sy < n && grid[sx][sy] != '#' { 49 | if sx == b[0] && sy == b[1] { 50 | //if the store keeper can move to the box position, check if the box can move one step further 51 | nbx := b[0] + mv[i] 52 | nby := b[1] + mv[i+1] 53 | if nbx >= 0 && nby >= 0 && nbx < m && nby < n && grid[nbx][nby] != '#' { 54 | newpos := encode(nbx, nby, sx, sy) 55 | if val, ok := mem[newpos]; ok && val <= mem[cur]+1 { 56 | continue 57 | } 58 | queue = append(queue, newpos) 59 | mem[newpos] = mem[cur] + 1 60 | } 61 | } else { 62 | //the store keeper move to other position, the number of steps shall not change 63 | newpos := encode(b[0], b[1], sx, sy) 64 | if val, ok := mem[newpos]; ok && val <= mem[cur] { 65 | continue 66 | } 67 | mem[newpos] = mem[cur] 68 | queue = append(queue, newpos) 69 | } 70 | } 71 | } 72 | } 73 | if res == math.MaxInt32 { 74 | return -1 75 | } else { 76 | return res 77 | } 78 | } 79 | 80 | func encode(bx int, by int, sx int, sy int) int { 81 | res := bx<<24 | by<<16 | sx<<8 | sy 82 | return res 83 | } 84 | 85 | func decode(state int) [4]int { 86 | res := [4]int{} 87 | res[0] = (state >> 24) & 0xff 88 | res[1] = (state >> 16) & 0xff 89 | res[2] = (state >> 8) & 0xff 90 | res[3] = (state) & 0xff 91 | return res 92 | } 93 | -------------------------------------------------------------------------------- /Problems/1269. Number of Ways to Stay In the Same Place After Some Steps/1269. Number of Ways to Stay In the Same Place After Some Steps.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func numWays(steps int, arrLen int) int { 4 | mod := int(1e9) + 7 5 | dp := make([]int, min(steps+1, arrLen)) 6 | dp[0] = 1 7 | for i := 0; i < steps; i++ { 8 | curr := make([]int, min(steps+1, arrLen)) 9 | for j := 0; j < len(curr); j++ { 10 | curr[j] = dp[j] 11 | if j+1 < len(curr) { 12 | curr[j] += dp[j+1] 13 | curr[j] %= mod 14 | } 15 | if j-1 >= 0 { 16 | curr[j] += dp[j-1] 17 | curr[j] %= mod 18 | } 19 | } 20 | dp = curr 21 | } 22 | return dp[0] 23 | } 24 | 25 | func min(a, b int) int { 26 | if a < b { 27 | return a 28 | } 29 | return b 30 | } 31 | -------------------------------------------------------------------------------- /Problems/127. Word Ladder/127. Word Ladder.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func ladderLength(beginWord string, endWord string, wordList []string) int { 4 | set := make(map[string]bool) 5 | for _, s := range wordList { 6 | set[s] = true 7 | } 8 | visited := make(map[string]bool) 9 | queue := make([]string, 0, len(wordList)) 10 | if beginWord == endWord { 11 | return 1 12 | } 13 | if !set[endWord] { 14 | return 0 15 | } 16 | queue = append(queue, beginWord) 17 | visited[beginWord] = true 18 | step := 1 19 | for len(queue) > 0 { 20 | size := len(queue) 21 | for i := 0; i < size; i++ { 22 | cur := queue[i] 23 | if cur == endWord { 24 | return step 25 | } 26 | next := nextWords(cur, set) 27 | for _, n := range next { 28 | if !visited[n] { 29 | queue = append(queue, n) 30 | visited[n] = true 31 | } 32 | } 33 | } 34 | queue = queue[size:] 35 | step++ 36 | } 37 | return 0 38 | } 39 | 40 | func nextWords(cur string, set map[string]bool) []string { 41 | var res []string 42 | for i := range cur { 43 | for c := 'a'; c <= 'z'; c++ { 44 | if cur[i] == byte(c) { 45 | continue 46 | } 47 | next := cur[:i] + string(c) + cur[i+1:] 48 | if set[next] { 49 | res = append(res, next) 50 | } 51 | } 52 | } 53 | return res 54 | } 55 | 56 | /* 57 | The default type for character values is rune. That means, if you don’t declare a type explicitly when declaring a variable with a character value, then Go will infer the type as rune - 58 | 59 | var firstLetter = 'A' // Type inferred as `rune` (Default type for character values) 60 | You can create a byte variable by explicitly specifying the type - 61 | 62 | var lastLetter byte = 'Z' 63 | */ 64 | -------------------------------------------------------------------------------- /Problems/1278. Palindrome Partitioning III/1278. Palindrome Partitioning III.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "math" 4 | 5 | var mem map[string]int 6 | 7 | func palindromePartition(s string, k int) int { 8 | mem = make(map[string]int) 9 | dp := [100][101]int{} 10 | for idx := range s { 11 | dp[0][idx+1] = helper(s[0 : idx+1]) 12 | } 13 | 14 | for i := 1; i < k; i++ { 15 | for j := i; j <= len(s); j++ { 16 | cur := math.MaxInt32 17 | for p := j; p >= i; p-- { 18 | //cut at p-1 19 | cur = min(cur, dp[i-1][p-1]+helper(s[p-1:j])) 20 | } 21 | dp[i][j] = cur 22 | } 23 | } 24 | //dp[i][j] = the min steps to cut into i palindromes with length = j 25 | return dp[k-1][len(s)] 26 | } 27 | 28 | func min(a int, b int) int { 29 | if a > b { 30 | return b 31 | } else { 32 | return a 33 | } 34 | } 35 | 36 | func helper(str string) int { 37 | if len(str) == 0 { 38 | return 0 39 | } 40 | if val, ok := mem[str]; ok { 41 | return val 42 | } 43 | l := 0 44 | r := len(str) 45 | res := 0 46 | for l < r { 47 | if str[l] != str[r] { 48 | res++ 49 | } 50 | l++ 51 | r-- 52 | } 53 | mem[str] = res 54 | return res 55 | } 56 | -------------------------------------------------------------------------------- /Problems/128. Longest Consecutive Sequence/128. Longest Consecutive Sequence.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func longestConsecutive(nums []int) int { 4 | cnt := make(map[int]int) 5 | res := 0 6 | for i := range nums { 7 | if _, ok := cnt[nums[i]]; !ok { 8 | l := cnt[nums[i]-1] 9 | r := cnt[nums[i]+1] 10 | sum := l + r + 1 11 | res = max(res, sum) 12 | cnt[nums[i]] = sum 13 | //only the boundary of a consecutive sequence need to be updated 14 | cnt[nums[i]-l] = sum 15 | cnt[nums[i]+r] = sum 16 | } 17 | } 18 | return res 19 | } 20 | 21 | func max(a, b int) int { 22 | if a > b { 23 | return a 24 | } 25 | return b 26 | } 27 | -------------------------------------------------------------------------------- /Problems/1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix/1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "strconv" 4 | 5 | func minFlips(mat [][]int) int { 6 | //brute force BFS for every status 7 | //each status has m*n options to flip 8 | m := len(mat) 9 | n := len(mat[0]) 10 | queue := make([]string, 0, 0) 11 | set := make(map[string]bool) 12 | target := "" 13 | temp := "" 14 | for i := 0; i < m; i++ { 15 | for j := 0; j < n; j++ { 16 | temp = temp + strconv.Itoa(mat[i][j]) 17 | target = target + "0" 18 | } 19 | } 20 | queue = append(queue, string(temp)) 21 | set[string(temp)] = true 22 | step := 0 23 | for len(queue) > 0 { 24 | size := len(queue) 25 | for t := 0; t < size; t++ { 26 | cur := queue[t] 27 | if cur == target { 28 | return step 29 | } 30 | for i := 0; i < len(cur); i++ { 31 | next := []byte(cur) 32 | next[i] = flip(next[i]) 33 | x := i / n 34 | y := i % n 35 | if x > 0 { 36 | next[i-n] = flip(next[i-n]) 37 | } 38 | if x < m-1 { 39 | next[i+n] = flip(next[i+n]) 40 | } 41 | if y > 0 { 42 | next[i-1] = flip(next[i-1]) 43 | } 44 | if y < n-1 { 45 | next[i+1] = flip(next[i+1]) 46 | } 47 | nextstr := string(next) 48 | if !set[nextstr] { 49 | set[nextstr] = true 50 | queue = append(queue, nextstr) 51 | } 52 | } 53 | } 54 | step++ 55 | queue = queue[size:] 56 | } 57 | return -1 58 | } 59 | 60 | func flip(a byte) byte { 61 | if a == '1' { 62 | return '0' 63 | } else { 64 | return '1' 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Problems/1286. Iterator for Combination/1286. Iterator for Combination.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | type CombinationIterator struct { 4 | idx int 5 | ss []string 6 | } 7 | 8 | func Constructor(characters string, combinationLength int) CombinationIterator { 9 | ss := make([]string, 0) 10 | helper(0, "", characters, combinationLength, &ss) 11 | return CombinationIterator{0, ss} 12 | } 13 | 14 | func helper(idx int, temp, chars string, length int, ss *[]string) { 15 | if len(temp) == length { 16 | *ss = append(*ss, temp) 17 | return 18 | } else { 19 | for i := idx; i < len(chars); i++ { 20 | temp = temp + chars[i:i+1] 21 | helper(i+1, temp, chars, length, ss) 22 | temp = temp[0 : len(temp)-1] 23 | } 24 | } 25 | } 26 | 27 | func (this *CombinationIterator) Next() string { 28 | this.idx++ 29 | return this.ss[this.idx] 30 | } 31 | 32 | func (this *CombinationIterator) HasNext() bool { 33 | return this.idx < len(this.ss) 34 | } 35 | -------------------------------------------------------------------------------- /Problems/1289. Minimum Falling Path Sum II/1289. Minimum Falling Path Sum II.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "math" 4 | 5 | func minFallingPathSum(arr [][]int) int { 6 | m := len(arr) 7 | n := len(arr[0]) 8 | dp := make([][]int, m) 9 | for i := range dp { 10 | dp[i] = make([]int, n) 11 | } 12 | min1, min2 := math.MaxInt32, math.MaxInt32 13 | 14 | for i := range dp[0] { 15 | dp[0][i] = arr[0][i] 16 | if dp[0][i] <= min1 { 17 | min2 = min1 18 | min1 = dp[0][i] 19 | } else { 20 | min2 = min(min2, dp[0][i]) 21 | } 22 | } 23 | 24 | for i := 1; i < m; i++ { 25 | curMin1, curMin2 := math.MaxInt32, math.MaxInt32 26 | for j := 0; j < n; j++ { 27 | if dp[i-1][j] == min1 { 28 | dp[i][j] = min2 + arr[i][j] 29 | } else { 30 | dp[i][j] = min1 + arr[i][j] 31 | } 32 | if dp[i][j] <= curMin1 { 33 | curMin2 = curMin1 34 | curMin1 = dp[i][j] 35 | } else { 36 | curMin2 = min(dp[i][j], curMin2) 37 | } 38 | } 39 | min1 = curMin1 40 | min2 = curMin2 41 | } 42 | return min1 43 | } 44 | 45 | func min(a, b int) int { 46 | if a < b { 47 | return a 48 | } else { 49 | return b 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /Problems/1291. Sequential Digits/1291. Sequential Digits.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "strconv" 4 | 5 | func sequentialDigits(low int, high int) []int { 6 | res := make([]int, 0, 0) 7 | l := strconv.Itoa(low) 8 | r := strconv.Itoa(high) 9 | llen := len(l) 10 | rlen := len(r) 11 | pattern := make([][]byte, 0, 0) 12 | for i := llen; i <= rlen; i++ { 13 | str := "" 14 | for j := 0; j < i; j++ { 15 | str = str + strconv.Itoa(j) 16 | } 17 | pattern = append(pattern, []byte(str)) 18 | } 19 | for _, pat := range pattern { 20 | for i := 1; i <= 9; i++ { 21 | var copy []byte 22 | copy = append(copy, pat...) 23 | for j := 0; j < len(copy); j++ { 24 | copy[j] += byte(i) 25 | if copy[j] == byte(10) { 26 | break 27 | } 28 | } 29 | tempRes, _ := strconv.Atoi(string(copy)) 30 | if tempRes >= low && tempRes <= high { 31 | res = append(res, tempRes) 32 | } 33 | } 34 | } 35 | return res 36 | } 37 | -------------------------------------------------------------------------------- /Problems/1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold/1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "math" 4 | 5 | func maxSideLength(mat [][]int, threshold int) int { 6 | m := len(mat) 7 | n := len(mat[0]) 8 | sum := make([][]int, m+1, m+1) 9 | for i := range sum { 10 | sum[i] = make([]int, n+1, n+1) 11 | } 12 | for i := 0; i < m; i++ { 13 | for j := 0; j < n; j++ { 14 | sum[i+1][j+1] = sum[i][j+1] + sum[i+1][j] - sum[i][j] + mat[i][j] 15 | } 16 | } 17 | l := 0 18 | r := int(math.Min(float64(m), float64(n))) 19 | for l+1 < r { 20 | mid := (l + r) / 2 21 | if !inThreshold(&sum, threshold, mid) { 22 | r = mid 23 | } else { 24 | l = mid 25 | } 26 | } 27 | if inThreshold(&sum, threshold, r) { 28 | return r 29 | } else { 30 | return l 31 | } 32 | } 33 | 34 | func inThreshold(sum *[][]int, threshold int, length int) bool { 35 | for i := 1; i < len(*sum); i++ { 36 | for j := 1; j < len((*sum)[0]); j++ { 37 | if i < length || j < length { 38 | continue 39 | } 40 | if (*sum)[i][j]+(*sum)[i-length][j-length]-(*sum)[i-length][j]-(*sum)[i][j-length] <= threshold { 41 | return true 42 | } 43 | } 44 | } 45 | return false 46 | } 47 | -------------------------------------------------------------------------------- /Problems/1293. Shortest Path in a Grid with Obstacles Elimination/1293. Shortest Path in a Grid with Obstacles Elimination.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "strconv" 4 | 5 | func shortestPath(grid [][]int, k int) int { 6 | move := []int{0, 1, 0, -1, 0} 7 | queue := make([][]int, 0, 0) 8 | queue = append(queue, []int{0, 0, k}) 9 | set := make(map[string]bool) 10 | set["0"+" "+"0"+" "+strconv.Itoa(k)] = true 11 | step := 0 12 | m := len(grid) 13 | n := len(grid[0]) 14 | for len(queue) > 0 { 15 | size := len(queue) 16 | for i := 0; i < size; i++ { 17 | cur := queue[i] 18 | if cur[0] == m-1 && cur[1] == n-1 { 19 | return step 20 | } 21 | for i := 0; i < 4; i++ { 22 | nx := cur[0] + move[i] 23 | ny := cur[1] + move[i+1] 24 | nk := cur[2] 25 | if nx >= 0 && nx < m && ny >= 0 && ny < n { 26 | if grid[nx][ny] == 1 { 27 | nk-- 28 | } 29 | if nk < 0 { 30 | continue 31 | } 32 | status := strconv.Itoa(nx) + " " + strconv.Itoa(ny) + " " + strconv.Itoa(nk) 33 | if _, ok := set[status]; !ok { 34 | set[status] = true 35 | queue = append(queue, []int{nx, ny, nk}) 36 | } 37 | } 38 | } 39 | } 40 | queue = queue[size:] 41 | step++ 42 | } 43 | return -1 44 | } 45 | -------------------------------------------------------------------------------- /Problems/1297. Maximum Number of Occurrences of a Substring/1297. Maximum Number of Occurrences of a Substring.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func maxFreq(s string, maxLetters int, minSize int, maxSize int) int { 4 | //actually the maxSize is redundant here, 5 | //if a string has frequency f, then its substring has frequency at least f 6 | cnt := make(map[string]int) 7 | res := 0 8 | l := 0 9 | r := 0 10 | ht := [26]int{} 11 | unique := 0 12 | //maintain a fixed size window in minSize 13 | for ; r < minSize-1; r++ { 14 | ht[s[r]-'a']++ 15 | if ht[s[r]-'a'] == 1 { 16 | unique++ 17 | } 18 | } 19 | for r < len(s) { 20 | ht[s[r]-'a']++ 21 | if ht[s[r]-'a'] == 1 { 22 | unique++ 23 | } 24 | if unique <= maxLetters { 25 | str := s[l : r+1] 26 | cnt[str]++ 27 | if cnt[str] > res { 28 | res = cnt[str] 29 | } 30 | } 31 | ht[s[l]-'a']-- 32 | if ht[s[l]-'a'] == 0 { 33 | unique-- 34 | } 35 | l++ 36 | r++ 37 | } 38 | return res 39 | } 40 | -------------------------------------------------------------------------------- /Problems/1298. Maximum Candies You Can Get from Boxes/1298. Maximum Candies You Can Get from Boxes.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func maxCandies(status []int, candies []int, keys [][]int, containedBoxes [][]int, initialBoxes []int) int { 4 | got := make([]bool, len(status), len(status)) 5 | queue := make([]int, 0, 0) 6 | used := make([]bool, len(status), len(status)) 7 | for _, i := range initialBoxes { 8 | got[i] = true 9 | if status[i] == 1 { 10 | queue = append(queue, i) 11 | used[i] = true 12 | } 13 | } 14 | res := 0 15 | for len(queue) != 0 { 16 | cur := queue[0] 17 | queue = queue[1:] 18 | res += candies[cur] 19 | for _, i := range keys[cur] { 20 | status[i] = 1 21 | if got[i] && !used[i] { 22 | queue = append(queue, i) 23 | used[i] = true 24 | } 25 | } 26 | for _, i := range containedBoxes[cur] { 27 | got[i] = true 28 | if status[i] == 1 && !used[i] { 29 | queue = append(queue, i) 30 | used[i] = true 31 | } 32 | } 33 | } 34 | return res 35 | } 36 | -------------------------------------------------------------------------------- /Problems/130. Surrounded Regions/130. Surrounded Regions.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func solve(board [][]byte) { 4 | m := len(board) 5 | if m == 0 { 6 | return 7 | } 8 | n := len(board[0]) 9 | if n == 0 { 10 | return 11 | } 12 | for i := 0; i < m; i++ { 13 | if board[i][0] == 'O' { 14 | bfs(board, '1', i, 0) 15 | } 16 | if board[i][n-1] == 'O' { 17 | bfs(board, '1', i, n-1) 18 | } 19 | } 20 | for i := 0; i < n; i++ { 21 | if board[0][i] == 'O' { 22 | bfs(board, '1', 0, i) 23 | } 24 | if board[m-1][i] == 'O' { 25 | bfs(board, '1', m-1, i) 26 | } 27 | } 28 | for i := 0; i < m; i++ { 29 | for j := 0; j < n; j++ { 30 | if board[i][j] == 'O' { 31 | bfs(board, 'X', i, j) 32 | } 33 | } 34 | } 35 | for i := 0; i < m; i++ { 36 | for j := 0; j < n; j++ { 37 | if board[i][j] == '1' { 38 | board[i][j] = 'O' 39 | } 40 | } 41 | } 42 | } 43 | 44 | func bfs(board [][]byte, c byte, x int, y int) { 45 | m := len(board) 46 | n := len(board[0]) 47 | move := [5]int{0, 1, 0, -1, 0} 48 | queue := make([][]int, 0, m*n) 49 | queue = append(queue, []int{x, y}) 50 | board[x][y] = c 51 | for len(queue) > 0 { 52 | cur := queue[0] 53 | queue = queue[1:] 54 | for i := 0; i < 4; i++ { 55 | nx := cur[0] + move[i] 56 | ny := cur[1] + move[i+1] 57 | if nx >= 0 && nx < m && ny >= 0 && ny < n && board[nx][ny] == 'O' { 58 | queue = append(queue, []int{nx, ny}) 59 | board[nx][ny] = c 60 | } 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /Problems/1300. Sum of Mutated Array Closest to Target/1300. Sum of Mutated Array Closest to Target.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "math" 4 | 5 | func findBestValue(arr []int, target int) int { 6 | right := 0 7 | for i := range arr { 8 | if arr[i] > right { 9 | right = arr[i] 10 | } 11 | } 12 | right += 1 13 | dif := math.MaxUint16 14 | res := arr[0] 15 | left := 0 16 | for left < right { 17 | mid := (left + right) / 2 18 | sum := 0 19 | for _, val := range arr { 20 | if val > mid { 21 | sum += mid 22 | } else { 23 | sum += val 24 | } 25 | } 26 | temp := int(math.Abs(float64(sum - target))) 27 | if temp < dif { 28 | dif = temp 29 | res = mid 30 | } else if temp == dif { 31 | if res > mid { 32 | res = mid 33 | } 34 | } 35 | if sum < target { 36 | left = mid + 1 37 | } else { 38 | right = mid 39 | } 40 | } 41 | return res 42 | } 43 | -------------------------------------------------------------------------------- /Problems/1301. Number of Paths with Max Score/1301. Number of Paths with Max Score.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "math" 4 | 5 | func pathsWithMaxScore(board []string) []int { 6 | mod := int(math.Pow10(9)) + 7 7 | m := len(board) 8 | max := make([][]int, m, m) 9 | for i := range max { 10 | max[i] = make([]int, m, m) 11 | } 12 | cnt := make([][]int, m, m) 13 | for i := range cnt { 14 | cnt[i] = make([]int, m, m) 15 | } 16 | max[0][0] = 0 17 | cnt[0][0] = 1 18 | for i := 1; i < m; i++ { 19 | if board[i][0] == 'X' || max[i-1][0] == -1 { 20 | max[i][0] = -1 21 | cnt[i][0] = 0 22 | } else { 23 | max[i][0] = max[i-1][0] + int(board[i][0]-'0') 24 | cnt[i][0] = 1 25 | } 26 | } 27 | for i := 1; i < m; i++ { 28 | if board[0][i] == 'X' || max[0][i-1] == -1 { 29 | max[0][i] = -1 30 | cnt[0][i] = 0 31 | } else { 32 | max[0][i] = max[0][i-1] + int(board[0][i]-'0') 33 | cnt[0][i] = 1 34 | } 35 | } 36 | for i := 1; i < m; i++ { 37 | for j := 1; j < m; j++ { 38 | if board[i][j] == 'X' { 39 | max[i][j] = -1 40 | cnt[i][j] = 0 41 | } else { 42 | prevMax := getMax(max[i-1][j-1], getMax(max[i-1][j], max[i][j-1])) 43 | if prevMax == -1 { 44 | max[i][j] = -1 45 | cnt[i][j] = 0 46 | } else { 47 | max[i][j] = prevMax + int(board[i][j]-'0') 48 | if prevMax == max[i-1][j] { 49 | cnt[i][j] += cnt[i-1][j] 50 | cnt[i][j] %= mod 51 | } 52 | if prevMax == max[i-1][j-1] { 53 | cnt[i][j] += cnt[i-1][j-1] 54 | cnt[i][j] %= mod 55 | } 56 | if prevMax == max[i][j-1] { 57 | cnt[i][j] += cnt[i][j-1] 58 | cnt[i][j] %= mod 59 | } 60 | } 61 | } 62 | } 63 | } 64 | if max[m-1][m-1] == -1 { 65 | return []int{0, 0} 66 | } else { 67 | return []int{max[m-1][m-1] - int('S'-'0'), cnt[m-1][m-1]} 68 | } 69 | } 70 | 71 | func getMax(a, b int) int { 72 | if a > b { 73 | return a 74 | } 75 | return b 76 | } 77 | -------------------------------------------------------------------------------- /Problems/1307. Verbal Arithmetic Puzzle/1307. Verbal Arithmetic Puzzle.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | "sort" 7 | ) 8 | 9 | type charInt struct { 10 | x byte 11 | y int 12 | } 13 | 14 | var ws []charInt 15 | 16 | func pow10(x int) int { 17 | res := 1 18 | for i := 0; i < x; i++ { 19 | res *= 10 20 | } 21 | return res 22 | } 23 | 24 | func isSolvable(words []string, result string) bool { 25 | weights := make(map[byte]int) 26 | set := make(map[byte]bool) //characters that cannot be zeros (no leading zeros) 27 | for _, s := range words { 28 | for i := range s { 29 | weights[s[i]] += pow10(len(s) - 1 - i) 30 | } 31 | if len(s) > 1 { 32 | set[s[0]] = true //no leading zero 33 | } 34 | } 35 | for i := range result { 36 | weights[result[i]] -= pow10(len(result) - 1 - i) 37 | } 38 | if len(result) > 1 { 39 | set[result[0]] = true //no leading zero 40 | } 41 | 42 | for k, v := range weights { 43 | ws = append(ws, charInt{k, v}) 44 | } 45 | 46 | sort.Slice(ws, func(i, j int) bool { 47 | return math.Abs(float64(ws[i].y)) > math.Abs(float64(ws[j].y)) 48 | }) 49 | fmt.Println(ws) 50 | n := len(ws) 51 | sufSumMax := make([]int, n) //the upper bound of ith weight character value 52 | sufSumMin := make([]int, n) //the lower bound of ith weight character value 53 | for i := range ws { 54 | sufPos := make([]int, 0) //positive suffix weights 55 | sufNeg := make([]int, 0) //negative suffix weights 56 | for j := i; j < n; j++ { 57 | if ws[j].y > 0 { 58 | sufPos = append(sufPos, ws[j].y) 59 | } else { 60 | sufNeg = append(sufNeg, ws[j].y) 61 | } 62 | } 63 | sort.Ints(sufPos) 64 | sort.Ints(sufNeg) 65 | for j := range sufPos { 66 | //note the sufPos is increasing 67 | sufSumMax[i] += sufPos[j] * (10 - len(sufPos) + j) //add from 10-len(sufPos)+j to ..8,9 68 | sufSumMin[i] += sufPos[j] * (len(sufPos) - j - 1) //add from len(sufPos)-j-1 to ..1,0 69 | } 70 | for j := range sufNeg { 71 | //the absolute value is decreasing 72 | sufSumMin[i] += (9 - j) * sufNeg[j] 73 | sufSumMax[i] += j * sufNeg[j] 74 | } 75 | } 76 | leadingZero := make([]int, n) 77 | for i := range ws { 78 | if set[ws[i].x] { 79 | leadingZero[i] = 1 80 | } else { 81 | leadingZero[i] = 0 82 | } 83 | } 84 | 85 | return false 86 | } 87 | 88 | func dfs(pos, total int, sufSumMax, sufSumMin []int) bool { 89 | if pos == len(ws) { 90 | return total == 0 91 | } 92 | return false 93 | } 94 | 95 | func main() { 96 | isSolvable([]string{"SEND", "MORE"}, "MONEY") 97 | } 98 | -------------------------------------------------------------------------------- /Problems/131. Palindrome Partitioning/131. Palindrome Partitioning.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | var res [][]string 4 | 5 | func partition(s string) [][]string { 6 | res = [][]string{} 7 | helper(0, s, []string{}) 8 | return res 9 | } 10 | 11 | func helper(idx int, s string, cur []string) { 12 | if idx == len(s) { 13 | res = append(res, append([]string{}, cur...)) 14 | return 15 | } 16 | for i := idx; i < len(s); i++ { 17 | if isPalindrome(s, idx, i) { 18 | cur = append(cur, s[idx:i+1]) 19 | helper(i+1, s, cur) 20 | cur = cur[:len(cur)-1] 21 | } 22 | } 23 | } 24 | 25 | func isPalindrome(s string, i int, j int) bool { 26 | for i < j { 27 | if s[i] != s[j] { 28 | return false 29 | } else { 30 | i++ 31 | j-- 32 | } 33 | } 34 | return true 35 | } 36 | -------------------------------------------------------------------------------- /Problems/1310. XOR Queries of a Subarray/1310. XOR Queries of a Subarray.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func xorQueries(arr []int, queries [][]int) []int { 4 | prefix := make([]int, len(arr)+1) 5 | prefix[0] = 0 6 | for i := 1; i <= len(arr); i++ { 7 | prefix[i] = prefix[i-1] ^ arr[i-1] 8 | } 9 | res := make([]int, len(queries)) 10 | for i := range queries { 11 | cur := queries[i] 12 | res[i] = prefix[cur[1]+1] ^ prefix[cur[0]] 13 | } 14 | return res 15 | } 16 | -------------------------------------------------------------------------------- /Problems/1311. Get Watched Videos by Your Friends/1311. Get Watched Videos by Your Friends.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "sort" 4 | 5 | func watchedVideosByFriends(watchedVideos [][]string, friends [][]int, id int, level int) []string { 6 | ht := make(map[string]int, 0) 7 | set := make(map[int]bool, 0) 8 | queue := make([]int, 0, 0) 9 | set[id] = true 10 | queue = append(queue, id) 11 | for level >= 1 { 12 | level-- 13 | size := len(queue) 14 | for i := 0; i < size; i++ { 15 | cur := queue[i] 16 | for _, f := range friends[cur] { 17 | if !set[f] { 18 | set[f] = true 19 | queue = append(queue, f) 20 | } 21 | } 22 | } 23 | queue = queue[size:] 24 | } 25 | for i := 0; i < len(queue); i++ { 26 | cur := queue[i] 27 | for _, v := range watchedVideos[cur] { 28 | ht[v]++ 29 | } 30 | } 31 | res := make([]string, 0) 32 | for k := range ht { 33 | res = append(res, k) 34 | } 35 | sort.Slice(res, func(a, b int) bool { 36 | if ht[res[a]] != ht[res[b]] { 37 | return ht[res[a]] < ht[res[b]] 38 | } else { 39 | return res[a] < res[b] 40 | } 41 | }) 42 | return res 43 | } 44 | -------------------------------------------------------------------------------- /Problems/1312. Minimum Insertion Steps to Make a String Palindrome/1312. Minimum Insertion Steps to Make a String Palindrome.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func minInsertions(s string) int { 4 | //let res[i][j] equals to the minimum steps of insertion to make s[i:j] a palindrome 5 | 6 | //for s[i,j] 7 | //if s[i]==s[j], then res[i][j] = res[i+1][j-1] 8 | //else res[i][j] = min(res[i+1][j], res[i][j-1])+1 9 | n := len(s) 10 | res := twodarray(n, n) 11 | for j := 1; j < n; j++ { 12 | for i := j - 1; i >= 0; i-- { 13 | if s[i] == s[j] { 14 | res[i][j] = res[i+1][j-1] 15 | } else { 16 | res[i][j] = min(res[i+1][j], res[i][j-1]) + 1 17 | } 18 | } 19 | } 20 | return res[0][n-1] 21 | } 22 | 23 | func twodarray(m, n int) [][]int { 24 | res := make([][]int, m) 25 | for i := range res { 26 | res[i] = make([]int, n) 27 | } 28 | return res 29 | } 30 | 31 | func min(a, b int) int { 32 | if a > b { 33 | return b 34 | } 35 | return a 36 | } 37 | -------------------------------------------------------------------------------- /Problems/1314. Matrix Block Sum/1314. Matrix Blcok Sum.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func matrixBlockSum(mat [][]int, K int) [][]int { 4 | m := len(mat) 5 | n := len(mat[0]) 6 | fix := twodarray(m+1, n+1) 7 | for i := 1; i < m+1; i++ { 8 | for j := 1; j < n+1; j++ { 9 | fix[i][j] = fix[i-1][j] + fix[i][j-1] - fix[i-1][j-1] + mat[i-1][j-1] 10 | } 11 | } 12 | // fmt.Println(fix) 13 | res := twodarray(m, n) 14 | for i := 0; i < m; i++ { 15 | for j := 0; j < n; j++ { 16 | l := max(0, j-K) 17 | r := min(n-1, j+K) 18 | upper := max(0, i-K) 19 | lower := min(i+K, m-1) 20 | res[i][j] = fix[lower+1][r+1] + fix[upper][l] - fix[upper][r+1] - fix[lower+1][l] 21 | } 22 | } 23 | return res 24 | } 25 | 26 | func max(a, b int) int { 27 | if a > b { 28 | return a 29 | } 30 | return b 31 | } 32 | 33 | func min(a, b int) int { 34 | if a > b { 35 | return b 36 | } 37 | return a 38 | } 39 | 40 | func twodarray(m, n int) [][]int { 41 | res := make([][]int, m) 42 | for i := range res { 43 | res[i] = make([]int, n) 44 | } 45 | return res 46 | } 47 | -------------------------------------------------------------------------------- /Problems/1315. Sum of Nodes with Even-Valued Grandparent/1315. Sum of Nodes with Even-Valued Grandparent.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import . "LeetCode-GoSol/Utils" 4 | 5 | func sumEvenGrandparent(root *TreeNode) int { 6 | res := 0 7 | add(false, false, root, &res) 8 | return res 9 | } 10 | 11 | func add(grandpa, pa bool, root *TreeNode, res *int) { 12 | if root == nil { 13 | return 14 | } 15 | if grandpa { 16 | *res += root.Val 17 | } 18 | if root.Val%2 == 0 { 19 | add(pa, true, root.Left, res) 20 | add(pa, true, root.Right, res) 21 | } else { 22 | add(pa, false, root.Left, res) 23 | add(pa, false, root.Right, res) 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Problems/1316. Distinct Echo Substrings/1316. Distinct Echo Substrings.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func distinctEchoSubstrings(text string) int { 4 | set := map[string]bool{} 5 | n := len(text) 6 | for w := 1; w <= n/2; w++ { 7 | cnt := 0 8 | for l, r := 0, w; r < n; l, r = l+1, r+1 { 9 | if text[l] == text[r] { 10 | cnt++ 11 | if cnt == w { 12 | if !set[text[l-w+1:l+1]] { 13 | set[text[l-w+1:l+1]] = true 14 | } 15 | } 16 | } else { 17 | cnt = 0 18 | } 19 | } 20 | } 21 | return len(set) 22 | } 23 | -------------------------------------------------------------------------------- /Problems/1318. Minimum Flips to Make a OR b Equal to c/1318. Minimum Flips to Make a OR b Equal to c.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func minFlips(a int, b int, c int) int { 4 | res := 0 5 | for i := 0; i < 32; i++ { 6 | b1, b2, b3 := 0, 0, 0 7 | if (a>>uint(i))&1 == 1 { 8 | b1 = 1 9 | } 10 | if (b>>uint(i))&1 == 1 { 11 | b2 = 1 12 | } 13 | if (c>>uint(i))&1 == 1 { 14 | b3 = 1 15 | } 16 | if b3 == 0 { 17 | res += b1 + b2 18 | } else { 19 | if b1 == 0 && b2 == 0 { 20 | res += 1 21 | } 22 | } 23 | } 24 | return res 25 | } 26 | -------------------------------------------------------------------------------- /Problems/1319. Number of Operations to Make Network Connected/1319. Number of Operations to Make Network Connected.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func makeConnected(n int, connections [][]int) int { 6 | root := make([]int, n) 7 | for i := range root { 8 | root[i] = i 9 | } 10 | dup := 0 11 | for i := range connections { 12 | a := connections[i][0] 13 | b := connections[i][1] 14 | if !connect(a, b, root) { 15 | dup++ 16 | } 17 | } 18 | set := make(map[int]bool, 0) 19 | fmt.Println(root) 20 | for i := range root { 21 | root[i] = find(i, root) 22 | set[root[i]] = true 23 | } 24 | fmt.Println(root) 25 | 26 | cnt := len(set) 27 | res := cnt - 1 28 | if dup < res { 29 | return -1 30 | } else { 31 | return res 32 | } 33 | } 34 | 35 | func find(a int, root []int) int { 36 | if root[a] == a { 37 | return a 38 | } 39 | root[a] = find(root[a], root) 40 | return root[a] 41 | } 42 | 43 | func connect(a, b int, root []int) bool { 44 | ra := find(a, root) 45 | rb := find(b, root) 46 | if ra == rb { 47 | return false 48 | } 49 | root[rb] = ra 50 | return true 51 | } 52 | -------------------------------------------------------------------------------- /Problems/132. Palindrome Partitioning II/132. Palindrome Partitioning II.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func minCut(s string) int { 4 | n := len(s) 5 | dp := make([]int, n, n) 6 | is := make([][]bool, n) 7 | for i := range is { 8 | is[i] = make([]bool, n) 9 | } 10 | for i := 0; i < n; i++ { 11 | min := i 12 | for j := i; j >= 0; j-- { 13 | if s[i] == s[j] && (i-j < 2 || is[j+1][i-1]) { 14 | is[j][i] = true 15 | if j == 0 { 16 | min = 0 17 | } else { 18 | if min > dp[j-1]+1 { 19 | min = dp[j-1] + 1 20 | } 21 | } 22 | } 23 | } 24 | dp[i] = min 25 | } 26 | return dp[n-1] 27 | } 28 | -------------------------------------------------------------------------------- /Problems/1320. Minimum Distance to Type a Word Using Two Fingers/1320. Minimum Distance to Type a Word Using Two Fingers.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "math" 5 | "strconv" 6 | ) 7 | 8 | func minimumDistance(word string) int { 9 | tb := make(map[int][]int, 26) 10 | for i := 0; i < 26; i++ { 11 | x := i / 6 12 | y := i % 6 13 | tb[i] = make([]int, 2) 14 | tb[i][0] = x 15 | tb[i][1] = y 16 | } 17 | mem := make(map[string]int) 18 | return helper(word, 0, tb, mem, 'a', 'a') 19 | } 20 | 21 | func helper(s string, idx int, tb map[int][]int, mem map[string]int, left, right byte) int { 22 | if idx == len(s) { 23 | return 0 24 | } 25 | key := strconv.Itoa(idx) + " " + string(left) + " " + string(right) 26 | if v, ok := mem[key]; ok { 27 | return v 28 | } 29 | res := math.MaxInt32 30 | c := s[idx] 31 | x := tb[int(c-'A')][0] 32 | y := tb[int(c-'A')][1] 33 | if left == 'a' { 34 | res = min(res, helper(s, idx+1, tb, mem, c, right)) 35 | } else { 36 | prevX := tb[int(left-'A')][0] 37 | prevY := tb[int(left-'A')][1] 38 | dist := abs(prevX-x) + abs(prevY-y) 39 | res = min(res, dist+helper(s, idx+1, tb, mem, c, right)) 40 | } 41 | if right == 'a' { 42 | res = min(res, helper(s, idx+1, tb, mem, left, c)) 43 | } else { 44 | prevX := tb[int(right-'A')][0] 45 | prevY := tb[int(right-'A')][1] 46 | dist := abs(prevX-x) + abs(prevY-y) 47 | res = min(res, dist+helper(s, idx+1, tb, mem, left, c)) 48 | } 49 | mem[key] = res 50 | return res 51 | } 52 | 53 | func min(a, b int) int { 54 | if a > b { 55 | return b 56 | } 57 | return a 58 | } 59 | 60 | func abs(a int) int { 61 | if a < 0 { 62 | return -1 * a 63 | } 64 | return a 65 | } 66 | 67 | //--------------------------Bottom Up--------------------------------- 68 | 69 | func minimumDistance2(word string) int { 70 | tb := make(map[int][]int, 26) 71 | for i := 0; i < 26; i++ { 72 | x := i / 6 73 | y := i % 6 74 | tb[i] = make([]int, 2) 75 | tb[i][0] = x 76 | tb[i][1] = y 77 | } 78 | dp := make([][][]int, len(word)+1) 79 | for i := range dp { 80 | dp[i] = make([][]int, 27) 81 | for j := range dp[i] { 82 | dp[i][j] = make([]int, 27) 83 | } 84 | } 85 | //dp[i][j][k] is the minimum distance for word[i:] with left finger on j, right finger on k 86 | //dp[i][j][k] = min(dp[i+1][word[i]][k]+distance(word[i], j), dp[i+1][j][word[i]]+distance(word[i],k)) 87 | for i := len(word) - 1; i >= 0; i-- { 88 | for j := 0; j < 27; j++ { 89 | for k := 0; k < 27; k++ { 90 | distL := dist(j, int(word[i]-'A'), tb) 91 | distR := dist(k, int(word[i]-'A'), tb) 92 | dp[i][j][k] = min(distL+dp[i+1][int(word[i]-'A')][k], distR+dp[i+1][j][int(word[i]-'A')]) 93 | } 94 | } 95 | } 96 | return dp[0][26][26] 97 | } 98 | 99 | func dist(x, y int, tb map[int][]int) int { 100 | if x == 26 { 101 | return 0 //the current finger is not on keyboard 102 | } 103 | return abs(tb[x][0]-tb[y][0]) + abs(tb[x][1]-tb[y][1]) 104 | } 105 | -------------------------------------------------------------------------------- /Problems/1325. Delete Leaves With a Given Value/1325. Delete Leaves With a Given Value.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import . "LeetCode-GoSol/Utils" 4 | 5 | func removeLeafNodes(root *TreeNode, target int) *TreeNode { 6 | if root == nil { 7 | return root 8 | } 9 | if root.Left != nil { 10 | root.Left = removeLeafNodes(root.Left, target) 11 | } 12 | if root.Right != nil { 13 | root.Right = removeLeafNodes(root.Right, target) 14 | } 15 | if root.Left == nil && root.Right == nil && root.Val == target { 16 | return nil 17 | } 18 | return root 19 | } 20 | -------------------------------------------------------------------------------- /Problems/1326. Minimum Number of Taps to Open to Water a Garden/1326. Minimum Number of Taps to Open to Water a Garden.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "sort" 5 | ) 6 | 7 | func minTaps(n int, ranges []int) int { 8 | rs := make([][]int, n+1) 9 | for i := range rs { 10 | rs[i] = make([]int, 2) 11 | rs[i][0] = max(0, i-ranges[i]) 12 | rs[i][1] = min(n, i+ranges[i]) 13 | } 14 | sort.Slice(rs, func(i, j int) bool { 15 | if rs[i][0] == rs[j][0] { 16 | return rs[j][1] < rs[i][1] 17 | } else { 18 | return rs[i][0] < rs[j][0] 19 | } 20 | }) 21 | //fmt.Println(rs) 22 | if rs[0][0] > 0 { 23 | return -1 24 | } 25 | end := rs[0][1] 26 | cnt := 0 27 | for i := range rs { 28 | cnt++ 29 | if end >= n { 30 | return cnt 31 | } 32 | nextEnd := end 33 | for j := i + 1; j < len(rs); j++ { 34 | if rs[j][0] <= end && rs[j][1] > nextEnd { 35 | i = j 36 | nextEnd = rs[j][1] 37 | } 38 | } 39 | if nextEnd == end { 40 | return -1 41 | } 42 | end = nextEnd 43 | i-- 44 | } 45 | return -1 46 | } 47 | 48 | func max(a, b int) int { 49 | if a > b { 50 | return a 51 | } 52 | return b 53 | } 54 | 55 | func min(a, b int) int { 56 | if a > b { 57 | return b 58 | } 59 | return a 60 | } 61 | -------------------------------------------------------------------------------- /Problems/1328. Break a Palindrome/1328. Break a Palindrome.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func breakPalindrome(palindrome string) string { 4 | if len(palindrome) == 1 { 5 | return "" 6 | } 7 | pb := []byte(palindrome) 8 | mid := len(palindrome) / 2 9 | for i := 0; i < mid; i++ { 10 | if palindrome[i] > 'a' { 11 | pb[i] = 'a' 12 | return string(pb) 13 | } 14 | } 15 | pb[len(pb)-1] = 'b' 16 | return string(pb) 17 | } 18 | -------------------------------------------------------------------------------- /Problems/1329. Sort the Matrix Diagonally/1329. Sort the Matrix Diagonally.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "sort" 4 | 5 | func diagonalSort(mat [][]int) [][]int { 6 | m := len(mat) 7 | n := len(mat[0]) 8 | for i := 0; i < m; i++ { 9 | temp := make([]int, 0) 10 | x := i 11 | y := 0 12 | for x < m && y < n { 13 | temp = append(temp, mat[x][y]) 14 | x++ 15 | y++ 16 | } 17 | sort.Ints(temp) 18 | idx := 0 19 | x = i 20 | y = 0 21 | for x < m && y < n { 22 | mat[x][y] = temp[idx] 23 | idx++ 24 | x++ 25 | y++ 26 | } 27 | } 28 | for j := 0; j < n; j++ { 29 | temp := make([]int, 0) 30 | x := 0 31 | y := j 32 | for x < m && y < n { 33 | temp = append(temp, mat[x][y]) 34 | x++ 35 | y++ 36 | } 37 | sort.Ints(temp) 38 | idx := 0 39 | x = 0 40 | y = j 41 | for x < m && y < n { 42 | mat[x][y] = temp[idx] 43 | idx++ 44 | x++ 45 | y++ 46 | } 47 | } 48 | return mat 49 | } 50 | -------------------------------------------------------------------------------- /Problems/1330. Reverse Subarray To Maximize Array Value/1330. Reverse Subarray To Maximize Array Value.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "math" 4 | 5 | func maxValueAfterReverse(nums []int) int { 6 | n := len(nums) 7 | maxPair := math.MinInt32 8 | minPair := math.MaxInt32 9 | //it is only possible to increase when in a, b ... c, d 10 | //the distance between min(c,d) and max(a, b) is positive 11 | //then will increase by 2*(min(c, d) - max(a, b) 12 | for i := 0; i < n-1; i++ { 13 | l := i 14 | r := i + 1 15 | maxPair = max(maxPair, min(nums[l], nums[r])) 16 | minPair = min(minPair, max(nums[l], nums[r])) 17 | } 18 | change := max(0, (maxPair-minPair)*2) 19 | //another situation is reverse from nums[0] or reverse from nums[-1] 20 | //if reverse from nums[0] to nums[i] 21 | //change = -abs(nums[i]-nums[i+1])+abs(nums[i+1]-nums[0]) 22 | //if reverse from nums[i] to nums[-1] 23 | //change = -abs(nums[i]-nums[i-1])+abs(nums[-1]-nums[i-1]) 24 | revHead := math.MinInt32 25 | revTail := math.MinInt32 26 | for i := 0; i < n-1; i++ { 27 | revHead = max(revHead, -abs(nums[i]-nums[i+1])+abs(nums[i+1]-nums[0])) 28 | revTail = max(revTail, -abs(nums[i+1]-nums[i])+abs(nums[i]-nums[len(nums)-1])) 29 | } 30 | change = max(max(revTail, revHead), change) 31 | res := 0 32 | for i := 0; i < n-1; i++ { 33 | res += abs(nums[i] - nums[i+1]) 34 | } 35 | return res + change 36 | } 37 | 38 | func abs(a int) int { 39 | if a < 0 { 40 | return -a 41 | } 42 | return a 43 | } 44 | 45 | func max(a, b int) int { 46 | if a > b { 47 | return a 48 | } 49 | return b 50 | } 51 | 52 | func min(a, b int) int { 53 | if a < b { 54 | return a 55 | } 56 | return b 57 | } 58 | -------------------------------------------------------------------------------- /Problems/1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance/1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func findTheCity(n int, edges [][]int, distanceThreshold int) int { 4 | dp := make([][]int, n) 5 | for i := range dp { 6 | dp[i] = make([]int, n) 7 | for j := range dp[i] { 8 | dp[i][j] = 10000000 9 | } 10 | } 11 | for i := range dp { 12 | dp[i][i] = 0 13 | } 14 | for i := range edges { 15 | dp[edges[i][0]][edges[i][1]] = edges[i][2] 16 | dp[edges[i][1]][edges[i][0]] = edges[i][2] 17 | } 18 | //note! the outer most iteration is the transit point for dynamic programming 19 | for k := range dp { 20 | for i := range dp { 21 | for j := range dp { 22 | dp[i][j] = min(dp[i][k]+dp[k][j], dp[i][j]) 23 | } 24 | } 25 | } 26 | //now dp is all shortest path for all nodes 27 | res := make([]int, n) 28 | for i := range dp { 29 | for j := range dp[i] { 30 | if i != j && dp[i][j] <= distanceThreshold { 31 | res[i]++ 32 | } 33 | } 34 | } 35 | rs := 0 36 | cur := res[0] 37 | for i := range res { 38 | if res[i] <= cur { 39 | rs = i 40 | cur = res[i] 41 | } 42 | } 43 | return rs 44 | } 45 | 46 | func min(a, b int) int { 47 | if a < b { 48 | return a 49 | } 50 | return b 51 | } 52 | -------------------------------------------------------------------------------- /Problems/1335. Minimum Difficulty of a Job Schedule/1335. Minimum Difficulty of a Job Schedule.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "math" 4 | 5 | func minDifficulty(jobDifficulty []int, d int) int { 6 | //let dp[i][j] is the result for given i day to finish the [1:j] job 7 | //we need to decide what is the difficulty at the ith day 8 | //if the ith day we finish job[k:j], then ith day difficulty is max(jobDifficulty[k:j]) 9 | //then dp[i][j] = dp[i-1][k-1]+max(jobDifficulty[k:j]) 10 | length := len(jobDifficulty) 11 | dp := make([][]int, d+1) 12 | for i := range dp { 13 | dp[i] = make([]int, length+1) 14 | } 15 | curMax := 0 16 | for i := 1; i <= length; i++ { 17 | curMax = max(jobDifficulty[i-1], curMax) 18 | dp[1][i] = curMax 19 | } 20 | for i := 2; i <= d; i++ { 21 | for j := 1; j <= length; j++ { 22 | if i > j { 23 | dp[i][j] = -1 24 | continue 25 | } 26 | dp[i][j] = math.MaxInt32 27 | nextDay := 0 28 | for k := j; k > 1; k-- { 29 | nextDay = max(jobDifficulty[k-1], nextDay) 30 | if dp[i-1][k-1] != -1 { 31 | dp[i][j] = min(dp[i][j], dp[i-1][k-1]+nextDay) 32 | } 33 | } 34 | } 35 | } 36 | return dp[d][length] 37 | } 38 | 39 | func max(a, b int) int { 40 | if a > b { 41 | return a 42 | } 43 | return b 44 | } 45 | 46 | func min(a, b int) int { 47 | if a > b { 48 | return b 49 | } 50 | return a 51 | } 52 | -------------------------------------------------------------------------------- /Problems/1339. Maximum Product of Splitted Binary Tree/1339. Maximum Product of Splitted Binary Tree.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | . "LeetCode-GoSol/Utils" 5 | ) 6 | 7 | func maxProduct(root *TreeNode) int { 8 | pos := make([]int64, 0) 9 | sum := helper(root, &pos) 10 | mod := int64(1e9) + 7 11 | res := int64(0) 12 | for i := range pos { 13 | temp := int64(sum-pos[i]) * int64(pos[i]) 14 | res = max(res, temp) 15 | } 16 | return int(res % mod) 17 | } 18 | 19 | func helper(root *TreeNode, pos *[]int64) int64 { 20 | if root == nil { 21 | return 0 22 | } else { 23 | l := helper(root.Left, pos) 24 | r := helper(root.Right, pos) 25 | temp := l + r + int64(root.Val) 26 | *pos = append(*pos, temp) 27 | return temp 28 | } 29 | } 30 | func max(a, b int64) int64 { 31 | if a > b { 32 | return a 33 | } 34 | return b 35 | } 36 | -------------------------------------------------------------------------------- /Problems/1340. Jump Game V/1340. Jump Game V.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "sort" 4 | 5 | func maxJumps(arr []int, d int) int { 6 | res := 1 7 | l := len(arr) 8 | pairs := make([][]int, len(arr)) 9 | for i := range arr { 10 | pairs[i] = []int{arr[i], i} 11 | } 12 | sort.Slice(pairs, func(i, j int) bool { 13 | return pairs[i][0] < pairs[j][0] 14 | }) 15 | dp := make([]int, len(arr)) 16 | for i := range pairs { 17 | idx := pairs[i][1] 18 | cur := 1 19 | for j := 1; j <= d; j++ { 20 | if idx+j < l { 21 | if arr[idx+j] >= arr[idx] { 22 | break 23 | } 24 | cur = max(cur, dp[idx+j]+1) 25 | } 26 | } 27 | for j := 1; j <= d; j++ { 28 | if idx-j >= 0 { 29 | if arr[idx-j] >= arr[idx] { 30 | break 31 | } 32 | cur = max(cur, dp[idx-j]+1) 33 | } 34 | } 35 | dp[idx] = cur 36 | res = max(dp[idx], res) 37 | } 38 | // fmt.Println(dp) 39 | return res 40 | } 41 | func max(a, b int) int { 42 | if a > b { 43 | return a 44 | } 45 | return b 46 | } 47 | -------------------------------------------------------------------------------- /Problems/1342. Number of Steps to Reduce a Number to Zero/1342. Number of Steps to Reduce a Number to Zero.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func numberOfSteps(num int) int { 4 | //bit manipulation 5 | //if the last bit is 0, divide by two, res+=1 6 | //if the last bit is 1, minus one and then divide by two, res+=2 7 | //we will have one extra step included 1-1=0, 0/2=0 8 | res := 0 9 | for num > 0 { 10 | if num&1 == 1 { 11 | res += 2 12 | } else { 13 | res += 1 14 | } 15 | num >>= uint(1) 16 | } 17 | return res - 1 18 | } 19 | -------------------------------------------------------------------------------- /Problems/1344. Angle Between Hands of a Clock/1344. Angle Between Hands of a Clock.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "math" 5 | ) 6 | 7 | func angleClock(hour int, minutes int) float64 { 8 | full := float64(360) 9 | min := full * float64(minutes) / float64(60) 10 | h := full*float64(hour%12)/float64(12) + full/float64(12)*float64(minutes)/float64(60) 11 | return math.Min(math.Abs(h-min), 360-math.Abs(h-min)) 12 | } 13 | -------------------------------------------------------------------------------- /Problems/1345. Jump Game IV/1345. Jump Game IV.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func minJumps(arr []int) int { 4 | ht := make(map[int][]int) 5 | for i := range arr { 6 | if ht[arr[i]] == nil { 7 | ht[arr[i]] = make([]int, 0) 8 | } 9 | ht[arr[i]] = append(ht[arr[i]], i) 10 | } 11 | numVisited := make(map[int]bool) 12 | 13 | queue := make([]int, 1) 14 | queue[0] = 0 15 | step := 0 16 | visited := make([]bool, len(arr)) 17 | visited[0] = true 18 | for len(queue) > 0 { 19 | size := len(queue) 20 | for i := 0; i < size; i++ { 21 | cur := queue[i] 22 | if cur == len(arr)-1 { 23 | return step 24 | } 25 | /* if the current number has been visited, then all the same number are already in queue */ 26 | if !numVisited[arr[cur]] { 27 | numVisited[arr[cur]] = true 28 | for _, j := range ht[arr[cur]] { 29 | if j == cur { 30 | continue 31 | } 32 | queue = append(queue, j) 33 | visited[j] = true 34 | } 35 | } 36 | if cur-1 >= 0 && !visited[cur-1] { 37 | queue = append(queue, cur-1) 38 | visited[cur-1] = true 39 | } 40 | if cur+1 < len(arr) && !visited[cur+1] { 41 | queue = append(queue, cur+1) 42 | visited[cur+1] = true 43 | } 44 | } 45 | queue = queue[size:] 46 | step++ 47 | } 48 | return -1 49 | } 50 | -------------------------------------------------------------------------------- /Problems/1349. Maximum Students Taking Exam/1349. Maximum Students Taking Exam.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func amxStudents2(seats [][]byte) int { 4 | m := len(seats) 5 | n := len(seats[0]) 6 | dp := make([][]int, m) 7 | for i := range dp { 8 | dp[i] = make([]int, 1<>1)&j) == 0 { 38 | //current row meets the requirement 39 | for k := 0; k < 1<>1)&k == 0 && (j<<1)&k == 0 { 41 | dp[i][j] = max(dp[i][j], dp[i-1][k]+validCnt[j]) 42 | } 43 | } 44 | } 45 | } 46 | } 47 | res := 0 48 | for _, v := range dp[m] { 49 | res = max(res, v) 50 | } 51 | return res 52 | } 53 | 54 | func maxStudents(seats [][]byte) int { 55 | //bitMask, dp[i][mask] is the max student number of first i rows with the last row distribution status as mask 56 | m := len(seats) 57 | n := len(seats[0]) 58 | //the valid position for students for each row 59 | validPos := make([]int, m) 60 | for i := range seats { 61 | cur := 0 62 | for j := range seats[i] { 63 | cur = cur << uint(1) 64 | if seats[i][j] == '.' { 65 | cur += 1 66 | } 67 | } 68 | validPos[i] = cur 69 | } 70 | //the number of students for every mask 71 | validCnt := make([]int, 1<>1)&j == 0) { 92 | //first ensure that the current mask is a subset of current row valid position 93 | //second ensure that no student sitting next to each other 94 | for k := 0; k < 1<>1)&j == 0 && (j>>1)&k == 0 && dp[i-1][k] != -1 { 97 | //if the upperLeft and upperRight principle is met 98 | //if the mask is valid for previous row 99 | dp[i][j] = max(dp[i][j], dp[i-1][k]+validCnt[j]) 100 | } 101 | } 102 | } 103 | } 104 | } 105 | res := 0 106 | for _, v := range dp[m] { 107 | res = max(res, v) 108 | } 109 | return res 110 | } 111 | 112 | func max(a, b int) int { 113 | if a > b { 114 | return a 115 | } 116 | return b 117 | } 118 | -------------------------------------------------------------------------------- /Problems/1352. Product of the Last K Numbers/1352. Product of the Last K Numbers.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | type ProductOfNumbers struct { 4 | prefixProd []int 5 | lastZero int 6 | } 7 | 8 | func Constructor() ProductOfNumbers { 9 | return ProductOfNumbers{[]int{1}, 0} 10 | } 11 | 12 | func (this *ProductOfNumbers) Add(num int) { 13 | if num == 0 { 14 | this.prefixProd = append(this.prefixProd, 1) 15 | this.lastZero = len(this.prefixProd) - 1 16 | } else { 17 | this.prefixProd = append(this.prefixProd, this.prefixProd[len(this.prefixProd)-1]*num) 18 | } 19 | } 20 | 21 | func (this *ProductOfNumbers) GetProduct(k int) int { 22 | start := len(this.prefixProd) - 1 - k 23 | if this.lastZero > start { 24 | return 0 25 | } 26 | return this.prefixProd[len(this.prefixProd)-1] / this.prefixProd[start] 27 | } 28 | -------------------------------------------------------------------------------- /Problems/1353. Maximum Number of Events That Can Be Attended/1353. Maximum Number of Events That Can Be Attended.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "container/heap" 5 | "sort" 6 | ) 7 | 8 | type minHeap []int 9 | 10 | func (m minHeap) Len() int { 11 | return len(m) 12 | } 13 | 14 | func (m minHeap) Less(a, b int) bool { 15 | return m[a] < m[b] 16 | } 17 | 18 | func (m minHeap) Swap(a, b int) { 19 | m[a], m[b] = m[b], m[a] 20 | } 21 | 22 | func (m *minHeap) Push(x interface{}) { 23 | *m = append(*m, x.(int)) 24 | } 25 | 26 | func (m *minHeap) Pop() interface{} { 27 | x := (*m)[len(*m)-1] 28 | *m = (*m)[0 : len(*m)-1] 29 | return x 30 | } 31 | 32 | func maxEvents(events [][]int) int { 33 | sort.Slice(events, func(i, j int) bool { 34 | return events[i][0] < events[j][0] 35 | }) 36 | m := &minHeap{} 37 | heap.Init(m) 38 | res := 0 39 | idx := 0 40 | l := len(events) 41 | for i := 1; i <= 100000; i++ { 42 | for idx < l && events[idx][0] == i { 43 | heap.Push(m, events[idx][1]) 44 | } 45 | for m.Len() > 0 && (*m)[0] < i { 46 | heap.Pop(m) 47 | } 48 | if m.Len() > 0 { 49 | heap.Pop(m) 50 | res++ 51 | } 52 | } 53 | return res 54 | } 55 | -------------------------------------------------------------------------------- /Problems/1354. Construct Target Array With Multiple Sums/1354. Construct Target Arrays With Multiple Sums.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "container/heap" 4 | 5 | type maxHeap []int 6 | 7 | func (max maxHeap) Len() int { 8 | return len(max) 9 | } 10 | 11 | func (max maxHeap) Less(a, b int) bool { 12 | return max[a] > max[b] 13 | } 14 | 15 | func (max maxHeap) Swap(a, b int) { 16 | max[a], max[b] = max[b], max[a] 17 | } 18 | 19 | func (max *maxHeap) Push(a interface{}) { 20 | *max = append(*max, a.(int)) 21 | } 22 | func (max *maxHeap) Pop() interface{} { 23 | x := (*max)[len(*max)-1] 24 | *max = (*max)[0 : len(*max)-1] 25 | return x 26 | } 27 | 28 | func isPossible(target []int) bool { 29 | m := &maxHeap{} 30 | heap.Init(m) 31 | sum := 0 32 | for i := range target { 33 | sum += target[i] 34 | heap.Push(m, target[i]) 35 | } 36 | for m.Len() > 0 { 37 | cur := heap.Pop(m).(int) 38 | if cur == 1 { 39 | return true 40 | } 41 | dif := sum - cur 42 | times := cur / dif 43 | if times == 0 { 44 | return false 45 | } 46 | sum -= times * dif 47 | cur %= dif 48 | heap.Push(m, cur) 49 | } 50 | return true 51 | } 52 | -------------------------------------------------------------------------------- /Problems/1358. Number of Substrings Containing All Three Characters/1358. Number of Substrings Containing All Three Characters.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func numberOfSubstrings(s string) int { 4 | ca, cb, cc := 0, 0, 0 5 | i := 0 6 | j := 0 7 | res := 0 8 | for j < len(s) { 9 | if s[j] == 'a' { 10 | ca++ 11 | } else if s[j] == 'b' { 12 | cb++ 13 | } else { 14 | cc++ 15 | } 16 | for ca > 0 && cb > 0 && cc > 0 { 17 | if s[i] == 'a' { 18 | ca-- 19 | } else if s[i] == 'b' { 20 | cb-- 21 | } else { 22 | cc-- 23 | } 24 | i++ 25 | } 26 | res += i 27 | j++ 28 | } 29 | return res 30 | } 31 | -------------------------------------------------------------------------------- /Problems/1359. Count All Valid Pickup and Delivery Options/1359. Count All Valid Pickup and Delivery Options.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func countOrders(n int) int { 4 | mod := int(1e9) + 7 5 | res := 1 6 | // dp[i] = dp[i-1] * (1+2+3+...+ (i-1)*2+1) 7 | cur := 1 8 | for i := 0; i < n; i++ { 9 | cur = res * (i + 1) * (2*i + 1) 10 | cur %= mod 11 | res = cur 12 | } 13 | return res 14 | } 15 | -------------------------------------------------------------------------------- /Problems/1366. Rank Teams by Votes/1366. Rank Teams by Votes.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "sort" 5 | ) 6 | 7 | func rankTeams(votes []string) string { 8 | s := votes[0] 9 | ss := []byte(s) 10 | sort.Slice(ss, func(i, j int) bool { 11 | return ss[i] < ss[j] 12 | }) 13 | if len(votes) == 1 { 14 | return votes[0] 15 | } 16 | rk := make(map[byte][]int) 17 | for i := range votes { 18 | for j := 0; j < len(votes[i]); j++ { 19 | c := ([]byte(votes[i]))[j] 20 | if _, ok := rk[c]; !ok { 21 | rk[c] = make([]int, len(votes[i])) 22 | } 23 | rk[c][j]++ 24 | } 25 | } 26 | sort.Slice(ss, func(a, b int) bool { 27 | for i := 0; i < len(votes[0]); i++ { 28 | if rk[ss[a]][i] != rk[ss[b]][i] { 29 | return rk[ss[a]][i] > rk[ss[b]][i] 30 | } 31 | } 32 | return ss[a] < ss[b] 33 | }) 34 | return string(ss) 35 | } 36 | -------------------------------------------------------------------------------- /Problems/1368. Minimum Cost to Make at Least One Valid Path in a Grid/1368. Minimum Cost to Make at Least One Valid Path in a Grid.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | var shift = [][]int{{0, 1}, {0, -1}, {1, 0}, {-1, 0}} 4 | 5 | func minCost(grid [][]int) int { 6 | m := len(grid) 7 | n := len(grid[0]) 8 | res := make([][]int, m) 9 | for i := range res { 10 | res[i] = make([]int, n) 11 | for j := range res[i] { 12 | res[i][j] = -1 13 | } 14 | } 15 | queue := make([][]int, 0) 16 | dfs(grid, res, 0, 0, 0, &queue) 17 | cost := 0 18 | for len(queue) > 0 { 19 | cost += 1 20 | size := len(queue) 21 | for i := 0; i < size; i++ { 22 | cur := queue[i] 23 | x := cur[0] 24 | y := cur[1] 25 | for i := 0; i < 4; i++ { 26 | dfs(grid, res, x+shift[i][0], y+shift[i][1], cost, &queue) 27 | } 28 | } 29 | queue = queue[size:] 30 | } 31 | return res[m-1][n-1] 32 | } 33 | 34 | func dfs(grid, res [][]int, x, y, cost int, queue *[][]int) { 35 | if x < 0 || x >= len(grid) || y < 0 || y >= len(grid[0]) || res[x][y] != -1 { 36 | return 37 | } 38 | res[x][y] = cost 39 | *queue = append(*queue, []int{x, y}) 40 | next := grid[x][y] - 1 41 | dfs(grid, res, x+shift[next][0], y+shift[next][1], cost, queue) 42 | } 43 | -------------------------------------------------------------------------------- /Problems/1373. Maximum Sum BST in Binary Tree/1373. Maximu Sum BST in Binary Tree.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "math" 4 | import . "LeetCode-GoSol/Utils" 5 | 6 | type comp struct { 7 | isBST bool 8 | min, max int 9 | sum int 10 | } 11 | 12 | func maxSumBST(root *TreeNode) int { 13 | res := 0 14 | helper(root, &res) 15 | return res 16 | } 17 | 18 | func helper(root *TreeNode, res *int) comp { 19 | if root == nil { 20 | return comp{true, math.MaxInt32, math.MinInt32, 0} 21 | } 22 | left := helper(root.Left, res) 23 | right := helper(root.Right, res) 24 | bst := false 25 | if left.isBST && right.isBST && root.Val < right.min && root.Val > left.max { 26 | bst = true 27 | } 28 | sum := 0 29 | if bst { 30 | sum = root.Val + left.sum + right.sum 31 | *res = max(*res, sum) 32 | return comp{true, min(left.min, root.Val), max(right.max, root.Val), sum} 33 | } 34 | return comp{false, min(left.min, root.Val), max(right.max, root.Val), sum} 35 | } 36 | 37 | func min(a, b int) int { 38 | if a < b { 39 | return a 40 | } 41 | return b 42 | } 43 | 44 | func max(a, b int) int { 45 | if a > b { 46 | return a 47 | } 48 | return b 49 | } 50 | -------------------------------------------------------------------------------- /Problems/1383. Maximum Performance of a Team/1383. Maximu, Performance of a Team.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "container/heap" 5 | "sort" 6 | ) 7 | 8 | type minHeap []int 9 | 10 | func (min minHeap) Len() int { 11 | return len(min) 12 | } 13 | 14 | func (min minHeap) Swap(i, j int) { 15 | min[i], min[j] = min[j], min[i] 16 | } 17 | 18 | func (min minHeap) Less(i, j int) bool { 19 | return min[i] < min[j] 20 | } 21 | 22 | func (min *minHeap) Push(x interface{}) { 23 | *min = append(*min, x.(int)) 24 | } 25 | 26 | func (min *minHeap) Pop() interface{} { 27 | x := (*min)[len(*min)-1] 28 | *min = (*min)[0 : len(*min)-1] 29 | return x 30 | } 31 | 32 | type pair struct { 33 | s int 34 | e int 35 | } 36 | 37 | func maxPerformance(n int, speed []int, efficiency []int, k int) int { 38 | mod := int(1e9) + 7 39 | m := minHeap{} 40 | heap.Init(&m) 41 | arr := make([]pair, n) 42 | for i := range speed { 43 | arr[i] = pair{speed[i], efficiency[i]} 44 | } 45 | sort.Slice(arr, func(a, b int) bool { 46 | if arr[a].e == arr[b].e { 47 | return arr[a].s > arr[b].s 48 | } else { 49 | return arr[a].e > arr[b].e 50 | } 51 | }) 52 | sum := 0 53 | res := 0 54 | for i := range arr { 55 | if m.Len() == k { 56 | sum -= heap.Pop(&m).(int) 57 | } 58 | heap.Push(&m, arr[i].s) 59 | sum += arr[i].s 60 | res = max(res, sum*arr[i].e) 61 | } 62 | return res % mod 63 | } 64 | 65 | func max(a, b int) int { 66 | if a > b { 67 | return a 68 | } 69 | return b 70 | } 71 | -------------------------------------------------------------------------------- /Problems/1388. Pizza WIth 3n Slices/1388. Pizza With 3n Slices.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func maxSizeSlices(slices []int) int { 4 | return max(helper(slices[0:len(slices)-1]), helper(slices[1:len(slices)])) 5 | } 6 | 7 | func helper(slices []int) int { 8 | m := len(slices) 9 | n := (m + 1) / 3 10 | dp := make([][]int, m+1) 11 | for i := range dp { 12 | dp[i] = make([]int, n+1) 13 | } 14 | dp[1][1] = slices[0] 15 | for i := 2; i <= m; i++ { 16 | for j := 1; j <= n; j++ { 17 | dp[i][j] = max(dp[i-1][j], dp[i-2][j-1]+slices[i-1]) 18 | } 19 | } 20 | return dp[m][n] 21 | } 22 | 23 | func max(a, b int) int { 24 | if a > b { 25 | return a 26 | } 27 | return b 28 | } 29 | 30 | // same as house robber ii 31 | -------------------------------------------------------------------------------- /Problems/1391. Check if There is a Valid Path in a Grid/1391. Check if There is a Valid Path in a Grid.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func hasValidPath(grid [][]int) bool { 4 | m := len(grid) 5 | n := len(grid[0]) 6 | root := make([]int, m*n) 7 | for i := range root { 8 | root[i] = i 9 | } 10 | for i := range grid { 11 | for j := range grid[i] { 12 | switch grid[i][j] { 13 | case 1: 14 | { 15 | if j > 0 && (grid[i][j-1] == 1 || grid[i][j-1] == 4 || grid[i][j-1] == 6) { 16 | connect(i*n+j, i*n+j-1, root) 17 | } 18 | if j < n-1 && (grid[i][j+1] == 1 || grid[i][j+1] == 3 || grid[i][j+1] == 5) { 19 | connect(i*n+j, i*n+j+1, root) 20 | } 21 | } 22 | case 2: 23 | { 24 | if i > 0 && (grid[i-1][j] == 2 || grid[i-1][j] == 3 || grid[i-1][j] == 4) { 25 | connect(i*n+j, (i-1)*n+j, root) 26 | } 27 | if i < m-1 && (grid[i+1][j] == 2 || grid[i+1][j] == 5 || grid[i+1][j] == 6) { 28 | connect(i*n+j, i*n+j+n, root) 29 | } 30 | } 31 | case 3: 32 | { 33 | if j > 0 && (grid[i][j-1] == 1 || grid[i][j-1] == 4 || grid[i][j-1] == 6) { 34 | connect(i*n+j, i*n+j-1, root) 35 | } 36 | if i < m-1 && (grid[i+1][j] == 2 || grid[i+1][j] == 5 || grid[i+1][j] == 6) { 37 | connect(i*n+j, i*n+j+n, root) 38 | } 39 | } 40 | case 4: 41 | { 42 | if j < n-1 && (grid[i][j+1] == 1 || grid[i][j+1] == 3 || grid[i][j+1] == 5) { 43 | connect(i*n+j, i*n+j+1, root) 44 | } 45 | if i < m-1 && (grid[i+1][j] == 2 || grid[i+1][j] == 5 || grid[i+1][j] == 6) { 46 | connect(i*n+j, i*n+j+n, root) 47 | } 48 | } 49 | case 5: 50 | { 51 | if i > 0 && (grid[i-1][j] == 2 || grid[i-1][j] == 3 || grid[i-1][j] == 4) { 52 | connect(i*n+j, (i-1)*n+j, root) 53 | } 54 | if j > 0 && (grid[i][j-1] == 1 || grid[i][j-1] == 4 || grid[i][j-1] == 6) { 55 | connect(i*n+j, i*n+j-1, root) 56 | } 57 | } 58 | case 6: 59 | { 60 | if i > 0 && (grid[i-1][j] == 2 || grid[i-1][j] == 3 || grid[i-1][j] == 4) { 61 | connect(i*n+j, (i-1)*n+j, root) 62 | } 63 | if j < n-1 && (grid[i][j+1] == 1 || grid[i][j+1] == 3 || grid[i][j+1] == 5) { 64 | connect(i*n+j, i*n+j+1, root) 65 | } 66 | } 67 | } 68 | } 69 | } 70 | return connect(0, m*n-1, root) 71 | } 72 | 73 | func connect(a, b int, root []int) bool { 74 | ra := find(a, root) 75 | rb := find(b, root) 76 | if ra != rb { 77 | root[ra] = rb 78 | return false 79 | } 80 | return true 81 | } 82 | 83 | func find(a int, root []int) int { 84 | if root[a] == a { 85 | return a 86 | } 87 | root[a] = find(root[a], root) 88 | return root[a] 89 | } 90 | -------------------------------------------------------------------------------- /Problems/1392. Longest Happy Prefix/1392. Longest Happy Prefix.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func longestPrefix(s string) string { 4 | pmt := getPMT(s) 5 | n := len(s) 6 | if n < 2 { 7 | return "" 8 | } 9 | return s[0:pmt[len(pmt)-1]] 10 | } 11 | 12 | func getPMT(s string) []int { 13 | n := len(s) 14 | pmt := make([]int, n) 15 | pmt[0] = 0 16 | i := 1 17 | j := 0 18 | for i < n { 19 | if s[i] == s[j] { 20 | pmt[i] = j + 1 21 | j++ 22 | i++ 23 | } else if j == 0 { 24 | pmt[i] = 0 25 | i++ 26 | } else { 27 | j = pmt[j-1] 28 | } 29 | } 30 | return pmt 31 | } 32 | -------------------------------------------------------------------------------- /Problems/1400. Construct K Palindrome Strings/1400. Construct K Palindrome Strings.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | // count the number of odd occurrence 4 | // e.g. if there is one odd occurrence character, then the number of palindrome must be at least 1 5 | // the number of odd occurrence character must be no larger than k 6 | // and the length of string must be no smaller than k 7 | func canConstruct(s string, k int) bool { 8 | cnt := map[byte]int{} 9 | for i := range s { 10 | cnt[s[i]]++ 11 | } 12 | odd := 0 13 | for _, v := range cnt { 14 | if v%2 != 0 { 15 | odd++ 16 | } 17 | } 18 | return k <= len(s) && odd <= k 19 | } 20 | -------------------------------------------------------------------------------- /Problems/1401. Circle and Rectangle Overlapping/1401. Circle and Rectangle Overlapping.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func checkOverlap(radius int, x_center int, y_center int, x1 int, y1 int, x2 int, y2 int) bool { 4 | //find the closet point on rectangle to the circle 5 | cx := x_center 6 | cy := y_center 7 | if x1 < x_center { 8 | cx = min(x_center, x2) 9 | } else { 10 | cx = x1 11 | } 12 | if y1 < y_center { 13 | cy = min(y_center, y2) 14 | } else { 15 | cy = y1 16 | } 17 | distx := x_center - cx 18 | disty := y_center - cy 19 | return (distx*distx + disty*disty) <= (radius * radius) 20 | } 21 | 22 | func min(a, b int) int { 23 | if a < b { 24 | return a 25 | } 26 | return b 27 | } 28 | 29 | func max(a, b int) int { 30 | if a < b { 31 | return b 32 | } 33 | return a 34 | } 35 | -------------------------------------------------------------------------------- /Problems/1402. Reducing Dishes/1402. Reducing Dishes.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "sort" 4 | 5 | func maxSatisfaction(satisfaction []int) int { 6 | res := 0 7 | sort.Ints(satisfaction) 8 | posSum := 0 9 | posPos := -1 10 | for i := range satisfaction { 11 | if satisfaction[i] >= 0 && posPos == -1 { 12 | posPos = i 13 | } 14 | if satisfaction[i] >= 0 { 15 | posSum += satisfaction[i] 16 | res += (i - posPos + 1) * satisfaction[i] 17 | } 18 | } 19 | curRes := res 20 | for i := 1; i <= posPos; i++ { 21 | minus := 0 22 | for j := 1; j <= i; j++ { 23 | minus += (i - j + 1) * satisfaction[posPos-j] 24 | } 25 | res = max(res, curRes+minus+i*posSum) 26 | } 27 | return res 28 | } 29 | 30 | func max(a, b int) int { 31 | if a > b { 32 | return a 33 | } 34 | return b 35 | } 36 | -------------------------------------------------------------------------------- /Problems/1404. Number of Steps to Reduce a Number in Binary Representation to One/1404. Number of Steps to Reduce a Number in Binary Representation to One.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func numSteps(s string) int { 4 | n := len(s) 5 | if n == 1 { 6 | return 0 7 | } 8 | cnt := 0 9 | ss := []byte(s) 10 | for i := len(ss) - 1; i > 0; { 11 | if ss[i] == '0' { 12 | cnt++ 13 | i-- 14 | } else { 15 | cnt++ 16 | //change '1' to '0' 17 | for ss[i] == '1' && i > 0 { 18 | //count how many zeroes in the tail 19 | cnt++ 20 | i-- 21 | } 22 | if i == 0 { 23 | cnt++ 24 | return cnt 25 | } 26 | ss[i] = '1' 27 | } 28 | } 29 | return cnt 30 | } 31 | -------------------------------------------------------------------------------- /Problems/1405. Longest Happy String/1405. Longest Happy String.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "container/heap" 5 | ) 6 | 7 | type pair struct { 8 | c byte 9 | cnt int 10 | } 11 | 12 | type maxHeap []pair 13 | 14 | func (m maxHeap) Len() int { 15 | return len(m) 16 | } 17 | 18 | func (m maxHeap) Less(a, b int) bool { 19 | return m[a].cnt > m[b].cnt 20 | } 21 | 22 | func (m maxHeap) Swap(a, b int) { 23 | m[a], m[b] = m[b], m[a] 24 | } 25 | 26 | func (m *maxHeap) Push(x interface{}) { 27 | *m = append(*m, x.(pair)) 28 | } 29 | 30 | func (m *maxHeap) Pop() interface{} { 31 | n := len(*m) 32 | x := (*m)[n-1] 33 | *m = (*m)[0 : n-1] 34 | return x 35 | } 36 | 37 | func longestDiverseString(a int, b int, c int) string { 38 | m := &maxHeap{} 39 | heap.Init(m) 40 | if a > 0 { 41 | heap.Push(m, pair{'a', a}) 42 | } 43 | if b > 0 { 44 | heap.Push(m, pair{'b', b}) 45 | } 46 | if c > 0 { 47 | heap.Push(m, pair{'c', c}) 48 | } 49 | sb := []byte{} 50 | for m.Len() > 0 { 51 | first := heap.Pop(m).(pair) 52 | if len(sb) > 0 && sb[len(sb)-1] == first.c { 53 | if m.Len() == 0 { 54 | return string(sb) 55 | } 56 | second := heap.Pop(m).(pair) 57 | 58 | sb = append(sb, second.c) 59 | second.cnt-- 60 | if second.cnt != 0 { 61 | heap.Push(m, second) 62 | } 63 | heap.Push(m, first) 64 | } else { 65 | limit := min(2, first.cnt) 66 | for i := 0; i < limit; i++ { 67 | first.cnt-- 68 | sb = append(sb, first.c) 69 | } 70 | if first.cnt != 0 { 71 | heap.Push(m, first) 72 | } 73 | } 74 | } 75 | return string(sb) 76 | } 77 | 78 | func min(a, b int) int { 79 | if a > b { 80 | return b 81 | } 82 | return a 83 | } 84 | -------------------------------------------------------------------------------- /Problems/1406. Stone Game III/1406. Stone Game III.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func stoneGameIII(stoneValue []int) string { 4 | n := len(stoneValue) 5 | dp := make([]int, n) 6 | res := helper(stoneValue, dp, 0) 7 | if res > 0 { 8 | return "Alice" 9 | } 10 | if res == 0 { 11 | return "Tie" 12 | } 13 | return "Bob" 14 | } 15 | 16 | func helper(stoneValue []int, dp []int, index int) int { 17 | if index >= len(stoneValue) { 18 | return 0 19 | } 20 | if dp[index] != 0 { 21 | return dp[index] 22 | } 23 | res := stoneValue[index] - helper(stoneValue, dp, index+1) 24 | if index+1 < len(stoneValue) { 25 | res = max(res, stoneValue[index]+stoneValue[index+1]-helper(stoneValue, dp, index+2)) 26 | } 27 | if index+2 < len(stoneValue) { 28 | res = max(res, stoneValue[index]+stoneValue[index+1]+stoneValue[index+2]-helper(stoneValue, dp, index+3)) 29 | } 30 | dp[index] = res 31 | return res 32 | } 33 | 34 | func max(a, b int) int { 35 | if a < b { 36 | return b 37 | } 38 | return a 39 | } 40 | -------------------------------------------------------------------------------- /Problems/1411. Number of Ways to Paint N * 3 Grid/1411. Number of Ways to Paint N * 3 Grid.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func numOfWays(n int) int { 4 | // if the previous row has three color, e.g. ABC 5 | // the next row can be in two or three colors 6 | // 3color: CAB BCA 7 | // 2color: BAB BCB 8 | 9 | // if the previous row has two color, e.g. ABA 10 | // the next row can also in two/three colors 11 | // 2color: CAC BAB BCB 12 | // 3color: CAB, BAC 13 | 14 | // so we can get this conclusion 15 | // if the current row has three color, then it comes from 2*prevTwoColor + 2*prevThreeColor 16 | // if the current row has two color, then it comes from 2*prevThreeColor + 3*prevTwoColor 17 | two := make([]int, n) 18 | three := make([]int, n) 19 | two[0] = 6 20 | three[0] = 6 21 | mod := int(1e9) + 7 22 | for i := 1; i < n; i++ { 23 | two[i] = 3*two[i-1] + 2*three[i-1] 24 | two[i] %= mod 25 | three[i] = 2*two[i-1] + 2*three[i-1] 26 | three[i] %= mod 27 | } 28 | return (two[n-1] + three[n-1]) % (int(1e9) + 7) 29 | } 30 | 31 | func numOfWays2(n int) int { 32 | mod := int(1e9) + 7 33 | //for one row there are 3^3 combinations 34 | //get the validity of these 27 pattern 35 | valid := make([]bool, 27) 36 | for i := range valid { 37 | a := i / 9 //change every 9 pattern 38 | b := (i / 3) % 3 //change every 3 pattern 39 | c := i % 3 //change every 1 pattern 40 | if a != b && b != c { 41 | valid[i] = true 42 | } 43 | } 44 | //get the valid table for next row 45 | vv := make([][]bool, 27) 46 | for i := range vv { 47 | vv[i] = make([]bool, 27) 48 | if valid[i] { 49 | for j := range vv[i] { 50 | if valid[j] { 51 | a := i / 9 52 | b := j / 9 53 | c := (i / 3) % 3 54 | d := (j / 3) % 3 55 | e := i % 3 56 | f := j % 3 57 | if a != b && c != d && e != f { 58 | vv[i][j] = true 59 | } 60 | } 61 | } 62 | } 63 | } 64 | dp := make([][]int, n) 65 | for i := range dp { 66 | dp[i] = make([]int, 27) 67 | } 68 | for j := range dp[0] { 69 | if valid[j] { 70 | dp[0][j] = 1 71 | } 72 | } 73 | for i := 1; i < n; i++ { 74 | for j := 0; j < 27; j++ { 75 | for k := 0; k < 27; k++ { 76 | if vv[k][j] { 77 | dp[i][j] += dp[i-1][k] 78 | dp[i][j] %= mod 79 | } 80 | } 81 | } 82 | } 83 | res := 0 84 | for i := range dp[n-1] { 85 | res += dp[n-1][i] 86 | res %= mod 87 | } 88 | return res 89 | } 90 | -------------------------------------------------------------------------------- /Problems/1419. Minimu Number of Frogs Croaking/1419. Minimum Number of Frogs Croaking.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func minNumberOfFrogs(croakOfFrogs string) int { 4 | tb := make(map[byte]int, 5) 5 | prev := map[byte]byte{ 6 | 'c': '0', 7 | 'r': 'c', 8 | 'o': 'r', 9 | 'a': 'o', 10 | 'k': 'a', 11 | } 12 | tb['0'] = 100000 13 | tb['c'] = 0 14 | tb['r'] = 0 15 | tb['o'] = 0 16 | tb['a'] = 0 17 | tb['k'] = 0 18 | cnt := 0 19 | res := 0 20 | for i := range croakOfFrogs { 21 | cur := croakOfFrogs[i] 22 | if tb[cur] >= tb[prev[cur]] { 23 | return -1 24 | } 25 | tb[croakOfFrogs[i]]++ 26 | get := true 27 | if croakOfFrogs[i] == 'c' { 28 | cnt++ 29 | res = max(res, cnt) 30 | } 31 | if cur == 'k' { 32 | for _, v := range tb { 33 | if v == 0 { 34 | get = false 35 | } 36 | } 37 | if get { 38 | for k := range tb { 39 | tb[k]-- 40 | } 41 | cnt-- 42 | } 43 | } 44 | } 45 | for k, v := range tb { 46 | if v > 0 && k != '0' { 47 | return -1 48 | } 49 | } 50 | return res 51 | } 52 | 53 | func max(a, b int) int { 54 | if a > b { 55 | return a 56 | } 57 | return b 58 | } 59 | -------------------------------------------------------------------------------- /Problems/1420. Build Array Where You Can FInd the Maximum Exactly K Comparisons/1420. Build Array Where You Can FInd The Maximum Exactly K Comparisons.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func numOfArrays(n int, m int, K int) int { 4 | dp := make([][][]int, n+1) 5 | for i := range dp { 6 | dp[i] = make([][]int, m+1) 7 | for j := range dp[i] { 8 | dp[i][j] = make([]int, K+1) 9 | } 10 | } 11 | mod := int(1e9) + 7 12 | //dp[i][j][k] -> the first ith elements, with j is the largest value, and current search cost is k 13 | //if arr[i] is the current largest, dp[i][j][k] += sum(dp[i-1][1....j-1][k-1]) -> arr[i]==j 14 | //if arr[i] is not the current largest, dp[i][j][k] += j*(dp[i-1][j][k] -> 15 | // arr[i]<=j and 1:i-1 elements have largest value j. There will be j kinds of choice for arr[i] 16 | for j := 1; j <= m; j++ { 17 | dp[1][j][1] = 1 18 | } 19 | for i := 2; i <= n; i++ { 20 | for j := 1; j <= m; j++ { 21 | for k := 1; k <= K; k++ { 22 | for l := 1; l < j-1; l++ { 23 | dp[i][j][k] += dp[i-1][l][k-1] 24 | dp[i][j][k] %= mod 25 | } 26 | dp[i][j][k] += j * dp[i-1][j][k] 27 | dp[i][j][k] %= mod 28 | } 29 | } 30 | } 31 | res := 0 32 | for j := 1; j < m; j++ { 33 | res += dp[n][j][K] 34 | res %= mod 35 | } 36 | return res 37 | } 38 | -------------------------------------------------------------------------------- /Problems/1424. Diagonal Traversal II/1424. Diagonal Traversal II.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "sort" 4 | 5 | func findDiagonalOrder(nums [][]int) []int { 6 | m := len(nums) 7 | if m == 0 { 8 | return []int{} 9 | } 10 | total := 0 11 | pos := make([][]int, 0) 12 | for i := range nums { 13 | l := len(nums[i]) 14 | total += l 15 | temp := make([][]int, l) 16 | for j := 0; j < l; j++ { 17 | temp[j] = []int{i, j} 18 | } 19 | pos = append(pos, temp...) 20 | } 21 | sort.SliceStable(pos, func(a, b int) bool { 22 | if pos[a][0]+pos[a][1] == pos[b][0]+pos[b][1] { 23 | return a > b 24 | } else { 25 | return pos[a][0]+pos[a][1] < pos[b][0]+pos[b][1] 26 | } 27 | }) 28 | res := make([]int, total) 29 | for i := range pos { 30 | res[i] = nums[pos[i][0]][pos[i][1]] 31 | } 32 | return res 33 | } 34 | 35 | func findDiagonalOrder2(nums [][]int) []int { 36 | m := len(nums) 37 | if m == 0 { 38 | return []int{} 39 | } 40 | visited := make([][]bool, m) 41 | total := 0 42 | for i := range nums { 43 | l := len(nums[i]) 44 | total += l 45 | visited[i] = make([]bool, l) 46 | } 47 | res := make([]int, total) 48 | queue := make([][]int, 1) 49 | queue[0] = []int{0, 0} 50 | visited[0][0] = true 51 | cnt := 0 52 | for len(queue) > 0 { 53 | cur := queue[0] 54 | x := cur[0] 55 | y := cur[1] 56 | res[cnt] = nums[x][y] 57 | cnt++ 58 | if x+1 < m && len(nums[x+1]) > y && !visited[x+1][y] { 59 | queue = append(queue, []int{x + 1, y}) 60 | visited[x+1][y] = true 61 | } 62 | if y+1 < len(nums[x]) && !visited[x][y+1] { 63 | queue = append(queue, []int{x, y + 1}) 64 | visited[x][y+1] = true 65 | } 66 | queue = queue[1:] 67 | } 68 | return res 69 | } 70 | -------------------------------------------------------------------------------- /Problems/1434. Number of Ways to Wear Different Hats to Each Other /1434. Number of Ways to Wear Different Hats to Each Other.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func numberWays(hats [][]int) int { 4 | mod := int(1e9) + 7 5 | m := len(hats) 6 | htp := make([][]int, 41) 7 | //htp[i] is the people who like the ith hat 8 | for i := range hats { 9 | for j := range hats[i] { 10 | if htp[hats[i][j]] == nil { 11 | htp[hats[i][j]] = make([]int, 1) 12 | htp[hats[i][j]][0] = i 13 | } else { 14 | htp[hats[i][j]] = append(htp[hats[i][j]], i) 15 | } 16 | } 17 | } 18 | dp := make([][]int, 41) 19 | for i := range dp { 20 | //use binary to identify the people hats state (e.g. 1010 means the second and fourth people have assigned hats 21 | dp[i] = make([]int, 1< 0 && nums[mn.Back().Value.(int)] >= cur { 17 | mn.Remove(mn.Back()) 18 | } 19 | for mx.Len() > 0 && nums[mx.Back().Value.(int)] <= cur { 20 | mx.Remove(mx.Back()) 21 | } 22 | mn.PushBack(r) 23 | mx.PushBack(r) 24 | for nums[mx.Front().Value.(int)]-nums[mn.Front().Value.(int)] > limit { 25 | l++ 26 | for mx.Front().Value.(int) < l { 27 | mx.Remove(mx.Front()) 28 | } 29 | for mn.Front().Value.(int) < l { 30 | mn.Remove(mn.Front()) 31 | } 32 | } 33 | res = max(res, r-l+1) 34 | r++ 35 | } 36 | return res 37 | } 38 | 39 | func max(a, b int) int { 40 | if a < b { 41 | return b 42 | } 43 | return a 44 | } 45 | -------------------------------------------------------------------------------- /Problems/149. Max Points on a Line/149. Max Points on a Line.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "strconv" 4 | 5 | func maxPoints(points [][]int) int { 6 | max := 0 7 | for i, cur := range points { 8 | curmax := 0 9 | overlap := 0 10 | ht := make(map[string]int) 11 | 12 | for j, next := range points { 13 | if i == j { 14 | continue 15 | } 16 | distX := cur[0] - next[0] 17 | distY := cur[1] - next[1] 18 | if distX == 0 && distY == 0 { 19 | overlap++ 20 | continue 21 | } 22 | gcdXY := gcd(distX, distY) 23 | distX /= gcdXY 24 | distY /= gcdXY 25 | cur := strconv.Itoa(distX) + " " + strconv.Itoa(distY) 26 | ht[cur]++ 27 | if ht[cur] > curmax { 28 | curmax = ht[cur] 29 | } 30 | } 31 | if max < curmax+overlap+1 { 32 | max = curmax + overlap + 1 33 | } 34 | } 35 | return max 36 | } 37 | 38 | func gcd(a int, b int) int { 39 | if b == 0 { 40 | return a 41 | } 42 | return gcd(b, a%b) 43 | } 44 | -------------------------------------------------------------------------------- /Problems/166. Fraction to Recurring Decimal/166. Fraction to Recurring Decimal.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "math" 5 | "strconv" 6 | ) 7 | 8 | func fractionToDecimal(numerator int, denominator int) string { 9 | dividend := float64(numerator) 10 | divisor := float64(denominator) 11 | if math.Mod(dividend, divisor) == 0 { 12 | res := strconv.Itoa(int((dividend / divisor))) 13 | return res 14 | } 15 | sign := 1 16 | if divisor < 0 { 17 | divisor = -1 * divisor 18 | sign *= -1 19 | } 20 | if dividend < 0 { 21 | dividend = -1 * dividend 22 | sign *= -1 23 | } 24 | res := "" 25 | res = res + strconv.Itoa(int(dividend/divisor)) 26 | fraction := "" 27 | dividend = math.Mod(dividend, divisor) 28 | ht := make(map[float64]int) 29 | pos := 0 30 | for _, ok := ht[dividend]; !ok && dividend != 0; _, ok = ht[dividend] { 31 | ht[dividend] = pos 32 | pos++ 33 | dividend *= 10 34 | fraction = fraction + strconv.Itoa(int(dividend/divisor)) 35 | dividend = math.Mod(dividend, divisor) 36 | } 37 | if dividend == 0 { 38 | res = res + "." + fraction 39 | } else { 40 | pos = ht[dividend] 41 | res = res + "." + fraction[0:pos] + "(" + fraction[pos:] + ")" 42 | } 43 | if sign == -1 { 44 | res = "-" + res 45 | } 46 | return res 47 | } 48 | -------------------------------------------------------------------------------- /Problems/17. Letter Combinations of a Phone Number/17. Letter Combinations of a Phone Number.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "strconv" 4 | 5 | func letterCombinations(digits string) []string { 6 | ht := make(map[int]string) 7 | ht[2] = "abc" 8 | ht[3] = "def" 9 | ht[4] = "ghi" 10 | ht[5] = "jkl" 11 | ht[6] = "mno" 12 | ht[7] = "pqrs" 13 | ht[8] = "tuv" 14 | ht[9] = "wxyz" 15 | queue := []string{""} 16 | for len(digits) > 0 { 17 | cur, _ := strconv.Atoi(digits[0:1]) 18 | digits = digits[1:] 19 | size := len(queue) 20 | for i := 0; i < size; i++ { 21 | s := queue[i] 22 | for j := range ht[cur] { 23 | queue = append(queue, s+string(ht[cur][j])) 24 | } 25 | } 26 | queue = queue[size:] 27 | } 28 | return queue 29 | } 30 | -------------------------------------------------------------------------------- /Problems/174. Dungeon Game/174. Dungeon Game.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "math" 4 | 5 | func calculateMinimumHP(dungeon [][]int) int { 6 | m := len(dungeon) 7 | n := len(dungeon[0]) 8 | dp := make([][]int, m) 9 | for i := range dp { 10 | dp[i] = make([]int, n) 11 | } 12 | if dungeon[m-1][n-1] > 0 { 13 | dp[m-1][n-1] = 1 14 | } else { 15 | dp[m-1][n-1] = -dungeon[m-1][n-1] + 1 16 | } 17 | for j := n - 2; j >= 0; j-- { 18 | dp[m-1][j] = dp[m-1][j+1] 19 | if dungeon[m-1][j] > dp[m-1][j] { 20 | dp[m-1][j] = 1 21 | } else { 22 | dp[m-1][j] -= dungeon[m-1][j] 23 | } 24 | } 25 | for i := m - 2; i >= 0; i-- { 26 | for j := n - 1; j >= 0; j-- { 27 | dp[i][j] = math.MaxInt32 28 | if i < m-1 { 29 | dp[i][j] = min(dp[i][j], dp[i+1][j]) 30 | } 31 | if j < n-1 { 32 | dp[i][j] = min(dp[i][j], dp[i][j+1]) 33 | } 34 | if dungeon[i][j] > dp[i][j] { 35 | dp[i][j] = 1 36 | } else { 37 | dp[i][j] -= dungeon[i][j] 38 | } 39 | } 40 | } 41 | return dp[0][0] 42 | } 43 | 44 | func min(a, b int) int { 45 | if a < b { 46 | return a 47 | } 48 | return b 49 | } 50 | -------------------------------------------------------------------------------- /Problems/189. Rotate Array/189. Rotate Array.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func rotate(nums []int, k int) { 4 | reverse(0, len(nums)-1, &nums) 5 | k %= len(nums) 6 | reverse(0, k-1, &nums) 7 | reverse(k, len(nums)-1, &nums) 8 | } 9 | 10 | func reverse(s, e int, nums *[]int) { 11 | for s < e { 12 | (*nums)[s], (*nums)[e] = (*nums)[e], (*nums)[s] 13 | s++ 14 | e-- 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Problems/202. Happy Number/202. Happy Number.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func isHappy(n int) bool { 4 | set := make(map[int]bool) 5 | for _, ok := set[n]; !ok; _, ok = set[n] { 6 | set[n] = true 7 | if n == 1 { 8 | return true 9 | } 10 | sum := 0 11 | for n > 0 { 12 | sum += (n % 10) * (n % 10) 13 | n /= 10 14 | } 15 | n = sum 16 | } 17 | return false 18 | } 19 | -------------------------------------------------------------------------------- /Problems/206. Reverse Linked List/206. Reverse LInked List.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | . "LeetCode-GoSol/Utils" 5 | ) 6 | 7 | func reverseList(head *ListNode) *ListNode { 8 | cur := head 9 | var prev *ListNode 10 | for cur != nil { 11 | next := cur.Next 12 | cur.Next = prev 13 | prev = cur 14 | cur = next 15 | } 16 | return prev 17 | } 18 | 19 | /* 20 | func reverseList(head *ListNode) *ListNode { 21 | if head == nil || head.Next == nil { 22 | return head 23 | } 24 | next := reverseList(head.Next) 25 | head.Next.Next = head 26 | head.Next = nil 27 | return next 28 | } 29 | */ 30 | -------------------------------------------------------------------------------- /Problems/215. Kth Largest Element in an Array/215. Kth Largest Element in an Array.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "container/heap" 5 | ) 6 | 7 | //func findKthLargest(nums []int, k int) int { 8 | // l := 0 9 | // r := len(nums) - 1 10 | // return quickSelect(nums, l, r, k) 11 | //} 12 | // 13 | //func quickSelect(a []int, l, r, k int) int { 14 | // pivot := l 15 | // for i := l; i < r; i++ { 16 | // if a[i] >= a[r] { 17 | // a[i], a[pivot] = a[pivot], a[i] 18 | // pivot += 1 19 | // } 20 | // } 21 | // a[pivot], a[r] = a[r], a[pivot] 22 | // if pivot+1 == k { 23 | // return a[pivot] 24 | // } else if pivot+1 > k { 25 | // return quickSelect(a, l, pivot-1, k) 26 | // } else { 27 | // return quickSelect(a, pivot+1, r, k) 28 | // } 29 | //} 30 | 31 | func findKthLargest(nums []int, k int) int { 32 | pq := &maxHeap{} 33 | heap.Init(pq) 34 | 35 | for _, v := range nums { 36 | heap.Push(pq, v) 37 | if pq.Len() > k { 38 | heap.Pop(pq) 39 | } 40 | } 41 | return heap.Pop(pq).(int) 42 | } 43 | 44 | type maxHeap []int 45 | 46 | func (pq maxHeap) Len() int { 47 | return len(pq) 48 | } 49 | 50 | func (pq maxHeap) Less(i, j int) bool { 51 | return pq[i] < pq[j] 52 | } 53 | 54 | func (pq maxHeap) Swap(i, j int) { 55 | pq[i], pq[j] = pq[j], pq[i] 56 | } 57 | 58 | func (pq *maxHeap) Push(x interface{}) { 59 | *pq = append(*pq, x.(int)) 60 | } 61 | 62 | func (pq *maxHeap) Pop() interface{} { 63 | x := (*pq)[len(*pq)-1] 64 | *pq = (*pq)[0 : len(*pq)-1] 65 | return x 66 | } 67 | -------------------------------------------------------------------------------- /Problems/223. Rectangle Area/223. Rectangle Area.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func computeArea(A int, B int, C int, D int, E int, F int, G int, H int) int { 4 | res := (C-A)*(D-B) + (G-E)*(H-F) 5 | dx := min(C, G) - max(A, E) 6 | dy := min(D, H) - max(B, F) 7 | if dx > 0 && dy > 0 { 8 | res -= dx * dy 9 | } 10 | return res 11 | } 12 | 13 | func max(a, b int) int { 14 | if a > b { 15 | return a 16 | } 17 | return b 18 | } 19 | 20 | func min(a, b int) int { 21 | if a > b { 22 | return b 23 | } 24 | return a 25 | } 26 | -------------------------------------------------------------------------------- /Problems/23. Merge k Sorted Lists/23. Merge k Sorted Lists.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | . "LeetCode-GoSol/Utils" 5 | ) 6 | 7 | func mergeKLists(lists []*ListNode) *ListNode { 8 | end := len(lists) - 1 9 | if end == -1 { 10 | return nil 11 | } else { 12 | return multiMerge(lists, 0, end) 13 | } 14 | } 15 | 16 | func multiMerge(lists []*ListNode, start int, end int) *ListNode { 17 | if end == start { 18 | return lists[start] 19 | } 20 | mid := (end + start) / 2 21 | left := multiMerge(lists, start, mid) 22 | right := multiMerge(lists, mid+1, end) 23 | return merge(left, right) 24 | } 25 | 26 | func merge(l1, l2 *ListNode) *ListNode { 27 | if l1 == nil { 28 | return l2 29 | } 30 | if l2 == nil { 31 | return l1 32 | } 33 | if l1.Val < l2.Val { 34 | l1.Next = merge(l1.Next, l2) 35 | return l1 36 | } else { 37 | l2.Next = merge(l1, l2.Next) 38 | return l2 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Problems/233. Number of Digit One/233. Number of Digit One.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func countDigitOne(n int) int { 4 | q := n 5 | ans := 0 6 | x := 1 7 | for q > 0 { 8 | digit := q % 10 9 | q /= 10 10 | ans += q * x 11 | if digit == 1 { 12 | ans += n%x + 1 13 | } else if digit > 1 { 14 | ans += x 15 | } 16 | x *= 10 17 | } 18 | return ans 19 | } 20 | 21 | /* 22 | if n = xyzdabc 23 | and we are considering the occurrence of one on thousand, it should be: 24 | 25 | (1) xyz * 1000 if d == 0 26 | (2) xyz * 1000 + abc + 1 if d == 1 27 | (3) xyz * 1000 + 1000 if d > 1 28 | */ 29 | -------------------------------------------------------------------------------- /Problems/264. Ugly Number II/264. Ugly Number II.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | import "container/heap" 5 | 6 | type minHeap []int 7 | 8 | func (m minHeap) Len() int { 9 | return len(m) 10 | } 11 | 12 | func (m minHeap) Less(a, b int) bool { 13 | return m[a] < m[b] 14 | } 15 | 16 | func (m minHeap) Swap(a, b int) { 17 | m[a], m[b] = m[b], m[a] 18 | } 19 | 20 | func (m *minHeap) Push(x interface{}) { 21 | *m = append(*m, x.(int)) 22 | } 23 | 24 | func (m *minHeap) Pop() interface{} { 25 | x := (*m)[len(*m)-1] 26 | *m = (*m)[0 : len(*m)-1] 27 | return x 28 | } 29 | func nthUglyNumber(n int) int { 30 | min := &minHeap{} 31 | heap.Init(min) 32 | heap.Push(min, 1) 33 | for i := 1; i < n; i++ { 34 | cur := heap.Pop(min).(int) 35 | for min.Len() > 0 && (*min)[0] == cur { 36 | heap.Pop(min) 37 | } 38 | heap.Push(min, cur*2) 39 | heap.Push(min, cur*3) 40 | heap.Push(min, cur*5) 41 | } 42 | return heap.Pop(min).(int) 43 | } 44 | */ 45 | func nthUglyNumber(n int) int { 46 | dp := make([]int, n) 47 | dp[0] = 1 48 | p2, p3, p5 := 0, 0, 0 49 | for i := 1; i < n; i++ { 50 | dp[i] = min(min(dp[p2]*2, dp[p3]*3), dp[p5]*5) 51 | if dp[i] == dp[p2]*2 { 52 | p2++ 53 | } 54 | if dp[i] == dp[p3]*3 { 55 | p3++ 56 | } 57 | if dp[i] == dp[p5]*5 { 58 | p5++ 59 | } 60 | } 61 | return dp[n-1] 62 | } 63 | 64 | func min(a, b int) int { 65 | if a < b { 66 | return a 67 | } 68 | return b 69 | } 70 | -------------------------------------------------------------------------------- /Problems/287. Find the Duplicate Number/287. Find the Duplicate Number.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func findDuplicate(nums []int) int { 4 | n := len(nums) 5 | l := 1 6 | r := n - 1 7 | for l < r { 8 | mid := (l + r) / 2 9 | cnt := 0 10 | for _, val := range nums { 11 | if mid >= val { 12 | cnt++ 13 | } 14 | } 15 | if cnt > mid { 16 | r = mid 17 | } else { 18 | l = mid + 1 19 | } 20 | } 21 | return l 22 | } 23 | -------------------------------------------------------------------------------- /Problems/300. Longest Increasing Subsequence/300. Longest Increasing Subsequence.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func lengthOfLIS(nums []int) int { 4 | n := len(nums) 5 | dp := make([]int, n) 6 | length := 0 7 | for i := range nums { 8 | idx := binarySearch(dp, nums[i], 0, length) 9 | if idx == length { 10 | length++ 11 | } 12 | dp[idx] = nums[i] 13 | } 14 | return length 15 | } 16 | 17 | func binarySearch(nums []int, target int, l, r int) int { 18 | for l < r { 19 | m := l + (r-l)/2 20 | if nums[m] < target { 21 | l = m + 1 22 | } else { 23 | r = m 24 | } 25 | } 26 | return l 27 | } 28 | -------------------------------------------------------------------------------- /Problems/31. Next Permutation/31. Next Permutation.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func nextPermutation(nums []int) { 4 | if len(nums) <= 1 { 5 | return 6 | } 7 | swapL := -1 8 | for i := len(nums) - 1; i >= 1; i-- { 9 | if nums[i-1] < nums[i] { 10 | swapL = i - 1 11 | break 12 | } 13 | } 14 | if swapL == -1 { 15 | reverse(nums, 0, len(nums)-1) 16 | } else { 17 | swapR := swapL + 1 18 | for i := swapL + 1; i < len(nums); i++ { 19 | if nums[i] > nums[swapL] && nums[i] <= nums[swapR] { 20 | swapR = i 21 | } 22 | } 23 | nums[swapL], nums[swapR] = nums[swapR], nums[swapL] 24 | reverse(nums, swapL+1, len(nums)-1) 25 | } 26 | } 27 | 28 | func reverse(nums []int, start, end int) { 29 | i := start 30 | j := end 31 | for i < j { 32 | nums[i], nums[j] = nums[j], nums[i] 33 | j-- 34 | i++ 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Problems/312. Burst Balloons/312. Burst Balloons.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func maxCoins(nums []int) int { 4 | n := len(nums) 5 | nn := make([]int, n+2) 6 | nn[0], nn[n+1] = 1, 1 7 | for i := 0; i < n; i++ { 8 | nn[i+1] = nums[i] 9 | } 10 | dp := make([][]int, n+2) 11 | for i := range dp { 12 | dp[i] = make([]int, n+2) 13 | } 14 | for j := 1; j <= n; j++ { 15 | for i := j; i >= 1; i-- { 16 | for k := i; k <= j; k++ { 17 | cur := nn[k] * nn[i-1] * nn[j+1] 18 | prev := dp[i][k-1] + dp[k+1][j] 19 | dp[i][j] = max(prev+cur, dp[i][j]) 20 | } 21 | } 22 | } 23 | return dp[1][n] 24 | } 25 | 26 | func max(a, b int) int { 27 | if a > b { 28 | return a 29 | } 30 | return b 31 | } 32 | -------------------------------------------------------------------------------- /Problems/329. Longest Increasing Path/329. Longest Increasing Path.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func longestIncreasingPath(matrix [][]int) int { 4 | shift := []int{0, 1, 0, -1, 0} 5 | var m = len(matrix) 6 | if m == 0 { 7 | return 0 8 | } 9 | var n = len(matrix[0]) 10 | if n == 0 { 11 | return 0 12 | } 13 | ind := make([][]int, m) 14 | for i := range ind { 15 | ind[i] = make([]int, n) 16 | } 17 | queue := make([][]int, 0) 18 | for i := range ind { 19 | for j := range ind[i] { 20 | cur := matrix[i][j] 21 | for k := 0; k < 4; k++ { 22 | nx := i + shift[k] 23 | ny := j + shift[k+1] 24 | if nx >= 0 && ny >= 0 && nx < m && ny < n && matrix[nx][ny] < cur { 25 | ind[i][j] += 1 26 | } 27 | } 28 | if ind[i][j] == 0 { 29 | queue = append(queue, []int{i, j}) 30 | } 31 | } 32 | } 33 | res := 0 34 | for len(queue) > 0 { 35 | res++ 36 | size := len(queue) 37 | for i := 0; i < size; i++ { 38 | cur := queue[i] 39 | for j := 0; j < 4; j++ { 40 | nx := cur[0] + shift[j] 41 | ny := cur[1] + shift[j+1] 42 | if nx >= 0 && ny >= 0 && nx < m && ny < n && matrix[cur[0]][cur[1]] < matrix[nx][ny] { 43 | ind[nx][ny]-- 44 | if ind[nx][ny] == 0 { 45 | queue = append(queue, []int{nx, ny}) 46 | } 47 | } 48 | 49 | } 50 | } 51 | queue = queue[size:] 52 | } 53 | return res 54 | } 55 | 56 | var shift = []int{0, 1, 0, -1, 0} 57 | 58 | func longestIncreasingPath2(matrix [][]int) int { 59 | m := len(matrix) 60 | if m == 0 { 61 | return 0 62 | } 63 | n := len(matrix[0]) 64 | if n == 0 { 65 | return 0 66 | } 67 | mem := make([][]int, m) 68 | for i := range mem { 69 | mem[i] = make([]int, n) 70 | } 71 | res := 0 72 | for i := range matrix { 73 | for j := range matrix[i] { 74 | res = max(res, helper(i, j, mem, matrix)) 75 | } 76 | } 77 | return res 78 | } 79 | 80 | func helper(x, y int, mem, matrix [][]int) int { 81 | if mem[x][y] != 0 { 82 | return mem[x][y] 83 | } 84 | res := 1 85 | mx := 0 86 | for i := 0; i < 4; i++ { 87 | nx := x + shift[i] 88 | ny := y + shift[i+1] 89 | if nx >= 0 && ny >= 0 && nx < len(mem) && ny < len(mem[0]) && matrix[x][y] > matrix[nx][ny] { 90 | mx = max(mx, helper(nx, ny, mem, matrix)) 91 | } 92 | } 93 | mem[x][y] = res + mx 94 | return res + mx 95 | } 96 | 97 | func max(a, b int) int { 98 | if a > b { 99 | return a 100 | } 101 | return b 102 | } 103 | -------------------------------------------------------------------------------- /Problems/335. Self Crossing/335. Self Crossing.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func isSelfCrossing(x []int) bool { 4 | if len(x) <= 3 { 5 | return false 6 | } 7 | for i := 3; i < len(x); i++ { 8 | if x[i] >= x[i-2] && x[i-1] <= x[i-3] { 9 | return true 10 | } 11 | if i >= 4 && x[i-1] == x[i-3] && x[i]+x[i-4] >= x[i-2] { 12 | return true 13 | } 14 | if i >= 5 && x[i-2] >= x[i-4] && x[i]+x[i-4] >= x[i-2] && x[i-1] <= x[i-3] && x[i-1]+x[i-5] >= x[i-3] { 15 | return true 16 | } 17 | } 18 | return false 19 | } 20 | -------------------------------------------------------------------------------- /Problems/365. Water and Jug Problem/365. Water and Jug Problem.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func canMeasureWater(x int, y int, z int) bool { 4 | if z == 0 { 5 | return true 6 | } 7 | if x+y < z { 8 | return false 9 | } 10 | return z%gcd(x, y) == 0 11 | } 12 | 13 | func gcd(a, b int) int { 14 | if b == 0 { 15 | return a 16 | } 17 | return gcd(b, a%b) 18 | } 19 | -------------------------------------------------------------------------------- /Problems/368. Largest Divisble Subset/368. Largest Divisble Subset.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "sort" 4 | 5 | type pair struct { 6 | prev int 7 | cnt int 8 | } 9 | 10 | func largestDivisibleSubset(nums []int) []int { 11 | n := len(nums) 12 | if n == 0 { 13 | return []int{} 14 | } 15 | sort.Ints(nums) 16 | dp := make([]pair, n) 17 | dp[0] = pair{-1, 1} 18 | maxCnt := 1 19 | maxPos := 0 20 | for i := 1; i < n; i++ { 21 | curCnt := 0 22 | curPrev := -1 23 | for j := i - 1; j >= 0; j-- { 24 | if nums[i]%nums[j] == 0 { 25 | if dp[j].cnt > curCnt { 26 | curCnt = dp[j].cnt 27 | curPrev = j 28 | } 29 | } 30 | } 31 | dp[i] = pair{curPrev, curCnt + 1} 32 | if dp[i].cnt > maxCnt { 33 | maxCnt = dp[i].cnt 34 | maxPos = i 35 | } 36 | } 37 | // fmt.Println(dp, maxCnt) 38 | res := make([]int, maxCnt) 39 | for maxPos != -1 { 40 | res[maxCnt-1] = nums[maxPos] 41 | maxCnt-- 42 | maxPos = dp[maxPos].prev 43 | } 44 | return res 45 | } 46 | 47 | func max(a, b int) int { 48 | if a > b { 49 | return a 50 | } 51 | return b 52 | } 53 | -------------------------------------------------------------------------------- /Problems/369. Plus One Linked List/Plus One Linked List.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import . "LeetCode-GoSol/Utils" 4 | 5 | func plusOne(head *ListNode) *ListNode { 6 | next := carry(head) 7 | if next { 8 | newHead := ListNode{1, head} 9 | return &newHead 10 | } else { 11 | return head 12 | } 13 | } 14 | 15 | func carry(head *ListNode) bool { 16 | if head == nil { 17 | return true 18 | } 19 | next := carry(head.Next) 20 | curVal := head.Val 21 | if next { 22 | curVal += 1 23 | } 24 | if curVal >= 10 { 25 | head.Val = curVal % 10 26 | return true 27 | } else { 28 | head.Val = curVal 29 | return false 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Problems/375. Guess Number Higher or Lower II/375. Guess Number Higher or Lower II.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func getMoneyAmount(n int) int { 4 | dp := make([][]int, n+1) 5 | for i := range dp { 6 | dp[i] = make([]int, n+1) 7 | } 8 | for j := 1; j <= n; j++ { 9 | for i := j - 1; i >= 1; i-- { 10 | dp[i][j] = min(i+dp[i+1][j], j+dp[i][j-1]) 11 | //choose the leftmost or rightmost number 12 | for k := i + 1; k < j; k++ { 13 | dp[i][j] = min(dp[i][j], max(dp[i][k-1], dp[k+1][j])+k) 14 | //choose k, and then the extra cost is at most dp[i][k-1] or dp[k+1][j], because we know k is higher or lower 15 | } 16 | 17 | } 18 | } 19 | return dp[1][n] 20 | } 21 | 22 | func max(a, b int) int { 23 | if a > b { 24 | return a 25 | } 26 | return b 27 | } 28 | 29 | func min(a, b int) int { 30 | if a < b { 31 | return a 32 | } 33 | return b 34 | } 35 | -------------------------------------------------------------------------------- /Problems/396. Rotate Function/396. Rotate Function.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func maxRotateFunction(A []int) int { 4 | if len(A) == 0 { 5 | return 0 6 | } 7 | // F[0] = 0A + 1B + 2C + 3D 8 | // F[1] = 1A + 2B + 3C + 0D 9 | // F[2] = 2A + 3B + 0C + 1D 10 | // F[3] = 3A + 0B + 1C + 2D 11 | // F[0] -> F[1] = F[0]+(A+B+C+D)-4D 12 | // F[1] -> F[2] = F[1]+(A+B+C+D)-4C 13 | sum := 0 14 | f0 := 0 15 | for i := range A { 16 | sum += A[i] 17 | f0 += i * A[i] 18 | } 19 | l := len(A) 20 | max := f0 21 | for i := 1; i < l; i++ { 22 | f0 += sum - l*A[l-i] 23 | if max < f0 { 24 | max = f0 25 | } 26 | } 27 | return max 28 | } 29 | -------------------------------------------------------------------------------- /Problems/40. Combination Sum II/40. Combination Sum II.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "sort" 4 | 5 | func combinationSum2(candidates []int, target int) [][]int { 6 | sort.Ints(candidates) 7 | res := make([][]int, 0) 8 | helper([]int{}, candidates, 0, 0, target, &res) 9 | return res 10 | } 11 | 12 | func helper(temp, cands []int, idx, sum, target int, res *[][]int) { 13 | if sum == target { 14 | cp := make([]int, len(temp)) 15 | copy(cp, temp) 16 | *res = append(*res, cp) 17 | return 18 | } else if sum > target { 19 | return 20 | } else { 21 | for i := idx; i < len(cands); i++ { 22 | if i > idx && cands[i-1] == cands[i] { 23 | continue 24 | } 25 | sum += cands[i] 26 | temp = append(temp, cands[i]) 27 | helper(temp, cands, i+1, sum, target, res) 28 | temp = temp[0 : len(temp)-1] 29 | sum -= cands[i] 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Problems/40. Permutations II/40. Permutations II.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sort" 6 | ) 7 | 8 | func permuteUnique(nums []int) [][]int { 9 | res := make([][]int, 0) 10 | used := make([]bool, len(nums)) 11 | sort.Ints(nums) 12 | backTrack(nums, &res, used, make([]int, 0)) 13 | return res 14 | } 15 | 16 | func backTrack(nums []int, res *[][]int, used []bool, temp []int) { 17 | if len(temp) == len(nums) { 18 | *res = append(*res, append(make([]int, 0), temp...)) 19 | return 20 | } else { 21 | for i := range nums { 22 | if used[i] { 23 | continue 24 | } 25 | if i > 0 && !used[i-1] && nums[i-1] == nums[i] { 26 | continue 27 | } 28 | used[i] = true 29 | temp = append(temp, nums[i]) 30 | backTrack(nums, res, used, temp) 31 | used[i] = false 32 | temp = temp[0 : len(temp)-1] 33 | } 34 | } 35 | } 36 | 37 | func main() { 38 | fmt.Println(permuteUnique([]int{2, 2, 1, 1})) 39 | } 40 | -------------------------------------------------------------------------------- /Problems/400. Nth Digit/400. Nth Digit.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "math" 5 | ) 6 | 7 | func findNthDigit(n int) int { 8 | //1-9 -> 9 * length-1 number 9 | //10-99 -> 90 * length-2 number 10 | //100-999 -> 900 * length-3 number 11 | //... 12 | if n <= 9 { 13 | return n 14 | } 15 | nine := 9 16 | curDigits := 0 17 | curNum := 0 18 | i := 1 19 | for ; i <= 10; i++ { 20 | curDigits += nine * i 21 | curNum = curNum*10 + 9 22 | nine *= 10 23 | if curDigits+(i+1)*nine > n { 24 | i++ 25 | break 26 | } 27 | } 28 | dif := (n - curDigits) / i //(difference in digits)/(number of digits) = difference in value 29 | digit := (n - curDigits) % i 30 | resNum := curNum + dif 31 | if digit != 0 { 32 | //if mod!=0, go to the next number 33 | resNum += 1 34 | } else { 35 | return resNum % 10 36 | } 37 | return resNum / int(math.Pow(float64(10), float64(i-digit))) % 10 38 | } 39 | -------------------------------------------------------------------------------- /Problems/446. Arithmetic Slices II - Subsequene/446. Arithmetic Subsequence II - Subsequence.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func numberOfArithmeticSlices(A []int) int { 4 | n := len(A) 5 | dp := make([]map[int]int, n) 6 | for i := range dp { 7 | dp[i] = map[int]int{} 8 | } 9 | res := 0 10 | for i := range A { 11 | for j := 0; j < i; j++ { 12 | dist := A[i] - A[j] 13 | res += dp[j][dist] 14 | dp[i][dist] += dp[j][dist] + 1 15 | } 16 | } 17 | return res 18 | } 19 | -------------------------------------------------------------------------------- /Problems/458. Poor Pigs/458. Poor Pigs.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "math" 4 | 5 | func poorPigs(buckets int, minutesToDie int, minutesToTest int) int { 6 | return int(math.Ceil(math.Log(float64(buckets)) / math.Log(float64(minutesToTest/minutesToDie+1)))) 7 | } 8 | 9 | //if there are two pigs, and we can test 3 times 10 | /* 11 | 1 2 3 4 12 | 5 6 7 8 13 | 9 10 11 12 14 | 13 14 15 16 15 | */ 16 | //for the first time: pig one try [1,2,3,4], pig two try [1,5,9,13] 17 | //for the second time: pig one try [5,6,7,8], pig two try [2,6,10,14] 18 | //for the third time:... 19 | 20 | //then based on the death, we can find the poisonous bucket (x,y) just like in a 2d cartesian coordinate 21 | //If there are three pigs, we can have a 4*4*4 three-dimension space for the buckets 22 | //the length of each axis is (test times+1) 23 | 24 | //(no. of pigs)^(test times+1) >= no. of buckets 25 | -------------------------------------------------------------------------------- /Problems/474. Ones and Zeroes/474. Ones and Zeroes.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func findMaxForm(strs []string, m int, n int) int { 4 | dp := make([][]int, m+1) 5 | for i := range dp { 6 | dp[i] = make([]int, n+1) 7 | } 8 | for _, v := range strs { 9 | z := 0 10 | o := 0 11 | for _, c := range v { 12 | if c == '0' { 13 | z++ 14 | } else { 15 | o++ 16 | } 17 | } 18 | for i := m; i >= z; i-- { 19 | for j := n; j >= o; j-- { 20 | dp[i][j] = max(dp[i][j], dp[i-z][j-o]+1) 21 | } 22 | } 23 | } 24 | return dp[m][n] 25 | } 26 | 27 | func max(a, b int) int { 28 | if a < b { 29 | return b 30 | } 31 | return a 32 | } 33 | -------------------------------------------------------------------------------- /Problems/483. Smallest Good Base/483. Smallest Good Base.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "math" 5 | "strconv" 6 | ) 7 | 8 | func smallestGoodBase(n string) string { 9 | num, _ := strconv.ParseInt(n, 10, 64) 10 | //the target is to get the longest 1111111.... 11 | //and the longest 1... length is 64, the shortest should be 2, since the range of n is [3,10^18] 12 | x := int64(1) 13 | for i := 62; i >= 1; i-- { 14 | if (x << uint(i)) < num { 15 | //make sure that the 2 base number is smaller than num 16 | //now e.g. 100001 29 | for l < r { 30 | mid := l + (r-l)/2 31 | sum := int64(1) 32 | cur := int64(1) 33 | for i := 1; i <= length; i++ { 34 | cur *= mid 35 | sum += cur 36 | } 37 | if sum == num { 38 | return mid 39 | } 40 | if sum > num { 41 | r = mid 42 | } else { 43 | l = mid + 1 44 | } 45 | } 46 | return -1 47 | } 48 | -------------------------------------------------------------------------------- /Problems/498. Diagonal Traversal/498. Diagonal Traversal.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "sort" 5 | ) 6 | 7 | func findDiagonalOrder(matrix [][]int) []int { 8 | m := len(matrix) 9 | if m == 0 { 10 | return []int{} 11 | } 12 | n := len(matrix[0]) 13 | toSort := make([][]int, m*n) 14 | idx := 0 15 | for i := 0; i < m; i++ { 16 | for j := 0; j < n; j++ { 17 | toSort[idx] = []int{i, j} 18 | idx++ 19 | } 20 | } 21 | sort.SliceStable(toSort, func(a, b int) bool { 22 | if toSort[a][0]+toSort[a][1] == toSort[b][0]+toSort[b][1] { 23 | if (toSort[a][0]+toSort[a][1])&1 == 1 { 24 | return a < b 25 | } else { 26 | return a > b 27 | } 28 | } else { 29 | return toSort[a][0]+toSort[a][1] < toSort[b][0]+toSort[b][1] 30 | } 31 | }) 32 | res := make([]int, n*m) 33 | for i := range toSort { 34 | res[i] = matrix[toSort[i][0]][toSort[i][1]] 35 | } 36 | return res 37 | } 38 | 39 | func findDiagonalOrder2(matrix [][]int) []int { 40 | m := len(matrix) 41 | if m == 0 { 42 | return []int{} 43 | } 44 | n := len(matrix[0]) 45 | visited := make([][]bool, m) 46 | for i := range visited { 47 | visited[i] = make([]bool, n) 48 | } 49 | res := make([]int, n*m) 50 | cnt := 0 51 | queue := make([][]int, 1) 52 | queue[0] = []int{0, 0} 53 | level := 0 54 | for len(queue) > 0 { 55 | level++ 56 | size := len(queue) 57 | for i := 0; i < size; i++ { 58 | cur := queue[i] 59 | x := cur[0] 60 | y := cur[1] 61 | if level%2 == 1 { 62 | res[cnt+i] = matrix[x][y] 63 | } else { 64 | res[cnt+size-1-i] = matrix[x][y] 65 | } 66 | if x+1 < m && !visited[x+1][y] { 67 | visited[x+1][y] = true 68 | queue = append(queue, []int{x + 1, y}) 69 | } 70 | if y+1 < n && !visited[x][y+1] { 71 | visited[x][y+1] = true 72 | queue = append(queue, []int{x, y + 1}) 73 | } 74 | } 75 | queue = queue[size:] 76 | cnt += size 77 | } 78 | return res 79 | } 80 | -------------------------------------------------------------------------------- /Problems/514. Freedom Trail/514. Freedom Trail.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "math" 5 | ) 6 | 7 | func findRotateSteps(ring string, key string) int { 8 | mp := map[byte][]int{} 9 | for i := range ring { 10 | if _, ok := mp[ring[i]]; !ok { 11 | mp[ring[i]] = []int{i} 12 | } else { 13 | mp[ring[i]] = append(mp[ring[i]], i) 14 | } 15 | } 16 | m := len(ring) 17 | n := len(key) 18 | dp := make([][]int, n) 19 | for i := range dp { 20 | dp[i] = make([]int, m) 21 | for j := range dp[i] { 22 | dp[i][j] = math.MaxInt32 / 2 23 | } 24 | } 25 | for i := range ring { 26 | if ring[i] == key[0] { 27 | dp[0][i] = getDist(0, i, m) 28 | dp[0][i] += 1 29 | } 30 | } 31 | for i := 1; i < n; i++ { 32 | cur := key[i] 33 | for _, curIdx := range mp[cur] { 34 | for _, prevIdx := range mp[key[i-1]] { 35 | dp[i][curIdx] = min(dp[i][curIdx], dp[i-1][prevIdx]+getDist(curIdx, prevIdx, m)) 36 | } 37 | dp[i][curIdx] += 1 38 | } 39 | } 40 | res := math.MaxInt32 41 | for i := range dp[n-1] { 42 | res = min(res, dp[n-1][i]) 43 | } 44 | return res 45 | } 46 | 47 | func getDist(a, b, n int) int { 48 | abs := 0 49 | rev := 0 50 | if a < b { 51 | abs = b - a 52 | rev = a + n - b 53 | } else { 54 | rev = b + n - a 55 | abs = a - b 56 | } 57 | return min(rev, abs) 58 | } 59 | 60 | func min(a, b int) int { 61 | if a < b { 62 | return a 63 | } 64 | return b 65 | } 66 | -------------------------------------------------------------------------------- /Problems/517. Super Washing Machines/517. Super Washing Machines.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func findMinMoves(machines []int) int { 4 | //since each machine can only transfer one dress at each step 5 | //the strategy is to find for each machine, the sum of dresses that passes left/right through this machine 6 | //among all the machine, the highest passes through number is also the steps to take 7 | sum := 0 8 | for i := range machines { 9 | sum += machines[i] 10 | } 11 | if sum%len(machines) != 0 { 12 | return -1 13 | } 14 | avg := sum / len(machines) 15 | leftSum := 0 16 | leftTarget := 0 17 | rightTarget := sum + avg 18 | res := 0 19 | for i := range machines { 20 | leftSum += machines[i] //prefix sum, i included 21 | rightSum := sum - leftSum + machines[i] //suffix sum, i included 22 | leftTarget += avg //prefix target, i included 23 | rightTarget -= avg //suffix target, i included 24 | toRight, toLeft := 0, 0 25 | if leftSum > leftTarget { 26 | toRight = leftSum - leftTarget 27 | } 28 | if rightSum > rightTarget { 29 | toLeft = rightSum - rightTarget 30 | } 31 | res = max(res, toLeft+toRight) 32 | } 33 | return res 34 | } 35 | 36 | func max(a, b int) int { 37 | if a > b { 38 | return a 39 | } 40 | return b 41 | } 42 | -------------------------------------------------------------------------------- /Problems/518. Coin Change 2/518. Coin Change 2.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func change(amount int, coins []int) int { 4 | dp := make([][]int, len(coins)+1) 5 | for i := range dp { 6 | dp[i] = make([]int, amount+1) 7 | } 8 | dp[0][0] = 1 9 | for i := 1; i <= len(coins); i++ { 10 | dp[i][0] = 1 11 | for j := 1; j <= amount; j++ { 12 | dp[i][j] = dp[i-1][j] 13 | if j-coins[i-1] >= 0 { 14 | dp[i][j] += dp[i][j-coins[i-1]] 15 | } 16 | } 17 | } 18 | return dp[len(coins)][amount] 19 | } 20 | -------------------------------------------------------------------------------- /Problems/523. Continuous Subarray Sum/523. Continuous Subarray Sum.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func checkSubarraySum(nums []int, k int) bool { 4 | mod := make(map[int]int) 5 | sum := 0 6 | mod[sum] = -1 7 | for i := range nums { 8 | sum += nums[i] 9 | if k != 0 { 10 | sum %= k 11 | } 12 | if _, ok := mod[sum]; ok { 13 | if i-mod[sum] > 1 { 14 | return true 15 | } 16 | } else { 17 | mod[sum] = i 18 | } 19 | } 20 | return false 21 | } 22 | -------------------------------------------------------------------------------- /Problems/546. Remove Boxes/546. Remove Boxes.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func removeBoxes(boxes []int) int { 4 | m := len(boxes) 5 | if m == 0 { 6 | return 0 7 | } 8 | dp := make([][][]int, m) 9 | for i := range dp { 10 | dp[i] = make([][]int, m) 11 | for j := range dp[i] { 12 | dp[i][j] = make([]int, m) 13 | } 14 | } 15 | for i := 0; i < m; i++ { 16 | for j := 0; j <= i; j++ { 17 | dp[i][i][j] = (j + 1) * (j + 1) 18 | } 19 | } 20 | for j := 1; j < m; j++ { 21 | for i := j - 1; i >= 0; i-- { 22 | for k := 0; k <= i; k++ { 23 | res := (k+1)*(k+1) + dp[i+1][j][0] 24 | for m := i + 1; m <= j; m++ { 25 | if boxes[m] == boxes[i] { 26 | res = max(res, dp[i+1][m-1][0]+dp[m][j][k+1]) 27 | } 28 | } 29 | dp[i][j][k] = res 30 | } 31 | } 32 | } 33 | return dp[0][m-1][0] 34 | } 35 | 36 | func max(a, b int) int { 37 | if a > b { 38 | return a 39 | } 40 | return b 41 | } 42 | -------------------------------------------------------------------------------- /Problems/567. Permutation in String/567. Permutation in String.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func checkInclusion(s1 string, s2 string) bool { 4 | if len(s1) > len(s2) { 5 | return false 6 | } 7 | ht := make(map[byte]int) 8 | cnt := len(s1) 9 | for i := range s1 { 10 | ht[s1[i]]++ 11 | } 12 | l := 0 13 | r := 0 14 | for r < len(s1)-1 { 15 | ht[s2[r]]-- 16 | if ht[s2[r]] >= 0 { 17 | cnt-- 18 | } 19 | r++ 20 | } 21 | for r < len(s2) { 22 | ht[s2[r]]-- 23 | if ht[s2[r]] >= 0 { 24 | cnt-- 25 | } 26 | r++ 27 | if cnt == 0 { 28 | return true 29 | } 30 | ht[s2[l]]++ 31 | if ht[s2[l]] > 0 { 32 | cnt++ 33 | } 34 | l++ 35 | } 36 | return false 37 | } 38 | -------------------------------------------------------------------------------- /Problems/576. Out of Boundary Paths/576. Out of Boundary Paths.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func findPaths(m int, n int, N int, i int, j int) int { 4 | mod := int(1e9 + 7) 5 | dp := make([][][]int, N+1) 6 | for i := range dp { 7 | dp[i] = make([][]int, m) 8 | for j := range dp[i] { 9 | dp[i][j] = make([]int, n) 10 | } 11 | } 12 | shift := []int{0, 1, 0, -1, 0} 13 | dp[0][i][j] = 0 14 | for i := 1; i <= N; i++ { 15 | for x := 0; x < m; x++ { 16 | for y := 0; y < n; y++ { 17 | for l := 0; l < 4; l++ { 18 | nx := x + shift[l] 19 | ny := y + shift[l+1] 20 | if nx < 0 || ny < 0 || nx >= m || ny >= n { 21 | dp[i][x][y]++ 22 | } else { 23 | dp[i][x][y] += dp[i-1][nx][ny] 24 | dp[i][x][y] %= mod 25 | } 26 | } 27 | } 28 | } 29 | } 30 | return dp[N][i][j] % mod 31 | } 32 | -------------------------------------------------------------------------------- /Problems/593. Valid Square/593. Valid Square.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func validSquare(p1 []int, p2 []int, p3 []int, p4 []int) bool { 4 | d12 := distSq(p1, p2) 5 | d13 := distSq(p1, p3) 6 | d14 := distSq(p1, p4) 7 | if d12 == 0 || d13 == 0 || d14 == 0 { 8 | return false 9 | } 10 | if d12 == d13 && d12*2 == d14 && p4[0] == p3[0]-p1[0]+p2[0] && p4[1] == p3[1]-p1[1]+p2[1] { 11 | return true 12 | } else if d12 == d14 && d12*2 == d13 && p3[0] == p2[0]-p1[0]+p4[0] && p3[1] == p2[1]-p1[1]+p4[1] { 13 | return true 14 | } else if d13 == d14 && d13*2 == d12 && p2[0] == p3[0]-p1[0]+p4[0] && p2[1] == p3[1]-p1[1]+p4[1] { 15 | return true 16 | } else { 17 | return false 18 | } 19 | } 20 | 21 | func distSq(p1, p2 []int) int { 22 | return (p1[0]-p2[0])*(p1[0]-p2[0]) + (p1[1]-p2[1])*(p1[1]-p2[1]) 23 | } 24 | -------------------------------------------------------------------------------- /Problems/60. Permutation Sequence/60. Permutation Sequence.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "strconv" 5 | ) 6 | 7 | func getPermutation(n int, k int) string { 8 | factorial := make([]int, n) 9 | product := 1 10 | number := make([]int, n) 11 | for i := range number { 12 | factorial[i] = product 13 | product *= i + 1 14 | number[i] = i + 1 15 | } 16 | rs := 0 17 | k-- 18 | for i := n - 1; i >= 0; i-- { 19 | num := k / factorial[i] 20 | rs = rs*10 + number[num] 21 | k %= factorial[i] 22 | number = append(number[0:num], number[num+1:]...) 23 | } 24 | return strconv.Itoa(rs) 25 | } 26 | -------------------------------------------------------------------------------- /Problems/634. Find the Derangement of An Array/634. Find the Derangement of An Array.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func findDerangement(n int) int { 4 | dp := make([]int, n+1) 5 | if n < 2 { 6 | return 0 7 | } 8 | dp[0] = 0 9 | dp[1] = 0 10 | dp[2] = 1 11 | mod := int(1e9) + 7 12 | for i := 3; i <= n; i++ { 13 | // for the ith number, there are i-1 number already, the ith number has i-1 choice of placement 14 | // for where to place the ith number, there are two situations 15 | // 1. ith number exchange with jth number, jth number go to ith index, ith number go to jth index 16 | // now the other i-2 numbers has dp[i-2] derangement 17 | // 2. ith number go to jth index, but jth number did not go to ith index, 18 | // so now there are i-1 numbers, and for each number there is an invalid position (for the jth number, the ith index is invalid) 19 | // so now there will be dp[i-1] derangement 20 | dp[i] = (i - 1) * (dp[i-1] + dp[i-2]) % mod 21 | } 22 | return dp[n] 23 | } 24 | -------------------------------------------------------------------------------- /Problems/664. Strange Printer/664. Strange Printer.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func strangePrinter(s string) int { 4 | n := len(s) 5 | if n == 0 { 6 | return 0 7 | } 8 | dp := make([][]int, n) 9 | for i := range dp { 10 | dp[i] = make([]int, n) 11 | } 12 | for j := 0; j < n; j++ { 13 | for i := j; i >= 0; i-- { 14 | if i == j { 15 | dp[i][j] = 1 16 | } else if j == i+1 { 17 | if s[i] == s[j] { 18 | dp[i][j] = 1 19 | } else { 20 | dp[i][j] = 2 21 | } 22 | } else { 23 | dp[i][j] = dp[i][i] + dp[i+1][j] 24 | for k := i; k < j; k++ { 25 | dp[i][j] = min(dp[i][k]+dp[k+1][j], dp[i][j]) 26 | } 27 | if s[i] == s[j] { 28 | dp[i][j] -= 1 29 | } 30 | } 31 | } 32 | } 33 | return dp[0][n-1] 34 | } 35 | 36 | func min(a, b int) int { 37 | if a < b { 38 | return a 39 | } 40 | return b 41 | } 42 | -------------------------------------------------------------------------------- /Problems/67. Add Binary/67. Add BInary.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func addBinary(a string, b string) string { 4 | i := len(a) - 1 5 | j := len(b) - 1 6 | res := make([]byte, 0) 7 | carry := 0 8 | for i >= 0 || j >= 0 || carry != 0 { 9 | if i >= 0 && a[i] == '1' { 10 | carry += 1 11 | } 12 | if j >= 0 && b[j] == '1' { 13 | carry += 1 14 | } 15 | res = append(res, byte(carry&1)+'0') 16 | carry >>= 1 17 | i-- 18 | j-- 19 | } 20 | reverse(res) 21 | return string(res) 22 | } 23 | 24 | func reverse(arr []byte) []byte { 25 | i := 0 26 | j := len(arr) - 1 27 | for i < j { 28 | arr[i], arr[j] = arr[j], arr[i] 29 | i++ 30 | j-- 31 | } 32 | return arr 33 | } 34 | -------------------------------------------------------------------------------- /Problems/670. Maximum Swap/670. Maximum Swap.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "strconv" 4 | 5 | /* 6 | func maximumSwap(num int) int { 7 | str := []byte(strconv.Itoa(num)) 8 | //check from the last digit, update the current max digit 9 | //if the current digit is smaller than current max, store them as temporary swap position 10 | curMax := str[len(str)-1] 11 | maxPos := len(str) - 1 12 | swapX := -1 13 | swapY := -1 14 | for i := len(str) - 1; i >= 0; i-- { 15 | if str[i] > curMax { 16 | curMax = str[i] 17 | maxPos = i 18 | } else if str[i] < curMax { 19 | swapX = i 20 | swapY = maxPos 21 | } 22 | } 23 | if swapX == -1 && swapY == -1 { 24 | return num 25 | } 26 | str[swapX], str[swapY] = str[swapY], str[swapX] 27 | res, _ := strconv.Atoi(string(str)) 28 | return res 29 | } 30 | */ 31 | 32 | func maximumSwap(num int) int { 33 | table := make(map[byte]int) 34 | chars := []byte(strconv.Itoa(num)) 35 | for i, c := range chars { 36 | table[c] = i 37 | } 38 | for i := 0; i < len(chars); i++ { 39 | for c := byte('9'); c > chars[i]; c-- { 40 | if table[c] > i { 41 | chars[table[c]], chars[i] = chars[i], chars[table[c]] 42 | res, _ := strconv.Atoi(string(chars)) 43 | return res 44 | } 45 | } 46 | } 47 | return num 48 | } 49 | -------------------------------------------------------------------------------- /Problems/678. Valid Parenthesis String/678. Valid Parenthesis String.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func checkValidString(s string) bool { 4 | buffer := 0 5 | prev := -1 6 | left := 0 7 | used := make([]bool, len(s)) 8 | for i := range s { 9 | if s[i] == '(' { 10 | left++ 11 | } else if s[i] == ')' { 12 | left-- 13 | } else { 14 | buffer++ 15 | prev = i 16 | } 17 | if left < 0 { 18 | if buffer > 0 { 19 | buffer-- 20 | used[prev] = true 21 | left++ 22 | } else { 23 | return false 24 | } 25 | } 26 | } 27 | //note, the final result of left can be greater or equal to zero 28 | right := 0 29 | buffer = 0 30 | for i := len(s) - 1; i >= 0; i-- { 31 | if s[i] == ')' { 32 | right++ 33 | } else if s[i] == '(' { 34 | right-- 35 | } else { 36 | if used[i] { 37 | right-- 38 | } else { 39 | buffer++ 40 | } 41 | } 42 | if right < 0 { 43 | if buffer > 0 { 44 | buffer-- 45 | right++ 46 | } else { 47 | return false 48 | } 49 | } 50 | } 51 | return right == 0 52 | } 53 | -------------------------------------------------------------------------------- /Problems/727. Minimum Window Subsequence/727. Minimum Window Subsequence.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "math" 4 | 5 | func minWindow(S string, T string) string { 6 | m := len(S) 7 | n := len(T) 8 | dp := make([][]int, m+1) 9 | for i := range dp { 10 | dp[i] = make([]int, n+1) 11 | } 12 | 13 | for j := range dp[0] { 14 | dp[0][j] = math.MaxInt32 / 2 15 | } 16 | for i := range dp { 17 | dp[i][0] = 0 18 | } 19 | for i := 1; i <= m; i++ { 20 | for j := 1; j <= n; j++ { 21 | if S[i-1] == T[j-1] { 22 | dp[i][j] = dp[i-1][j-1] + 1 23 | } else { 24 | dp[i][j] = dp[i-1][j] + 1 25 | } 26 | } 27 | } 28 | minLen := math.MaxInt32 / 2 29 | pos := -1 30 | // fmt.Println(dp) 31 | for i := 1; i <= m; i++ { 32 | if dp[i][n] < minLen { 33 | minLen = dp[i][n] 34 | pos = i 35 | } 36 | } 37 | if minLen >= math.MaxInt32/2 { 38 | return "" 39 | } 40 | return S[pos-minLen : pos] 41 | } 42 | -------------------------------------------------------------------------------- /Problems/744. Find Smallest Letter Greater Than Target/744. Find Smallest Letter Greater Than Target.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func nextGreatestLetter(letters []byte, target byte) byte { 4 | l := 0 5 | r := len(letters) - 1 6 | for l < r { 7 | mid := (l + r) / 2 8 | if letters[mid] <= target { 9 | l = mid + 1 10 | } else { 11 | r = mid 12 | } 13 | } 14 | if l == len(letters)-1 && letters[l] <= target { 15 | return letters[0] 16 | } 17 | return letters[l] 18 | } 19 | -------------------------------------------------------------------------------- /Problems/753. Cracking the Safe/753. Cracking the Safe.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "math" 5 | "strconv" 6 | ) 7 | 8 | func crackSafe(n int, k int) string { 9 | set := make(map[string]bool) 10 | s := "" 11 | for i := 0; i < n; i++ { 12 | s += strconv.Itoa(0) 13 | } 14 | set[s] = true 15 | target := int(math.Pow(float64(k), float64(n))) 16 | helper(&s, set, target, n, k) 17 | return s 18 | } 19 | 20 | func helper(s *string, set map[string]bool, target, n, k int) bool { 21 | if len(set) == target { 22 | return true 23 | } 24 | //get last n-1 digits in s 25 | cur := (*s)[len(*s)-n+1:] 26 | for i := 0; i < k; i++ { 27 | temp := cur + strconv.Itoa(i) 28 | if !set[temp] { 29 | set[temp] = true 30 | *s = *s + strconv.Itoa(i) 31 | if helper(s, set, target, n, k) { 32 | return true 33 | } 34 | delete(set, temp) 35 | *s = (*s)[0 : len(*s)-1] 36 | } 37 | } 38 | return false 39 | } 40 | -------------------------------------------------------------------------------- /Problems/754. Reach a Number/754. Reach a Number.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "math" 4 | 5 | func reachNumber(target int) int { 6 | //first we need to find the steps of total addition 1+2+3+...+n 7 | target = int(math.Abs(float64(target))) 8 | step := 0 9 | total := 0 10 | for total < target { 11 | step++ 12 | total += step 13 | } 14 | if total == target { 15 | return step 16 | } 17 | //if they are not equal, we need to reduce a number i and the total-=2*i 18 | //so the difference between target and total should be even 19 | //if they are not even, we just add steps to make the difference even 20 | dif := total - target 21 | for dif%2 != 0 { 22 | step++ 23 | total += step 24 | dif = total - target 25 | } 26 | return step 27 | } 28 | -------------------------------------------------------------------------------- /Problems/765. Couples Holding Hands/765. Couples Holding Hands.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | the key is to find all the cyclic permutations, e.g. 2341 is a cyclic group of 1234, and need 3 swap to restore 5 | for each 2i, 2i+1, if the person in these two position are not couple, and they come from couple u, v 6 | so the cyclic group involve couple u and v, which is just like add a connection between couple u and v 7 | */ 8 | var cnt = 0 9 | 10 | func minSwapsCouples(row []int) int { 11 | N := len(row) / 2 12 | cnt = N 13 | root := make([]int, cnt) 14 | for i := range root { 15 | root[i] = i 16 | } 17 | for i := 0; i < N; i++ { 18 | a := row[i*2] 19 | b := row[i*2+1] 20 | connect(root, a/2, b/2) 21 | } 22 | return N - cnt 23 | } 24 | 25 | func find(root []int, a int) int { 26 | if root[a] == a { 27 | return a 28 | } 29 | root[a] = find(root, root[a]) 30 | return root[a] 31 | } 32 | 33 | func connect(root []int, a, b int) { 34 | ra := find(root, a) 35 | rb := find(root, b) 36 | if ra != rb { 37 | root[ra] = rb 38 | cnt-- 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Problems/775. Global and Local Inversions/775. Global and Local Inversions.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "math" 4 | 5 | func isIdealPermutation(A []int) bool { 6 | //all local inversions are global inversions 7 | //so if there are more global inversions, then from 0...i, there must be max(A[0...i])>A[i+2], because they cannot be neighbors 8 | max := A[0] 9 | for i := 0; i < len(A)-2; i++ { 10 | max = int(math.Max(float64(A[i]), float64(max))) 11 | if max > A[i+2] { 12 | return false 13 | } 14 | } 15 | return true 16 | } 17 | -------------------------------------------------------------------------------- /Problems/780. Reaching Points/780. Reaching Points.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func reachingPoints(sx int, sy int, tx int, ty int) bool { 4 | //we can iterate backwards from tx and ty, the larger one in tx/ty must come from the addition of another 5 | //until one of them is equals to sx or sy, this is sure to happen 6 | for sx < tx && sy < ty { 7 | if tx > ty { 8 | tx -= ty 9 | } else { 10 | ty -= tx 11 | } 12 | } 13 | if tx == sx && sy <= ty && (ty-sy)%sx == 0 { 14 | //ty = sy+n*x 15 | return true 16 | } 17 | if ty == sy && sx <= tx && (tx-sx)%sy == 0 { 18 | //tx = sx+n*y 19 | return true 20 | } 21 | return false 22 | } 23 | -------------------------------------------------------------------------------- /Problems/789. Escape The Ghosts/789. Escape The Ghosts.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func escapeGhosts(ghosts [][]int, target []int) bool { 4 | //if the ghost want to catch you, the best way to go to the target and wait you 5 | //so as long as the distance between you and target is smaller than the distance between ghost and target, you are fine 6 | //is that possible that distance(src, target)= k-1; j-- { 22 | dp[k][i] = math.Max(dp[k-1][j]+float64(sums[i-1]-sums[j-1])/float64(i-j), dp[k][i]) 23 | } 24 | } 25 | } 26 | return dp[K][n] 27 | } 28 | -------------------------------------------------------------------------------- /Problems/828. Count Unique Characters of All Substrings of a Given String/828. Count Unique Character of All Substrings of a Given String.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func uniqueLetterString(s string) int { 4 | //what we need to do is to find the previous and next appearance of the character 5 | //then we know the longest substring it can be in, so that this character is unique 6 | //e.g. XAXXAXA the second A is unique in XA(XXAX)A 7 | n := len(s) 8 | occur := [26][2]int{} 9 | for i := range occur { 10 | occur[i] = [2]int{-1, -1} 11 | } 12 | sum := 0 13 | mod := int(1e9) + 7 14 | for i := range s { 15 | cur := s[i] - 'A' 16 | sum += (i - occur[cur][1]) * (occur[cur][1] - occur[cur][0]) 17 | sum %= mod 18 | occur[cur] = [2]int{occur[cur][1], i} 19 | } 20 | for i := range occur { 21 | sum += (n - occur[i][1]) * (occur[i][1] - occur[i][0]) 22 | sum %= mod 23 | } 24 | return sum 25 | } 26 | -------------------------------------------------------------------------------- /Problems/829. Consecutive Numbers Sum/829. Consecutive Numbers Sum.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func consecutiveNumbersSum(N int) int { 4 | //since its a consective array, starting from x, x+1, x+2 ... x+n-1 5 | //the sum is x*n+n*(n-1)/2 == N 6 | //x*n = N-n*(n-1)/2 7 | //iterate n from 1 to n(n-1)/2>N 8 | //if (N-n(n-1)/2)%n==0 then res++ 9 | res := 0 10 | for n := 1; n*(n-1)/2 < N; n++ { 11 | if (N-n*(n-1)/2)%n == 0 { 12 | res++ 13 | } 14 | } 15 | return res 16 | } 17 | -------------------------------------------------------------------------------- /Problems/836. Rectangle Overlap/836. Rectangle Overlap.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func isRectangleOverlap(rec1 []int, rec2 []int) bool { 4 | lowx := max(rec1[0], rec2[0]) 5 | lowy := max(rec1[1], rec2[1]) 6 | highx := min(rec1[2], rec2[2]) 7 | highy := min(rec1[3], rec2[3]) 8 | return (lowx < highx) && (lowy < highy) 9 | } 10 | 11 | func max(a, b int) int { 12 | if a > b { 13 | return a 14 | } else { 15 | return b 16 | } 17 | } 18 | 19 | func min(a, b int) int { 20 | if a > b { 21 | return b 22 | } else { 23 | return a 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Problems/837. New 21 Game/837. New 21 Game.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func new21Game(N int, K int, W int) float64 { 4 | //if N is smaller than K, possibility is 0 5 | //if K-1+W<=N, possibility is 1 6 | if N < K { 7 | return float64(0) 8 | } 9 | if K+W <= N || K == 0 { 10 | return float64(1) 11 | } 12 | //let dp[i] = possibility of getting i points 13 | //we can calculate dp[i] from previous step 14 | // dp[i] = dp[i-1]*P(1) + dp[i-2]*P(2) ... + dp[i-W]*P(W) 15 | // and P(1) P(2) ... is 1/W 16 | // so we keep a sliding window which is the sum of last w possibilities 17 | dp := make([]float64, N+1) 18 | dp[0] = 1 19 | wsum := float64(1) 20 | res := float64(0) 21 | for i := 1; i <= N; i++ { 22 | dp[i] = wsum / float64(W) 23 | if i < K { 24 | wsum += dp[i] 25 | } else { 26 | //once i is greater than k, we cannot draw new numbers 27 | res += dp[i] 28 | } 29 | if i-W >= 0 { 30 | wsum -= dp[i-W] 31 | } 32 | } 33 | return res 34 | } 35 | -------------------------------------------------------------------------------- /Problems/847. Shortest Path Visiting All Nodes/847. Shortest Path Visiting All Nodes.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func shortestPathLength(graph [][]int) int { 4 | //use current node and current visited status as the BFS state 5 | target := 0 6 | n := len(graph) 7 | queue := make([][]int, 0, n*n) 8 | visited := make(map[string]bool) 9 | for i := 0; i < n; i++ { 10 | target |= 1 << uint(i) 11 | status := 1 << uint(i) 12 | queue = append(queue, []int{status, i}) 13 | strStatus := string(status) + " " + string(i) 14 | visited[strStatus] = true 15 | } 16 | step := 0 17 | for len(queue) > 0 { 18 | size := len(queue) 19 | for i := 0; i < size; i++ { 20 | cur := queue[i] 21 | if cur[0] == target { 22 | return step 23 | } 24 | for _, next := range graph[cur[1]] { 25 | nextStatus := string(cur[0]|(1<= 0; i-- { 30 | for j := 0; j < len(A); j++ { 31 | res += int(math.Pow(2, float64(len(A[0])-1-i))) * A[j][i] 32 | } 33 | } 34 | return res 35 | } 36 | 37 | func toggle(a [][]int, col bool, pos int) { 38 | if col { 39 | for i := 0; i < len(a); i++ { 40 | a[i][pos] ^= 1 41 | } 42 | } else { 43 | for i := 0; i < len(a[0]); i++ { 44 | a[pos][i] ^= 1 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Problems/864. Shortest Path to Get All Keys/864. Shortest Path to Get All Keys.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "strconv" 5 | "unicode" 6 | ) 7 | 8 | func shortestPathAllKeys(grid []string) int { 9 | move := [5]int{0, 1, 0, -1, 0} 10 | sx := -1 11 | sy := -1 12 | m := len(grid) 13 | n := len(grid[0]) 14 | numKeys := 0 15 | for i := 0; i < m; i++ { 16 | for j := 0; j < n; j++ { 17 | if grid[i][j] == '@' { 18 | sx = i 19 | sy = j 20 | } else if unicode.IsLower(rune(grid[i][j])) { 21 | numKeys++ 22 | } 23 | } 24 | } 25 | queue := make([][]int, 0, m*n) 26 | visited := make(map[string]bool) 27 | cur := strconv.Itoa(0) + " " + strconv.Itoa(sx) + "/" + strconv.Itoa(sy) 28 | print(cur) 29 | visited[cur] = true 30 | queue = append(queue, []int{0, sx, sy}) 31 | step := 0 32 | for len(queue) > 0 { 33 | size := len(queue) 34 | for i := 0; i < size; i++ { 35 | temp := queue[i] 36 | if temp[0] == (1<= 0 && nx < m && ny >= 0 && ny < n && grid[nx][ny] != '#' { 44 | if unicode.IsLower(rune(grid[nx][ny])) { 45 | keys |= 1 << uint(grid[nx][ny]-'a') 46 | } 47 | if unicode.IsUpper(rune(grid[nx][ny])) { 48 | if (keys>>uint(grid[nx][ny]-'A'))&1 == 0 { 49 | continue 50 | } 51 | } 52 | status := strconv.Itoa(keys) + " " + strconv.Itoa(nx) + "/" + strconv.Itoa(ny) 53 | if !visited[status] { 54 | visited[status] = true 55 | queue = append(queue, []int{keys, nx, ny}) 56 | } 57 | } 58 | } 59 | } 60 | queue = queue[size:] 61 | step++ 62 | } 63 | return -1 64 | } 65 | -------------------------------------------------------------------------------- /Problems/869. Reordered Power of 2/869. Reordered Power of 2.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "math" 4 | 5 | // 6 | //func reorderedPowerOf2(N int) bool { 7 | // n := strconv.Itoa(N) 8 | // ct := []byte("0000000000") 9 | // for i := range n { 10 | // ct[n[i]-'0']++ 11 | // } 12 | // set:=make(map[int]bool, 0) 13 | // l := len(n) 14 | // upp := 0 15 | // for i := 0; i < l; i++ { 16 | // upp *= 10 17 | // upp += 9 18 | // } 19 | // low := int(math.Pow(10, float64(l-1))) 20 | // pow := 1 21 | // for pow < upp { 22 | // if pow >= low { 23 | // set[pow] = true 24 | // } 25 | // pow<<=1 26 | // } 27 | // for k:=range set{ 28 | // tempct:=[]byte("0000000000") 29 | // s:=strconv.Itoa(k) 30 | // for i:=range s{ 31 | // tempct[s[i]-'0']++ 32 | // } 33 | // if string(ct)==string(tempct){ 34 | // return true 35 | // } 36 | // } 37 | // return false 38 | //} 39 | // 40 | 41 | func reorderedPowerOf2(N int) bool { 42 | res := count(N) 43 | cur := 1 44 | for cur <= math.MaxInt32 { 45 | if count(cur) == res { 46 | return true 47 | } else { 48 | cur <<= 1 49 | } 50 | } 51 | return false 52 | } 53 | 54 | func count(N int) int { 55 | //count the numbers of 0123456789 56 | res := 0 57 | for N > 0 { 58 | res += int(math.Pow(10, float64(N%10))) 59 | N /= 10 60 | } 61 | return res 62 | } 63 | -------------------------------------------------------------------------------- /Problems/887. Super Egg Drop/887. Super Egg Drop.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "math" 4 | 5 | func superEggDropTLE(K int, N int) int { 6 | // FIXME this O(kn^2) solution cause TLE 7 | // dp[k][n] is the steps to find F, if we have k eggs and n floors 8 | // if we drop at ith floor 9 | // if it broke, dp[k][n] = 1 + dp[k-1][i-1], because we know the F is lower and we lost an egg 10 | // if it did not break, dp[k][n] = 1 + dp[k][n-k], because we know F>=i+1, and we still have k eggs 11 | // so dp[k][n] = min(1+max(dp[k][i+1], dp[k-1][i-1]) 12 | dp := make([][]int, 1+K) 13 | for i := range dp { 14 | dp[i] = make([]int, N+1) 15 | } 16 | // dp[1][x] = x, we need to check from the bottom for every floor 17 | // dp[i][0] = 0, no need to check 18 | for j := 1; j <= N; j++ { 19 | dp[1][j] = j 20 | } 21 | for i := 2; i <= K; i++ { 22 | for j := 1; j <= N; j++ { 23 | dp[i][j] = math.MaxInt32 24 | for k := 1; k <= j; k++ { 25 | dp[i][j] = min(dp[i][j], 1+max(dp[i-1][k-1], dp[i][j-k])) 26 | } 27 | } 28 | } 29 | return dp[K][N] 30 | } 31 | 32 | func max(a, b int) int { 33 | if a > b { 34 | return a 35 | } 36 | return b 37 | } 38 | 39 | func min(a, b int) int { 40 | if a < b { 41 | return a 42 | } 43 | return b 44 | } 45 | 46 | /* 47 | To improve the time efficiency we focus on k 48 | since we are looking at max(dp[i-1][k-1], dp[i][j-k]) 49 | dp[i-1][k-1] is increasing with k increasing 50 | dp[i][j-k] is decreasing with k increasing 51 | so dp[i][j] is minimum when the two function meet 52 | 53 | since in each iteration j is increasing, so in each iteration the k we need increasing 54 | we can keep the k in last iteration and start from there in the next round 55 | */ 56 | 57 | func superEggDrop(K int, n int) int { 58 | dp := make([][]int, K+1) 59 | for i := range dp { 60 | dp[i] = make([]int, n+1) 61 | } 62 | for i := 1; i <= n; i++ { 63 | dp[1][i] = i 64 | } 65 | for i := 2; i <= K; i++ { 66 | k := 1 67 | for j := 1; j <= n; j++ { 68 | for k <= j && dp[i-1][k-1] < dp[i][j-k] { 69 | k++ 70 | } 71 | dp[i][j] = 1 + dp[i-1][k-1] 72 | } 73 | } 74 | return dp[K][n] 75 | } 76 | -------------------------------------------------------------------------------- /Problems/89. Gray Code/89. Gray Code.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func grayCode(n int) []int { 4 | res := make([]int, 0, 0) 5 | res = append(res, 0) 6 | for i := 0; i < n; i++ { 7 | size := len(res) 8 | for j := size - 1; j >= 0; j-- { 9 | res = append(res, res[j]|1< 2,3,4,5,1 -> 3,4,5,1,2 8 | //bubble sort is to compare and swap two neighbor number like a sliding window, and sliding n times 9 | //when K>=2 10 | //we can achieve the step swap, e.g. 11 | //5 2 1 3 4 -> 2 1 3 4 5 -> 2 3 4 5 1 -> 2 4 5 1 3 -> 2 5 1 3 4 (rotate the [1:] part) 12 | //so when K>=2 we just sort the string 13 | // if K==1, we find the smallest in all rotated strings 14 | ss := []byte(S) 15 | if K >= 2 { 16 | sort.Slice(ss, func(a, b int) bool { 17 | return ss[a] < ss[b] 18 | }) 19 | return string(ss) 20 | } else { 21 | res := make([]string, len(ss)) 22 | for i := 0; i < len(ss); i++ { 23 | res[i] = S[i:] + S[0:i] 24 | } 25 | sort.Strings(res) 26 | return res[0] 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Problems/902. Numbers At Most N Given Digit Set/902. Numbers At Most N Given Digit Set.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "math" 5 | "strconv" 6 | ) 7 | 8 | func atMostNGivenDigitSet(D []string, N int) int { 9 | s := strconv.Itoa(N) 10 | n := len(s) 11 | res := 0 12 | for i := 1; i < n; i++ { 13 | res += int(math.Pow(float64(len(D)), float64(i))) 14 | } 15 | //first calculate the total number that with fewer digits than N 16 | //len(D)^(1 ~ len(N)-1) 17 | ht := make(map[string]bool, 0) 18 | for _, v := range D { 19 | ht[v] = true 20 | } 21 | i := 0 22 | for ; i < n; i++ { 23 | pos := 0 24 | for j := range D { 25 | if D[j][0] < s[i] { 26 | pos++ 27 | } 28 | } 29 | res += pos * int(math.Pow(float64(len(D)), float64(n-i-1))) 30 | if !ht[s[i:i+1]] { 31 | break 32 | } 33 | } 34 | if i == n { 35 | return res + 1 36 | } else { 37 | return res 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Problems/903. Valid Permutations for DI Sequence/903. Valid Permutations for DI Sequence.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func numPermsDISequence(S string) int { 4 | n := len(S) 5 | mod := int(1e9) + 7 6 | dp := make([][]int, n+1) 7 | for i := range dp { 8 | dp[i] = make([]int, n+1) 9 | } 10 | dp[0][0] = 1 11 | for i := 1; i <= n; i++ { 12 | for j := 0; j <= i; j++ { 13 | if S[i-1] == 'I' { 14 | for k := 0; k < j; k++ { 15 | dp[i][j] += dp[i-1][k] 16 | dp[i][j] %= mod 17 | } 18 | } else { 19 | for k := j; k <= i-1; k++ { 20 | dp[i][j] += dp[i-1][k] 21 | dp[i][j] %= mod 22 | } 23 | } 24 | } 25 | } 26 | res := 0 27 | for i := range dp[n] { 28 | res += dp[n][i] 29 | res %= mod 30 | } 31 | return res 32 | } 33 | -------------------------------------------------------------------------------- /Problems/906. Super Palindromes/906. Super Palindromes.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "strconv" 5 | ) 6 | 7 | func superpalindromesInRange(L string, R string) int { 8 | cands := []int64{1, 2, 3, 4, 5, 6, 7, 8, 9} 9 | for i := 1; i < 10000; i++ { 10 | cur := strconv.Itoa(i) 11 | rev := reverse(cur) 12 | temp, _ := strconv.ParseInt(cur+rev, 10, 64) 13 | cands = append(cands, temp) 14 | for j := 0; j < 10; j++ { 15 | toAdd, _ := strconv.ParseInt(cur+strconv.Itoa(j)+rev, 10, 64) 16 | cands = append(cands, toAdd) 17 | } 18 | } 19 | res := 0 20 | l, _ := strconv.ParseInt(L, 10, 64) 21 | r, _ := strconv.ParseInt(R, 10, 64) 22 | for _, v := range cands { 23 | sq := v * v 24 | if sq >= l && sq <= r && isP(strconv.FormatInt(sq, 10)) { 25 | res++ 26 | } 27 | } 28 | return res 29 | } 30 | 31 | func isP(s string) bool { 32 | chars := []byte(s) 33 | for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { 34 | if chars[i] != chars[j] { 35 | return false 36 | } 37 | } 38 | return true 39 | } 40 | 41 | func reverse(s string) string { 42 | chars := []byte(s) 43 | for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { 44 | chars[i], chars[j] = chars[j], chars[i] 45 | } 46 | return string(chars) 47 | } 48 | -------------------------------------------------------------------------------- /Problems/910. Smallest Range II/910. Smallest Range II.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "sort" 4 | 5 | func smallestRangeII(A []int, K int) int { 6 | //sort first and then add 0 or 2K to each position 7 | sort.Ints(A) 8 | min := A[0] 9 | max := A[len(A)-1] 10 | dif := max - min 11 | for i := 0; i < len(A)-1; i++ { 12 | if A[0]+2*K > A[i+1] { 13 | min = A[i+1] 14 | } else { 15 | min = A[0] + 2*K 16 | } 17 | if A[i]+2*K > max { 18 | max = A[i] + 2*K 19 | } 20 | if max-min < dif { 21 | dif = max - min 22 | } 23 | } 24 | return dif 25 | } 26 | -------------------------------------------------------------------------------- /Problems/913. Cat and Mouse/913. Cat and Mouse.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func catMouseGame(graph [][]int) int { 4 | //bfs from the final status (e.g. cat/mouse win, draw) 5 | //for each known status, get all its parent status, 6 | //for each parent status, check if all the child status is the same 7 | //if all child status are same, then the parent status is fixed 8 | n := len(graph) 9 | queue := make([][]int, 0, 10) 10 | states := [50][50][3]int{} 11 | for i := 0; i < n; i++ { 12 | for j := 1; j <= 2; j++ { 13 | states[0][i][j] = 1 14 | queue = append(queue, []int{0, i, j}) 15 | 16 | if i != 0 { 17 | states[i][i][j] = 2 18 | queue = append(queue, []int{i, i, j}) 19 | } 20 | } 21 | } 22 | 23 | for len(queue) > 0 { 24 | cur := queue[0] 25 | m := cur[0] 26 | c := cur[1] 27 | t := cur[2] 28 | res := states[m][c][t] 29 | queue = queue[1:] 30 | for _, p := range getParents(graph, m, c, t) { 31 | if states[p[0]][p[1]][p[2]] != 0 { 32 | continue 33 | } 34 | if p[2] == res { 35 | //the parent move is the final winner's move 36 | //then the final winner can win 37 | states[p[0]][p[1]][p[2]] = res 38 | queue = append(queue, p) 39 | } else if allKidsWin(graph, p[0], p[1], p[2], &states) { 40 | if p[2] == 1 { 41 | states[p[0]][p[1]][p[2]] = 2 42 | } else { 43 | states[p[0]][p[1]][p[2]] = 1 44 | } 45 | queue = append(queue, p) 46 | } 47 | } 48 | } 49 | return states[1][2][1] 50 | } 51 | 52 | func getParents(graph [][]int, m int, c int, turn int) [][]int { 53 | res := make([][]int, 0, 0) 54 | if turn == 1 { 55 | //if current is mouse move 56 | //then we check cat move for the parents 57 | for _, next := range graph[c] { 58 | if next != 0 { 59 | res = append(res, []int{m, next, 2}) 60 | } 61 | } 62 | } else { 63 | for _, next := range graph[m] { 64 | res = append(res, []int{next, c, 1}) 65 | } 66 | } 67 | return res 68 | } 69 | 70 | func allKidsWin(graph [][]int, m int, c int, t int, states *[50][50][3]int) bool { 71 | //check if all the next step (opponent step leads to win) 72 | //if all next steps lead to opponent's win, the current state is sure to lose 73 | if t == 1 { 74 | //check mouse move 75 | for _, next := range graph[m] { 76 | if (*states)[next][c][2] != 2 { 77 | return false 78 | } 79 | } 80 | } else { 81 | for _, next := range graph[c] { 82 | if next == 0 { 83 | continue 84 | } 85 | if (*states)[m][next][1] != 1 { 86 | return false 87 | } 88 | } 89 | } 90 | return true 91 | } 92 | -------------------------------------------------------------------------------- /Problems/914. X of a Kind in a Deck of Cards/914. X of a Kind in a Deck of Cards.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | //func hasGroupsSizeX(deck []int) bool { 4 | // //note! must get the two different minimum count!! 5 | // cnt := make(map[int]int, 0) 6 | // for _, v := range deck { 7 | // cnt[v]++ 8 | // } 9 | // min1 := len(deck) 10 | // min2 := len(deck) 11 | // for _, v := range cnt { 12 | // if v < min1 { 13 | // min2 = min1 14 | // min1 = v 15 | // } else if v != min1 && v < min2 { 16 | // min2 = v 17 | // } 18 | // } 19 | // if min1 == len(deck) || min2 == len(deck) { 20 | // return len(deck) >= 2 21 | // } 22 | // g := gcd(min1, min2) 23 | // if g < 2 { 24 | // return false 25 | // } 26 | // for _, v := range cnt { 27 | // if v%g != 0 { 28 | // return false 29 | // } 30 | // } 31 | // return true 32 | //} 33 | 34 | func hasGroupsSizeX(deck []int) bool { 35 | //to partition the array to group of same number with group size larger than 2 36 | //equals to that the gcd of the number of appearance of each number in deck is larger than 2 37 | cnt := make(map[int]int, 0) 38 | for _, v := range deck { 39 | cnt[v]++ 40 | } 41 | res := cnt[deck[0]] 42 | for _, i := range cnt { 43 | res = gcd(res, i) 44 | } 45 | return res >= 2 46 | } 47 | 48 | func gcd(a, b int) int { 49 | if b == 0 { 50 | return a 51 | } 52 | return gcd(b, a%b) 53 | } 54 | -------------------------------------------------------------------------------- /Problems/924. Minimize Malware Spread/924. Minimize Malware Spread.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "sort" 4 | 5 | func minMalwareSpread(graph [][]int, initial []int) int { 6 | num := len(graph) 7 | root := make([]int, num) 8 | for i := range root { 9 | root[i] = i 10 | } 11 | for i := range graph { 12 | for j := i + 1; j < num; j++ { 13 | if graph[i][j] == 1 { 14 | connect(root, i, j) 15 | } 16 | } 17 | } 18 | cnt := make(map[int]int) 19 | for i := range root { 20 | cnt[find(root, i)]++ 21 | } 22 | //note, we need to identify if there are multiple malwares in current union, if so, delete one of them won't work 23 | cntmal := make([]int, num) 24 | for i := range initial { 25 | cntmal[find(root, initial[i])]++ 26 | } 27 | sort.Slice(initial, func(a, b int) bool { 28 | if cnt[find(root, initial[a])] == cnt[find(root, initial[b])] { 29 | return initial[a] < initial[b] 30 | } else { 31 | return cnt[find(root, initial[a])] > cnt[find(root, initial[b])] 32 | } 33 | }) 34 | for i := range initial { 35 | if cntmal[find(root, initial[i])] == 1 { 36 | return initial[i] 37 | } 38 | } 39 | return initial[0] 40 | } 41 | 42 | func find(root []int, a int) int { 43 | if root[a] != a { 44 | root[a] = find(root, root[a]) 45 | } 46 | return root[a] 47 | } 48 | 49 | func connect(root []int, a, b int) { 50 | ra := find(root, a) 51 | rb := find(root, b) 52 | if ra != rb { 53 | root[ra] = rb 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /Problems/927. Three Equal Parts/927. Three Equal Parts.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func threeEqualParts(A []int) []int { 4 | //if there are three equal parts, then the zero/one pattern of the number must be the same for the three number 5 | //first count the total one in the array 6 | //the number of ones for each number is cnt/=3 7 | //to get the exact number, traverse from the rightmost part 8 | //count one to the target number 9 | if len(A) < 3 { 10 | return []int{-1, -1} 11 | } 12 | numOnes := 0 13 | for i := range A { 14 | if A[i] == 1 { 15 | numOnes++ 16 | } 17 | } 18 | if numOnes == 0 { 19 | return []int{0, 2} 20 | } 21 | if numOnes%3 != 0 { 22 | return []int{-1, -1} 23 | } 24 | cnt := numOnes / 3 25 | r := len(A) - 1 26 | rCnt := 0 27 | for rCnt < cnt { 28 | if A[r] == 1 { 29 | rCnt++ 30 | } 31 | r-- 32 | } 33 | lp := len(A) - r - 1 //pattern length 34 | //then remove all leading zero for the leftmost part 35 | l := 0 36 | for A[l] == 0 { 37 | l++ 38 | } 39 | //check if the pattern matches (left and right) 40 | for i := 0; i < lp; i++ { 41 | if A[l+i] != A[r+1+i] { 42 | return []int{-1, -1} 43 | } 44 | } 45 | m := l + lp 46 | //remove all the leading zero for the middle part 47 | for A[m] == 0 { 48 | m++ 49 | } 50 | //check if the pattern matches (middle and right) 51 | for i := 0; i < lp; i++ { 52 | if A[m+i] != A[r+1+i] { 53 | return []int{-1, -1} 54 | } 55 | } 56 | return []int{l + lp - 1, m + lp} 57 | } 58 | -------------------------------------------------------------------------------- /Problems/935. Knight Dialer/935. Knight Dialer.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func knightDialer(N int) int { 4 | mod := int(1e9) + 7 5 | dp := make([]int, 10) 6 | res := 0 7 | cnt := map[int][]int{} 8 | cnt[0] = []int{4, 6} 9 | cnt[1] = []int{6, 8} 10 | cnt[2] = []int{7, 9} 11 | cnt[3] = []int{4, 8} 12 | cnt[4] = []int{3, 9, 0} 13 | cnt[5] = []int{} 14 | cnt[6] = []int{1, 7, 0} 15 | cnt[7] = []int{2, 6} 16 | cnt[8] = []int{1, 3} 17 | cnt[9] = []int{2, 4} 18 | for i := range dp { 19 | dp[i] = 1 20 | } 21 | for i := 1; i < N; i++ { 22 | next := make([]int, 10) 23 | for j := range next { 24 | for prev := range cnt[j] { 25 | next[j] += dp[cnt[j][prev]] 26 | next[j] %= mod 27 | } 28 | } 29 | dp = next 30 | } 31 | for i := range dp { 32 | res += dp[i] 33 | res %= mod 34 | } 35 | return res 36 | } 37 | -------------------------------------------------------------------------------- /Problems/943. Find the Shortest Superstring/943. Find the Shortest Superstring.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /Problems/947. Most Stones Removed with Same Row or Column/947. Most Stones Removed with Same Row or Column.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "strconv" 5 | ) 6 | 7 | /* 8 | Taking each axis position as a node, and a stone connects x and y axis 9 | */ 10 | var cnt = 0 11 | 12 | func removeStones(stones [][]int) int { 13 | cnt = 0 14 | root := make(map[string]string) 15 | for i := range stones { 16 | x := strconv.Itoa(stones[i][0]) + "X" 17 | y := strconv.Itoa(stones[i][1]) + "Y" 18 | connect(root, x, y) 19 | } 20 | 21 | return len(stones) - cnt 22 | } 23 | 24 | func find(root map[string]string, a string) string { 25 | if _, ok := root[a]; !ok { 26 | cnt++ 27 | root[a] = a 28 | } 29 | if root[a] != a { 30 | root[a] = find(root, root[a]) 31 | } 32 | return root[a] 33 | } 34 | 35 | func connect(root map[string]string, a, b string) { 36 | ra := find(root, a) 37 | rb := find(root, b) 38 | if ra != rb { 39 | cnt-- 40 | root[ra] = rb 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Problems/949. Largest Time for Given Digits/949. Largest Time for Given Digits.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "strconv" 4 | 5 | //func largestTimeFromDigits(A []int) string { 6 | // sort.Ints(A) 7 | // num := 0 8 | // for i := range A { 9 | // num = num*10 + A[i] 10 | // } 11 | // for i := 23; i >= 0; i-- { 12 | // for j := 59; j >= 0; j-- { 13 | // temp := make([]int, 4, 4) 14 | // temp[0] = i / 10 15 | // temp[1] = i % 10 16 | // temp[2] = j / 10 17 | // temp[3] = j % 10 18 | // sort.Ints(temp) 19 | // curr := 0 20 | // for i := range temp { 21 | // curr = curr*10 + temp[i] 22 | // } 23 | // if curr == num { 24 | // return fmt.Sprintf("%02d", i) + ":" + fmt.Sprintf("%02d", j) 25 | // } 26 | // } 27 | // } 28 | // return "" 29 | //} 30 | 31 | func largestTimeFromDigits(A []int) string { 32 | perm := make([]string, 0, 24) 33 | used := make([]bool, 4, 4) 34 | dfs(used, "", A, &perm) 35 | for _, s := range perm { 36 | h, _ := strconv.Atoi(s[:2]) 37 | m, _ := strconv.Atoi(s[2:]) 38 | if h <= 23 && m <= 59 { 39 | return s[:2] + ":" + s[2:] 40 | } 41 | } 42 | return "" 43 | } 44 | 45 | func dfs(used []bool, curr string, A []int, perm *[]string) { 46 | if len(curr) == 4 { 47 | *perm = append(*perm, curr) 48 | return 49 | } 50 | for i := 0; i < 4; i++ { 51 | if !used[i] { 52 | used[i] = true 53 | s := strconv.Itoa(A[i]) 54 | dfs(used, curr+s, A, perm) 55 | used[i] = false 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Problems/956. Tallest Billboard/956. Tallest Billboard.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func tallestBillboard(rods []int) int { 4 | sum := 0 5 | for i := range rods { 6 | sum += rods[i] 7 | } 8 | dp := make([][]int, len(rods)+1) 9 | for i := range dp { 10 | dp[i] = make([]int, sum+1) 11 | for j := range dp[i] { 12 | dp[i][j] = -1 13 | } 14 | } 15 | dp[0][0] = 0 16 | for i := range rods { 17 | h := rods[i] 18 | for j := 0; j <= sum; j++ { 19 | if dp[i][j] == -1 { 20 | continue 21 | } 22 | dp[i+1][j] = max(dp[i][j], dp[i+1][j]) //not used 23 | dp[i+1][j+h] = max(dp[i][j], dp[i+1][j+h]) //put on higher rod 24 | dp[i+1][abs(j-h)] = max(dp[i+1][abs(j-h)], dp[i][j]+min(h, j)) //put on shorter rod 25 | } 26 | } 27 | return dp[len(rods)][0] 28 | } 29 | 30 | func min(a, b int) int { 31 | if a < b { 32 | return a 33 | } 34 | return b 35 | } 36 | 37 | func abs(a int) int { 38 | if a < 0 { 39 | return -a 40 | } 41 | return a 42 | } 43 | 44 | func max(a, b int) int { 45 | if a < b { 46 | return b 47 | } 48 | return a 49 | } 50 | -------------------------------------------------------------------------------- /Problems/959. Regions Cut By Slashes /959. Regions Cut By Slashes.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func regionsBySlashes(grid []string) int { 4 | /* 5 | _ _ 6 | |\ /| 7 | |/ \| 8 | if the character is blank, all the four parts: top(0), down(3), left(1), right(2) connect each other 9 | if the character is \, top and right connect, bottom and left connect 10 | if the character is /, top and left connect, bottom and right connect 11 | */ 12 | n := len(grid) 13 | root := make([]int, n*n*4) 14 | for i := range root { 15 | root[i] = i 16 | } 17 | cnt := n * n * 4 18 | for i := 0; i < n; i++ { 19 | for j := 0; j < n; j++ { 20 | if i > 0 { 21 | //connect top and previous row down 22 | connect(4*(i*n+j)+0, ((i-1)*n+j)*n+3, root, &cnt) 23 | } 24 | if j > 0 { 25 | //connect left and previous column right 26 | connect(4*(i*n+j)+1, (i*n+j-1)*4+2, root, &cnt) 27 | } 28 | if grid[i][j] != '/' { 29 | //connect top right, left bottom 30 | connect(4*(i*n+j)+0, 4*(i*n+j)+2, root, &cnt) 31 | connect(4*(i*n+j)+1, 4*(i*n+j)+3, root, &cnt) 32 | } 33 | if grid[i][j] != '\\' { 34 | //connect top left, right bottom 35 | connect(4*(i*n+j)+0, 4*(i*n+j)+1, root, &cnt) 36 | connect(4*(i*n+j)+2, 4*(i*n+j)+3, root, &cnt) 37 | } 38 | } 39 | } 40 | 41 | return cnt 42 | } 43 | 44 | func find(root []int, a int) int { 45 | if root[a] == a { 46 | return a 47 | } 48 | root[a] = find(root, root[a]) 49 | return root[a] 50 | } 51 | 52 | func connect(a, b int, root []int, cnt *int) bool { 53 | ra := find(root, a) 54 | rb := find(root, b) 55 | if ra != rb { 56 | root[ra] = rb 57 | *cnt -= 1 58 | return true 59 | } 60 | return false 61 | } 62 | -------------------------------------------------------------------------------- /Problems/964. Least Operators to Express Number/964. Least Operators to Express Number.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "math" 4 | 5 | /* 6 | the question is similar to transform target into a x-base number 7 | since the division operator / only returns rational number so the only use of / is to get x/x = 1 = x^0 8 | target = a*(x^0)+b*(x^1)+c*(x^2)..... 9 | a, b, c can also be negative 10 | 11 | To get the least operation, we need to find the largest possible exponent of x 12 | exp = log(target)/log(x) 13 | */ 14 | 15 | func leastOpsExpressTarget(x int, target int) int { 16 | exps := int(math.Log(float64(target))/math.Log(float64(x))) + 1 17 | //exps is the total bits of base x 18 | mem := make(map[int]map[int]int, 0) 19 | return dfs(x, target, exps, mem) - 1 //the first number do not have sign 20 | } 21 | 22 | func dfs(x int, target int, k int, mem map[int]map[int]int) int { 23 | if k == 0 { 24 | return int(target) * 2 25 | //if this is the last bit 26 | } 27 | if v, ok := mem[target][k]; ok { 28 | return v 29 | } 30 | times := target / int(math.Pow(float64(x), float64(k))) 31 | //check the number of current bit 32 | //the final solution of current bit is either times or times+1 33 | //it cannot be times-1, since then it will never fulfil target 34 | //if use times+2, the target is over by a larger number, which we need to reduce later, so it won't be a optimized solution 35 | ans1 := times*k + dfs(x, abs(target-times*int(math.Pow(float64(x), float64(k)))), k-1, mem) 36 | ans2 := (times+1)*k + dfs(x, abs(target-(times+1)*int(math.Pow(float64(x), float64(k)))), k-1, mem) 37 | mem[target] = make(map[int]int, 0) 38 | temp := min(ans1, ans2) 39 | mem[target][k] = temp 40 | return temp 41 | } 42 | 43 | func min(a, b int) int { 44 | if a > b { 45 | return b 46 | } 47 | return a 48 | } 49 | 50 | func abs(a int) int { 51 | if a < 0 { 52 | return -1 * a 53 | } 54 | return a 55 | } 56 | -------------------------------------------------------------------------------- /Problems/972. Equal Rational Numbers/972. Equal Rational Numbers.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "golang.org/x/tools/go/ssa/interp/testdata/src/strings" 5 | "strconv" 6 | ) 7 | 8 | func isRationalEqual(S string, T string) bool { 9 | return convert(S) == convert(T) 10 | } 11 | 12 | func convert(s string) float64 { 13 | i := strings.Index(s, "(") 14 | if i > 0 { 15 | base := s[0:i] 16 | rep := s[i+1 : len(s)-1] 17 | for j := 0; j < 20; j++ { 18 | base += rep 19 | } 20 | res, _ := strconv.ParseFloat(base, 64) 21 | return res 22 | } 23 | res, _ := strconv.ParseFloat(s, 64) 24 | return res 25 | } 26 | -------------------------------------------------------------------------------- /Problems/973. K Closest Points to Origin/973. K Closest Points to Origin.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "container/heap" 5 | "fmt" 6 | ) 7 | 8 | func kClosest(points [][]int, K int) [][]int { 9 | pq := &maxHeap{} 10 | heap.Init(pq) 11 | for _, v := range points { 12 | heap.Push(pq, v) 13 | if pq.Len() > K { 14 | heap.Pop(pq) 15 | } 16 | } 17 | res := make([][]int, 0) 18 | for pq.Len() > 0 { 19 | res = append(res, heap.Pop(pq).([]int)) 20 | } 21 | return res 22 | } 23 | 24 | type maxHeap [][]int 25 | 26 | func (pq maxHeap) Len() int { 27 | return len(pq) 28 | } 29 | 30 | func (pq maxHeap) Less(i, j int) bool { 31 | ii := pq[i][0]*pq[i][0] + pq[i][1]*pq[i][1] 32 | jj := pq[j][0]*pq[j][0] + pq[j][1]*pq[j][1] 33 | return ii > jj 34 | } 35 | 36 | func (pq maxHeap) Swap(i, j int) { 37 | pq[i], pq[j] = pq[j], pq[i] 38 | } 39 | 40 | func (pq *maxHeap) Push(x interface{}) { 41 | *pq = append(*pq, x.([]int)) 42 | } 43 | 44 | func (pq *maxHeap) Pop() interface{} { 45 | ptr := *pq 46 | x := ptr[len(ptr)-1] 47 | *pq = ptr[0 : len(ptr)-1] 48 | return x 49 | } 50 | 51 | func KClosest2(points [][]int, K int) [][]int { 52 | quickSelect(points, 0, len(points)-1, K) 53 | res := make([][]int, 0) 54 | for i := 0; i < K; i++ { 55 | res = append(res, points[i]) 56 | } 57 | return res 58 | } 59 | 60 | func quickSelect(a [][]int, l, r, k int) { 61 | pivot := l 62 | for i := l; i < r; i++ { 63 | if (a[i][0]*a[i][0] + a[i][1]*a[i][1]) <= (a[r][0]*a[r][0] + a[r][1]*a[r][1]) { 64 | a[i], a[pivot] = a[pivot], a[i] 65 | pivot += 1 66 | } 67 | } 68 | a[pivot], a[r] = a[r], a[pivot] 69 | if pivot+1 == k { 70 | return 71 | } else if pivot+1 > k { 72 | quickSelect(a, l, pivot-1, k) 73 | } else { 74 | quickSelect(a, pivot+1, r, k) 75 | } 76 | } 77 | 78 | func main() { 79 | fmt.Print(KClosest2([][]int{{6, 10}, {-3, 3}, {-2, 5}, {0, 2}}, 3)) 80 | } 81 | -------------------------------------------------------------------------------- /Problems/984. String Without AAA or BBB/984. String Without AAA or BBB.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func strWithout3a3b(A int, B int) string { 4 | chars := make([]byte, 0, A+B) 5 | a := byte('a') 6 | b := byte('b') 7 | if B > A { 8 | a, b = b, a 9 | A, B = B, A 10 | } 11 | for A > 0 { 12 | A-- 13 | chars = append(chars, a) 14 | if A > B { 15 | chars = append(chars, a) 16 | A-- 17 | } 18 | if B > 0 { 19 | chars = append(chars, b) 20 | B-- 21 | } 22 | } 23 | return string(chars) 24 | } 25 | 26 | /* In each round, add the char with more number, if its number is still larger than another, append again 27 | If the smaller number is still larger than zero, append it 28 | */ 29 | -------------------------------------------------------------------------------- /Problems/990. Satisfiability of Equality Equations/990. Satisfiability of Equality Equations.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func equationsPossible(equations []string) bool { 4 | root := make([]int, 26) 5 | for i := range root { 6 | root[i] = i 7 | } 8 | for i := range equations { 9 | idx1 := int(equations[i][0] - 'a') 10 | idx2 := int(equations[i][3] - 'a') 11 | if equations[i][1] == '=' { 12 | connect(idx1, idx2, root) 13 | } 14 | } 15 | for i := range equations { 16 | idx1 := int(equations[i][0] - 'a') 17 | idx2 := int(equations[i][3] - 'a') 18 | if equations[i][1] != '=' { 19 | if find(idx1, root) == find(idx2, root) { 20 | return false 21 | } 22 | } 23 | } 24 | return true 25 | } 26 | 27 | func find(a int, root []int) int { 28 | if root[a] == a { 29 | return root[a] 30 | } 31 | root[a] = find(root[a], root) 32 | return root[a] 33 | } 34 | 35 | func connect(a, b int, root []int) bool { 36 | ra := find(a, root) 37 | rb := find(b, root) 38 | if ra == rb { 39 | return false 40 | } else { 41 | root[ra] = rb 42 | return true 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Problems/991. Broken Calculator/991. Broken Calculator.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func brokenCalc(X int, Y int) int { 4 | if X >= Y { 5 | return X - Y 6 | } else { 7 | if Y%2 == 0 { 8 | return brokenCalc(X, Y/2) + 1 9 | } else { 10 | return brokenCalc(X, Y+1) + 1 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Problems/994. Rotting Oranges/994. Rotting Oranges.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func orangesRotting(grid [][]int) int { 4 | m := len(grid) 5 | n := len(grid[0]) 6 | shift := []int{0, 1, 0, -1, 0} 7 | queue := make([][]int, 0, 100) 8 | cnt := 0 9 | step := -1 10 | for i := range grid { 11 | for j := range grid[i] { 12 | if grid[i][j] == 1 { 13 | cnt++ 14 | } else if grid[i][j] == 2 { 15 | queue = append(queue, []int{i, j}) 16 | } 17 | } 18 | } 19 | if cnt == 0 { 20 | return 0 21 | } 22 | for len(queue) > 0 { 23 | step++ 24 | size := len(queue) 25 | for i := size - 1; i >= 0; i-- { 26 | cur := queue[i] 27 | cx := cur[0] 28 | cy := cur[1] 29 | for j := 0; j < 4; j++ { 30 | nx := cx + shift[j] 31 | ny := cy + shift[j+1] 32 | if nx >= 0 && nx < m && ny >= 0 && ny < n && grid[nx][ny] == 1 { 33 | cnt-- 34 | grid[nx][ny] = 2 35 | queue = append(queue, []int{nx, ny}) 36 | } 37 | } 38 | } 39 | queue = queue[size:] 40 | } 41 | if cnt == 0 { 42 | return step 43 | } else { 44 | return -1 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Utils/LCDS.go: -------------------------------------------------------------------------------- 1 | package Utils 2 | 3 | type ListNode struct { 4 | Val int 5 | Next *ListNode 6 | } 7 | 8 | type TreeNode struct { 9 | Val int 10 | Left *TreeNode 11 | Right *TreeNode 12 | } 13 | --------------------------------------------------------------------------------