😎
Cracking Leetcode
  • 😎Welcome to TimmyBeef's Cracking Leetcode
  • Recursion tips
  • Atlas
    • 1366. Rank Teams by Votes
  • 3 pointers
    • 689. Maximum Sum of 3 Non-Overlapping Subarrays
  • two pointer
    • Tips
    • 881. Boats to Save People
    • 11. Container With Most Water
    • 27. Remove Element
    • 42. Trapping Rain Water
    • 167. Two Sum II - Input array is sorted
    • 15. 3Sum
    • 611. Valid Triangle Number
    • 18. 4Sum
    • Page 6
    • 344. Reverse String
    • 345. Reverse Vowels of a String
    • 392. Is Subsequence
    • 763. Partition Labels
    • 844. Backspace String Compare
    • 925. Long Pressed Name
    • 977. Squares of a Sorted Array
    • 986. Interval List Intersections
    • Same direction, from start
    • Lintcode - 610. Two Sum - Difference equals to target
    • Lintcode - 1870 · Number of Substrings with All Zeroes
    • 283. Move Zeroes
    • 1513. Number of Substrings With Only 1s
    • 26. Remove Duplicates from Sorted Array
    • sliding win - subarray type
      • 2444. Count Subarrays With Fixed Bounds
      • 992. Subarrays with K Different Integers
      • 2962. Count Subarrays Where Max Element Appears at Least K Times
    • sliding window
      • 395. Longest Substring with At Least K Repeating Characters
      • 1052. Grumpy Bookstore Owner
      • 1208. Get Equal Substrings Within Budget
      • 487. Max Consecutive Ones II
      • lintcode 604 · Window Sum (basic)
      • 3. Longest Substring Without Repeating Characters
      • 340. Longest Substring with At Most K Distinct Characters (sliding window, hashmap, two pointers),
      • 424. Longest Repeating Character Replacement
      • 1151. Minimum Swaps to Group All 1's Together
      • 2134. Minimum Swaps to Group All 1's Together II
      • 1610. Maximum Number of Visible Points
      • 76. Minimum Window Substring (sliding window)
      • 567. Permutation in String
      • 438. Find All Anagrams in a String
      • 1004. Max Consecutive Ones III
      • 1248. Count Number of Nice Subarrays
      • 2516. Take K of Each Character From Left and Right
      • 424. Longest Repeating Character Replacement (ref to 1004
      • Page 12
    • Page 7
    • 1423. Maximum Points You Can Obtain from Cards
    • 643. Maximum Average Subarray I
    • 1176. Diet Plan Performance
    • 125. Valid Palindrome
    • 2108. Find First Palindromic String in the Array
    • 2109. Adding Spaces to a String
    • 2110. Number of Smooth Descent Periods of a Stock
    • 209. Minimum Size Subarray Sum
    • 777. Swap Adjacent in LR String
    • lintcode 1375 · Substring With At Least K Distinct Characters
    • 443. String Compression
    • 1855. Maximum Distance Between a Pair of Values
    • 80. Remove Duplicates from Sorted Array II
    • 26. Remove Duplicates from Sorted Array
    • summaryRanges
    • 5. Longest Palindromic Substring
    • 647. Palindromic Substrings
    • Page 13
  • stack & queue
    • tips
    • 1963. Minimum Number of Swaps to Make the String Balanced
    • 962. Maximum Width Ramp
    • 1249. Minimum Remove to Make Valid Parentheses
    • 232. Implement Queue using Stacks
    • 20. Valid Parentheses
    • 155. Min Stack
    • 394. Decode String
    • 856. Score of Parentheses
    • 224. Basic Calculator
    • 227. Basic Calculator II
    • 946. Validate Stack Sequences
    • 150. Evaluate Reverse Polish Notation
    • 2434. Using a Robot to Print the Lexicographically Smallest String
    • Queue
    • 950. Reveal Cards In Increasing Order
  • Tree
    • N-ary
    • 1261. Find Elements in a Contaminated Binary Tree
    • 2458. Height of Binary Tree After Subtree Removal Queries
    • 2641. Cousins in Binary Tree II
    • 998. Maximum Binary Tree II
    • 1367. Linked List in Binary Tree
    • 1506. Find Root of N-Ary Tree
    • BST
      • 669. Trim a Binary Search Tree
      • 99. Recover Binary Search Tree
      • 501. Find Mode in Binary Search Tree
      • 96. Unique Binary Search Trees
    • Binary Tree classic
      • 333. Largest BST Subtree
      • 965. Univalued Binary Tree
      • 1110. Delete Nodes And Return Forest
      • 450. Delete Node in a BST
      • 1028. Recover a Tree From Preorder Traversal
      • 109. Convert Sorted List to Binary Search Tree
      • 919. Complete Binary Tree Inserter
      • BS DFS enhancement
        • 107. Binary Tree Level Order Traversal II
        • 814. Binary Tree Pruning
        • 979. Distribute Coins in Binary Tree
        • 1325. Delete Leaves With a Given Value
      • 106. Construct Binary Tree from Inorder and Postorder Traversal
      • 105. Construct Binary Tree from Preorder and Inorder Traversal
      • 889. Construct Binary Tree from Preorder and Postorder Traversal
      • 226. Invert Binary Tree
      • 116. Populating Next Right Pointers in Each Node
    • BST classic
      • 1038. Binary Search Tree to Greater Sum Tree
      • 230. Kth Smallest Element in a BST
    • tips
    • 1028. Recover a Tree From Preorder Traversal
    • 971. Flip Binary Tree To Match Preorder Traversal
    • (specail) 314. Binary Tree Vertical Order Traversal
    • (314 followup) 987. Vertical Order Traversal of a Binary Tree
    • 655. Print Binary Tree
    • (bfs)993. Cousins in Binary Tree
    • 94. Binary Tree Inorder Traversal
    • 102. Binary Tree Level Order Traversal (BFS)
    • 114. Flatten Binary Tree to Linked List
    • 144. Binary Tree Preorder Traversal
    • 145. Binary Tree Postorder Traversal
    • preorder
    • 100. Same Tree
    • 101. Symmetric Tree
    • 230. Kth Smallest Element in a BST
    • 257. Binary Tree Paths
    • 112. Path Sum
    • 113. Path Sum II
    • 129. Sum Root to Leaf Numbers (example)
    • 404. Sum of Left Leaves (example)
    • 111. Minimum Depth of Binary Tree
    • 104. Maximum Depth of Binary Tree (divide & conquer)
    • 110. Balanced Binary Tree (divide & conquer)
    • 543. Diameter of Binary Tree
    • 1522. Diameter of N-Ary Tree
    • 687. Longest Univalue Path
    • 515. Find Largest Value in Each Tree Row (BFS)
    • 572. Subtree of Another Tree
    • 589. N-ary Tree Preorder Traversal
    • 590. N-ary Tree Postorder Traversal
    • 617. Merge Two Binary Trees
    • 700. Search in a Binary Search Tree
    • 112. Path Sum
    • 124. Binary Tree Maximum Path Sum
    • 199. Binary Tree Right Side View -BFS
    • 437. Path Sum III
    • 98. Validate Binary Search Tree
    • 270. Closest Binary Search Tree Value
    • 272. Closest Binary Search Tree Value II
    • 173. Binary Search Tree Iterator (stack)
    • 938. Range Sum of BST
    • LCA
      • 235. (LCA) Lowest Common Ancestor of a Binary Search Tree
      • 236. (LCA) Lowest Common Ancestor of a Binary Tree
      • 1644. Lowest Common Ancestor of a Binary Tree II
      • 1650. (LCA) Lowest Common Ancestor of a Binary Tree III
      • 1257. Smallest Common Region
      • 1676. Lowest Common Ancestor of a Binary Tree IV
      • 1123. Lowest Common Ancestor of Deepest Leaves
      • 2096. Step-By-Step Directions From a Binary Tree Node to Another
    • 863. All Nodes Distance K in Binary Tree
    • 652. Find Duplicate Subtrees
    • 366. Find Leaves of Binary Tree
    • 606. Construct String from Binary Tree
    • 285. Inorder Successor in BST
    • 545. Boundary of Binary Tree
    • 582. Kill Process
    • 337. House Robber III
    • 2265. Count Nodes Equal to Average of Subtree
  • DFS & BFS
    • Eulerian paths
      • 332. Reconstruct Itinerary
      • 2097. Valid Arrangement of Pairs
    • Tips
    • Graph I
    • Graph II
      • Bipartite
      • 785. Is Graph Bipartite?
      • 886. Possible Bipartition
      • 1820. Maximum Number of Accepted Invitations (Maximum Bipartite Matching)
      • MST - Prim's Algo
        • 1135. Connecting Cities With Minimum Cost
        • 1584. Min Cost to Connect All Points
      • MST - Kruskal's Algo
        • 1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree
        • 1584. Min Cost to Connect All Points
      • Floyd Algorithm
        • 1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance
    • 988. Smallest String Starting From Leaf
    • 463. Island Perimeter (actually counting
    • 997. Find the Town Judge
    • 1042. Flower Planting With No Adjacent
    • 332. Reconstruct Itinerary
    • Generic DFS
      • 386. Lexicographical Numbers
      • 365. Water and Jug Problem
      • 672. Bulb Switcher II
      • 279. Perfect Squares
      • 37. Sudoku Solver
    • DFS
      • backtracking tips
        • 46. Permutations - example
        • 47. Permutations II (i = 0, sort, used
        • Page 9
        • 39. Combination Sum (not use befroe, so int I = start, dfs(i) -> is i !!
        • 78. Subsets (not use befroe, so int I = start, dfs(i+1)
        • 77. Combinations (not use before, so int I = start, dfs(i+1
        • 90. Subsets II (not use before so int I = start, dfs(i+1), and sort
        • 40. Combination Sum II (not use before so int I = start, dfs(i+1), and sort
        • 17. Letter Combinations of a Phone Number
        • 37. Sudoku Solver
        • 51. N-Queens
        • 52. N-Queens II
        • 60. Permutation Sequence
        • 79. Word Search (backtracking)
        • 212. Word Search II (backtracking)
        • 113. Path Sum II
        • 282. Expression Add Operators
        • 301. Remove Invalid Parentheses
        • 399. Evaluate Division (backtracking
        • 489. Robot Room Cleaner
        • 465. Optimal Account Balancing
        • 996. Number of Squareful Arrays
        • 1568. Minimum Number of Days to Disconnect Island
        • 2065. Maximum Path Quality of a Graph
        • 1306. Jump Game III
        • dispatch to k subsets or ? subsets
          • 473. Matchsticks to Square
          • 698. Partition to K Equal Sum Subsets
          • 1986. Minimum Number of Work Sessions to Finish the Tasks
          • 1723. Find Minimum Time to Finish All Jobs
      • 279. Perfect Squares
      • 241. Different Ways to Add Parentheses
      • 417. Pacific Atlantic Water Flow
      • 200. Number of Islands
      • 959. Regions Cut By Slashes (in the end use 200)
      • 1905. Count Sub Islands
      • 1162. As Far from Land as Possible
      • 1162 compare to 317
      • 22. Generate Parentheses
      • 129. Sum Root to Leaf Numbers
      • 425. Word Squares
      • 694. Number of Distinct Islands
      • 1254. Number of Closed Islands
      • 1020. Number of Enclaves
      • 419. Battleships in a Board
      • 711. Number of Distinct Islands II
      • DFS with return value
      • Copy of 129. Sum Root to Leaf Numbers
      • 2477. Minimum Fuel Cost to Report to the Capital
      • 2492. Minimum Score of a Path Between Two Cities
    • 582. Kill Process
    • BFS
      • 102. Binary Tree Level Order Traversal (BFS)
      • 103. Binary Tree Zigzag Level Order Traversal
      • 127. Word Ladder - BFS
      • 133. Clone Graph (BFS, DFS)
      • 200. Number of Islands (BFS)
      • 733. Flood Fill
      • 1765. Map of Highest Peak
      • 1926. Nearest Exit from Entrance in Maze
      • 317. Shortest Distance from All Buildings
      • 399. Evaluate Division
      • 433. Minimum Genetic Mutation
      • 542. 01 Matrix
      • 547. Number of Provinces
      • 934. Shortest Bridge
      • 994. Rotting Oranges
      • 1091. Shortest Path in Binary Matrix
      • 690. Employee Importance
      • 773. Sliding Puzzle
      • 1293. Shortest Path in a Grid with Obstacles Elimination
      • 818. Race Car
      • Dijkstra
      • 2577. Minimum Time to Visit a Cell In a Grid
      • 01 BFS
        • (01 BFS) 1368. Minimum Cost to Make at Least One Valid Path in a Grid
        • (01 BFS) 2290. Minimum Obstacle Removal to Reach Corner
          • Page 14
      • 2642. Design Graph With Shortest Path Calculator
      • 1514. Path with Maximum Probability (spfa, dijkstra)
      • lintcode 1565 · Modern Ludo I (spfa, dijkstra)
      • 743. Network Delay Time (dijkstra
      • 2662. Minimum Cost of a Path With Special Roads
      • 787. Cheapest Flights Within K Stops (Dijsktra, DP
      • 490. The Maze (spfa
      • 505. The Maze II (spfa
      • 499. The Maze III (spfa, dijkstra
      • 1631. Path With Minimum Effort (dijkstra
      • 752. Open the Lock
      • 1197. Minimum Knight Moves
      • 1730. Shortest Path to Get Food
      • 305. Number of Islands II (union-find)
      • 803. Bricks Falling When Hit (backward union find)
      • 765. Couples Holding Hands
      • 841. Keys and Rooms
      • 2812. Find the Safest Path in a Grid
      • 2510. Check if There is a Path With Equal Number of 0's And 1's
    • 247. Strobogrammatic Number II
  • Binary Search (BS)
    • Template & Tips
    • 2594. Minimum Time to Repair Cars
    • 2226. Maximum Candies Allocated to K Children
    • 274. H-Index
    • 剑指 Offer 53 - II. 0~n-1中缺失的数字
    • 704. Binary Search
    • 33. Search in Rotated Sorted Array
    • 34. Find First and Last Position of Element in Sorted Array
    • 81. Search in Rotated Sorted Array II
    • 35. Search Insert Position
    • 69. Sqrt(x)
    • 74. Search a 2D Matrix
    • 240. Search a 2D Matrix II
    • 278. First Bad Version
    • 349. Intersection of Two Arrays
    • 374. Guess Number Higher or Lower
    • 153. Find Minimum in Rotated Sorted Array
    • 154. Find Minimum in Rotated Sorted Array II
    • 162. Find Peak Element
    • 528. Random Pick with Weight
    • 1428. Leftmost Column with at Least a One
    • 108. Convert Sorted Array to Binary Search Tree
    • 852. Peak Index in a Mountain Array
    • 658. Find K Closest Elements
    • 1891. Cutting Ribbons
    • Lintcode - 610. Two Sum - Difference equals to target
    • State machine or Binary search
      • 792. Number of Matching Subsequences
    • 475. Heaters
    • 410. Split Array Largest Sum
    • 1539. Kth Missing Positive Number
    • 1060. Missing Element in Sorted Array
    • 702. Search in a Sorted Array of Unknown Size
    • 1618. Maximum Font to Fit a Sentence in a Screen
    • New way:
    • 875. Koko Eating Bananas
    • 2517. Maximum Tastiness of Candy Basket ( 類似2616
    • 1011. Capacity To Ship Packages Within D Days
    • 911. Online Election
    • 1482. Minimum Number of Days to Make m Bouquets
    • 1552. Magnetic Force Between Two Balls
  • Greedy
    • 670. Maximum Swap
    • 1605. Find Valid Matrix Given Row and Column Sums
    • 330. Patching Array
    • (same as 330) 2952. Minimum Number of Coins to be Added
    • 1404. Number of Steps to Reduce a Number in Binary Representation to One
    • 55. Jump Game
    • 45. Jump Game II
    • 122. Best Time to Buy and Sell Stock II
    • 134. Gas Station
    • 135. Candy
    • 1840. Maximum Building Height
    • 452. Minimum Number of Arrows to Burst Balloons
    • 455. Assign Cookies
    • 659. Split Array into Consecutive Subsequences
    • 860. Lemonade Change
    • 874. Walking Robot Simulation
    • 1029. Two City Scheduling
    • 1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts
    • 1710. Maximum Units on a Truck
    • 767. Reorganize String
    • lintcode 1871 · Maximum moment
    • 1564. Put Boxes Into the Warehouse I
    • 1580. Put Boxes Into the Warehouse II
    • 921. Minimum Add to Make Parentheses Valid
    • 1167. Minimum Cost to Connect Sticks
    • 871. Minimum Number of Refueling Stops
    • 807. Max Increase to Keep City Skyline
    • 670. Maximum Swap
    • 1675. Minimize Deviation in Array (pq or TreeSet
    • 1567. Maximum Length of Subarray With Positive Product
    • 926. Flip String to Monotone Increasing
    • 2214. Minimum Health to Beat Game
    • 1686. Stone Game VI
  • Divide and Conquer
    • 169. Majority Element
    • 4. Median of Two Sorted Arrays
  • Linked List
    • 2807. Insert Greatest Common Divisors in Linked List
    • 725. Split Linked List in Parts
    • 143. Reorder List
    • 19. Remove Nth Node From End of List
    • 21. Merge Two Sorted Lists
    • 23. Merge k Sorted Lists
    • 141. Linked List Cycle
    • 160. Intersection of Two Linked Lists
    • 206. Reverse Linked List
    • 876. Middle of the Linked List
    • 234. Palindrome Linked List
    • 2816. Double a Number Represented as a Linked List
    • 369. Plus One Linked List
  • Dynamic programming (DP)
    • 1639. Number of Ways to Form a Target String Given a Dictionary
    • Prefix & each position substring
      • 2707. Extra Characters in a String
      • 3291. Minimum Number of Valid Strings to Form Target I
    • 1395. Count Number of Teams
    • 873. Length of Longest Fibonacci Subsequence
    • 741. Cherry Pickup
    • 2222. Number of Ways to Select Buildings
    • 1043. Partition Array for Maximum Sum
    • 1335. Minimum Difficulty of a Job Schedule
    • 2919. Minimum Increment Operations to Make Array
    • 823. Binary Trees With Factors
    • 174. Dungeon Game
    • 396. Rotate Function
    • 467. Unique Substrings in Wraparound String
    • How to save space complexity?
    • tips
    • 509. Fibonacci Number
    • 53. Maximum Subarray (1D-dp)
    • 53. Maximum Subarray (kadane-algo
    • 918. Maximum Sum Circular Subarray (kadane-algo)
    • 2036. Maximum Alternating Subarray Sum (kadane-algo)
    • 152. Maximum Product Subarray (1d-dp)
    • 70. Climbing Stairs (1D-dp)
    • 91. Decode Ways
    • 62. Unique Paths (2D-dp)
    • 63. Unique Paths II (2D-dp)
    • 118. Pascal's Triangle
    • 119. Pascal's Triangle II
    • 2221. Find Triangular Sum of an Array
    • 120. Triangle (1d)
    • 264. Ugly Number II
    • 313. Super Ugly Number
    • LIS
      • 300. Longest Increasing Subsequence (LIS)
      • 354. Russian Doll Envelopes
      • 1964. Find the Longest Valid Obstacle Course at Each Position
      • 673. Number of Longest Increasing Subsequence
      • 2370. Longest Ideal Subsequence
    • 198. House Robber (1d to 2d, 1d, fib)
    • 213. House Robber II
    • 256. Paint House
    • 276. Paint Fence
    • stock tips
      • 121. Best Time to Buy and Sell Stock
      • 122. Best Time to Buy and Sell Stock II
      • 123. Best Time to Buy and Sell Stock III
      • 188. Best Time to Buy and Sell Stock IV
      • 309. Best Time to Buy and Sell Stock with Cooldown
      • 714. Best Time to Buy and Sell Stock with Transaction Fee
    • 1411. Number of Ways to Paint N × 3 Grid
    • 72. Edit Distance
    • 1155. Number of Dice Rolls With Target Sum
    • 區間 dp
      • 132. Palindrome Partitioning II (區間型 + 一般 dp
      • 516. Longest Palindromic Subsequence
    • 322. Coin Change
    • 518. Coin Change 2 (Unbounded Knapsack problem)
    • 01 Knapsack
      • lintcoe 92 · Backpack
      • 416. Partition Equal Subset Sum
      • 474. Ones and Zeroes
      • 1049. Last Stone Weight II
    • Pattern Matching DP
      • 10. Regular Expression Matching
      • 44. Wildcard Matching
      • 97. Interleaving String
      • 718. Maximum Length of Repeated Subarray
      • 1062. Longest Repeating Substring
      • 1143. Longest Common Subsequence
    • math
      • 2485. Find the Pivot Integer
      • 812. Largest Triangle Area
      • Page 2
      • 837. New 21 Game
    • Specail - square DP
      • 221. Maximal Square (2D-dp)
      • 1504. Count Submatrices With All Ones
      • 1277. Count Square Submatrices with All Ones
    • 1048. Longest String Chain
    • 931. Minimum Falling Path Sum
    • 1289. Minimum Falling Path Sum II
    • 1937. Maximum Number of Points with Cost
    • 562. Longest Line of Consecutive One in Matrix (3D DP)
    • 413. Arithmetic Slices
    • 446. Arithmetic Slices II - Subsequence
  • 1218. Longest Arithmetic Subsequence of Given Difference
  • 940. Distinct Subsequences II
  • 552. Student Attendance Record II
  • 664. Strange Printer (區間型 dp
  • 1130. Minimum Cost Tree From Leaf Values (區間型
  • 403. Frog Jump
  • 494. Target Sum
  • (array, can be dp)1014. Best Sightseeing Pair
  • 139. Word Break
  • 140. Word Break II (backtracking)
  • 472. Concatenated Words
  • Page 10
  • 139. Word Break
  • 140. Word Break II
  • 1387. Sort Integers by The Power Value
  • 894. All Possible Full Binary Trees
  • Binary search + Robin karp(rolling hash)
    • 1044. Longest Duplicate Substring
    • 1062. Longest Repeating Substring (bs + rolling hash
  • HashTable, HashMap, HashSet
    • (interesting one) 1002. Find Common Characters
    • 1171. Remove Zero Sum Consecutive Nodes from Linked List
    • 1647. Minimum Deletions to Make Character Frequencies Unique
    • 1481. Least Number of Unique Integers after K Removals
    • Page 8
    • 2131. Longest Palindrome by Concatenating Two Letter Words
    • 1679. Max Number of K-Sum Pairs
    • 1. Two Sum
    • 36. Valid Sudoku
    • 49. Group Anagrams
    • 170. Two Sum III - Data structure design
    • 454. 4Sum II
    • 242. Valid Anagram
    • 243. Shortest Word Distance
    • 244. Shortest Word Distance II
    • 245. Shortest Word Distance III
    • 350. Intersection of Two Arrays II
    • 1160. Find Words That Can Be Formed by Characters
    • 2032. Two Out of Three
    • 981. Time Based Key-Value Store
    • 954. Array of Doubled Pairs
    • 2007. Find Original Array From Doubled Array
    • 811. Subdomain Visit Count
    • 833. Find And Replace in String
    • 1554. Strings Differ by One Character
    • 846. Hand of Straights, 1296. Divide Array in Sets of K Consecutive Numbers
    • 1512. Number of Good Pairs
    • 387. First Unique Character in a String
    • 1010. Pairs of Songs With Total Durations Divisible by 60
    • 1152. Analyze User Website Visit Pattern
    • 1657. Determine if Two Strings Are Close
    • 1347. Minimum Number of Steps to Make Two Strings Anagram
    • 2598. Smallest Missing Non-negative Integer After Operations
  • FB Study way
    • Facebook Tips
  • noname
  • Top K elements (heap, bucket sort)
    • 945. Minimum Increment to Make Array Unique
    • 347. Top K Frequent Elements
    • 692. Top K Frequent Words
    • 451. Sort Characters By Frequency
    • 502. IPO
    • 1046. Last Stone Weight
    • 1851. Minimum Interval to Include Each Query
  • bit
    • 2220. Minimum Bit Flips to Convert Number
    • 2419. Longest Subarray With Maximum Bitwise AND
    • 2917. Find the K-or of an Array
    • 717. 1-bit and 2-bit Characters
    • Xor ^
      • 268. Missing Number
      • 136. Single Number
    • 1310. XOR Queries of a Subarray
    • 371. Sum of Two Integers
    • 2275. Largest Combination With Bitwise AND Greater Than Zero (&1, >>= 1 )
    • Bit Mask
      • 137. Single Number II
      • 320. Generalized Abbreviation
    • 231. Power of Two
    • 191. Number of 1 Bits
    • 461. Hamming Distance
    • 477. Total Hamming Distance
    • Abbreviation
      • 408. Valid Word Abbreviation (two pointers)
    • 1284. Minimum Number of Flips to Convert Binary Matrix to Zero Matrix
    • 389. Find the Difference
  • String problem
    • 3. Longest Substring Without Repeating Characters
    • Perform String Shifts
    • 13. Roman to Integer
    • 14. Longest Common Prefix
    • 38. Count and Say
    • 68. Text Justification
    • 418 Sentence Screen Fitting
    • 151. Reverse Words in a String
    • 592. Fraction Addition and Subtraction
    • Page 1
    • 179. Largest Number
    • 468. Validate IP Address
    • 696. Count Binary Substrings
    • 937. Reorder Data in Log Files
    • 1592. Rearrange Spaces Between Words
    • 949. Largest Time for Given Digits
    • 2047. Number of Valid Words in a Sentence
    • 299. Bulls and Cows
    • 293. Flip Game
    • 1525. Number of Good Ways to Split a String
    • 551. Student Attendance Record I
  • array problem or interval
    • 163. Missing Ranges
    • 1441. Build an Array With Stack Operations
    • 12. Integer to Roman
    • 2373. Largest Local Values in a Matrix
    • 54. Spiral Matrix
    • 59. Spiral Matrix II
    • 2326. Spiral Matrix IV
    • 498. Diagonal Traverse
    • 56. Merge Intervals
    • 57. Insert Interval
    • 31. Next Permutation
    • 556. Next Greater Element III
    • 121. Best Time to Buy and Sell Stock
    • 217. Contains Duplicate
    • 219. Contains Duplicate II
    • 253. Meeting Rooms II
    • (similar to 253 )2406. Divide Intervals Into Minimum Number of Groups
    • lintcode - 1897 · Meeting Room III
    • 2402. Meeting Rooms III
    • 436. Find Right Interval
    • 1272. Remove Interval
    • 1288. Remove Covered Intervals
    • 729. My Calendar I
    • (sort by end)find Max Non-overlapping interval
      • 435. Non-overlapping Intervals
    • 422. Valid Word Square
    • 900. RLE Iterator
    • sweep line
      • 3355. Zero Array Transformation I
      • 3356. Zero Array Transformation II
      • 3346. Maximum Frequency of an Element After Performing Operations I & II
      • 759. Employee Free Time
      • 253. Meeting Rooms II
      • 1094. Car Pooling
      • 56. Merge Interval
      • 729. My Calendar I
      • 731. My Calendar II
      • 732. My Calendar III
    • 2018. Check if Word Can Be Placed In Crossword
    • 2158. Amount of New Area Painted Each Day
    • 2345. Finding the Number of Visible Mountains
  • queue, dqueue
    • mono queue
      • 239. Sliding Window Maximum
      • 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 - sliding win +heap
      • 1499. Max Value of Equation
  • stack
    • mono stack
      • 1130. Minimum Cost Tree From Leaf Values
      • 1673. Find the Most Competitive Subsequence
      • Agreegate element on ..range
        • 828. Count Unique Characters of All Substrings of a Given String
      • 1996. The Number of Weak Characters in the Game
      • 739. Daily Temperatures
      • 84. Largest Rectangle in Histogram ( mono increasing stack
      • 456. 132 Pattern
      • 496. Next Greater Element I
      • 503. Next Greater Element II
      • 581. Shortest Unsorted Continuous Subarray
      • 907. Sum of Subarray Minimums
      • 1856. Maximum Subarray Min-Product
      • 2104. Sum of Subarray Ranges
      • 1966. Binary Searchable Numbers in an Unsorted Array
      • 1762. Buildings With an Ocean View
      • 901. Online Stock Span
      • 402. Remove K Digits
      • 316. Remove Duplicate Letters, 1081. Smallest Subsequence of Distinct Characters
      • 255. Verify Preorder Sequence in Binary Search Tree
    • 735. Asteroid Collision
    • 388. Longest Absolute File Path
  • Quick Sort, Quick Select, Kth smallest, Partition
    • tips
    • lintcode 31 · Partition Array (basic)
    • 75. Sort Colors
    • 215. Kth Largest Element in an Array
    • 347. Top K Frequent Elements
    • 973. K Closest Points to Origin
  • Heap
  • 1405. Longest Happy String
  • 1642. Furthest Building You Can Reach
  • Sort
    • 1051. Height Checker
    • 791. Custom Sort String, 1122. Relative Sort Array
    • 853. Car Fleet
    • 1877. Minimize Maximum Pair Sum in Array
    • 1834. Single-Threaded CPU
  • Design
    • 1381. Design a Stack With Increment Operation
    • 146. LRU Cache
    • 295. Find Median from Data Stream
    • 355. Design Twitter
    • 460. LFU Cache
    • 588. Design In-Memory File System
    • 1429. First Unique Number
    • 380. Insert Delete GetRandom O(1)
    • 381. Insert Delete GetRandom O(1) - Duplicates allowed
    • 1146. Snapshot Array
    • 981. Time Based Key-Value Store
    • 359. Logger Rate Limiter
    • 2034. Stock Price Fluctuation
    • 362. Design Hit Counter
    • 348. Design Tic-Tac-Toe
    • 794. Valid Tic-Tac-Toe State
    • 1275. Find Winner on a Tic Tac Toe Game
    • 1628. Design an Expression Tree With Evaluate Function
  • Union Find
    • disjoint set - union find
    • 1579. Remove Max Number of Edges to Keep Graph Fully Traversable
    • 2316. Count Unreachable Pairs of Nodes in an Undirected Graph
    • 261. Graph Valid Tree
    • 323. Number of Connected Components in an Undirected Graph
    • 547. Number of Provinces
    • 990. Satisfiability of Equality Equations
    • 737. Sentence Similarity II (use hashmap version)
    • 684. Redundant Connection
    • 947. Most Stones Removed with Same Row or Column
    • 1202. Smallest String With Swaps
  • Topology sort
    • 207. Course Schedule
    • 210. Course Schedule II
    • 1136. Parallel Courses
    • 2115. Find All Possible Recipes from Given Supplies
    • 269. Alien Dictionary
    • 310. Minimum Height Trees
    • 2285. Maximum Total Importance of Roads
  • merge sort realated
    • 315. Count of Smaller Numbers After Self
  • Path related
    • Dijkstra's Algo
    • 1102. Path With Maximum Minimum Value
  • Couting sort
    • 1122. Relative Sort Array
    • 825. Friends Of Appropriate Ages
  • Trie
    • 208. Implement Trie (Prefix Tree)
    • 211. Design Add and Search Words Data Structure
    • 212. Word Search II
    • 745. Prefix and Suffix Search
    • 1032. Stream of Characters
    • 1268. Search Suggestions System
  • Page 3
  • Math
    • 564. Find the Closest Palindrome
    • 775. Global and Local Inversions
    • 1360. Number of Days Between Two Dates
    • 7. Reverse Integer
    • 9. Palindrome Number
    • 66. Plus One
    • 67. Add Binary
    • 415. Add Strings
    • 2. Add Two Numbers
    • 989. Add to Array-Form of Integer
    • 263. Ugly Number
    • 836. Rectangle Overlap
    • 1025. Divisor Game
    • 202. Happy Number
    • 2033. Minimum Operations to Make a Uni-Value Grid
    • 2048. Next Greater Numerically Balanced Number
    • 843. Guess the Word
    • square
      • 593. Valid Square
      • 939. Minimum Area Rectangle
      • 963. Minimum Area Rectangle II
      • 2013. Detect Squares
    • 384. Shuffle an Array
    • 149. Max Points on a Line
    • 2028. Find Missing Observations
    • 2128. Remove All Ones With Row and Column Flips
    • 539. Minimum Time Difference
    • 258. Add Digits
    • Page 5
    • 957. Prison Cells After N Days
    • 2178. Maximum Split of Positive Even Integers
    • 1492. The kth Factor of n
    • 273. Integer to English Words
  • Prefix Sum
    • 1608. Special Array With X Elements Greater Than or Equal X
    • (prefix product + siliding win)713. Subarray Product Less Than K
    • 930. Binary Subarrays With Sum
    • 2256. Minimum Average Difference
    • Page
    • 303. Range Sum Query - Immutable
    • 304. Range Sum Query 2D - Immutable
    • 560. Subarray Sum Equals K
    • lintcode 1844 · subarray sum equals to k II
    • 325. Maximum Size Subarray Sum Equals k (can refer to lintcode 1844)
    • 209. Minimum Size Subarray Sum
    • 1477. Find Two Non-overlapping Sub-arrays Each With Target Sum
    • 525. Contiguous Array
    • Diff array (差分
      • 370. Range Addition (差分
      • 1109. Corporate Flight Bookings (差分
      • 1094. Car Pooling (差分
      • 995. Minimum Number of K Consecutive Bit Flips
    • 1685. Sum of Absolute Differences in a Sorted Array
    • (sum %= k) 523. Continuous Subarray Sum
    • (sum %= k) 974. Subarray Sums Divisible by K
    • (sum % p) 1590. Make Sum Divisible by P
    • 2845. Count of Interesting Subarrays
    • 2155. All Divisions With the Highest Score of a Binary Array
    • 2875. Minimum Size Subarray in Infinite Array
  • Weekly Contest
    • Weekly Contest 274
      • 2124. Check if All A's Appears Before All B's
      • 2125. Number of Laser Beams in a Bank
      • 2126. Destroying Asteroids
      • 2127. Maximum Employees to Be Invited to a Meeting
    • Weekly Contest 275
      • 2133. Check if Every Row and Column Contains All Numbers
      • 2134. Minimum Swaps to Group All 1's Together II
      • 2135. Count Words Obtained After Adding a Letter
    • Weekly Contest 276
      • 2138. Divide a String Into Groups of Size k
      • 2139. Minimum Moves to Reach Target Score
      • 2140. Solving Questions With Brainpower
      • Page 4
    • Weekly Contest 279
      • 2164. Sort Even and Odd Indices Independently
      • 2165. Smallest Value of the Rearranged Number
      • 2166. Design Bitset
    • Weekly Contest 339
      • 2609. Find the Longest Balanced Substring of a Binary String
      • 2610. Convert an Array Into a 2D Array With Conditions
      • 2611. Mice and Cheese
    • Weekly Contest 340
    • 2614. Prime In Diagonal
    • 2615. Sum of Distances (same as 2121. Intervals Between Identical Elements)
    • 2616. Minimize the Maximum Difference of Pairs (binary search idea
    • TreeMap or TreeSet
    • 432. All O`one Data Structure
    • 2353. Design a Food Rating System
    • 2817. Minimum Absolute Difference Between Elements With Constraint
    • Pratical
    • 2437. Number of Valid Clock Times
    • 681. Next Closest Time
    • Min Max
    • 2905. Find Indices With Index and Value Difference II
    • 2910. Minimum Number of Groups to Create a Valid Assignment
    • Min or Max Prefix Suffix
    • 2012. Sum of Beauty in the Array
    • 2874. Maximum Value of an Ordered Triplet II
    • 2909. Minimum Sum of Mountain Triplets II
    • Greedy
    • 2918. Minimum Equal Sum of Two Arrays After Replacing Zeros
    • 1921. Eliminate Maximum Number of Monsters
    • 2147. Number of Ways to Divide a Long Corridor
    • DFS
    • 814. Binary Tree Pruning
    • 2925. Maximum Score After Applying Operations on a Tree
    • (re-root) 834. Sum of Distances in Tree
    • Math, Geometry
    • 1266. Minimum Time Visiting All Points
    • 2849. Determine if a Cell Is Reachable at a Given Time
    • 1759. Count Number of Homogenous Substrings
    • 2 pointers
    • 1578. Minimum Time to Make Rope Colorful
    • 2332. The Latest Time to Catch a Bus
    • Brainteaser
    • 1503. Last Moment Before All Ants Fall Out of a Plank
    • 1535. Find the Winner of an Array Game
    • Good Qestions
    • 2948. Make Lexicographically Smallest Array by Swapping Elements
    • 1930. Unique Length-3 Palindromic Subsequences
    • 1980. Find Unique Binary String - Cantor's Diagonalization
    • 1727. Largest Submatrix With Rearrangements
    • Backtracking practice
    • 2664. The Knight’s Tour
    • Matrix
    • 1582. Special Positions in a Binary Matrix
    • 531. Lonely Pixel I
  • O(n) to find top2 min or max number
    • 1913. Maximum Product Difference Between Two Pairs
    • 2706. Buy Two Chocolates
    • Some interesting easy
      • 1071. Greatest Common Divisor of Strings
      • 1758. Minimum Changes To Make Alternating Binary String
    • Atlassian
      • 353. Design Snake Game
    • Page 11
Powered by GitBook
On this page
  • dp
  • use variables

Was this helpful?

  1. Dynamic programming (DP)

1411. Number of Ways to Paint N × 3 Grid

Previous714. Best Time to Buy and Sell Stock with Transaction FeeNext72. Edit Distance

Last updated 3 years ago

Was this helpful?

ref:

1. think what part I stuck?
the DP formula, 
所以要針對所有排列組合, 3*3*3 = 27, 去思考
ABC
ABA
這兩種狀況下, 排除限制條件後, 會剩幾個?

the detail of problem (vertical side, 不能一樣
也就是這一列如果是 010
下一列三個位置不能跟上一列一樣

2. see solution, think about how this person came out this solution? what’s their thought process, why we have the same question and same knowledge, but I cant?
主要還是思考排列組合的過程, 要分析 ABC ABA 兩種case

3. note strategy! remember it!
所以策略是什麼? 要在看 leetcode 1349

dp

time: O(n)

space: O(n)

notice use long first

class Solution {
    public int numOfWays(int n) {
        // 0 ABC 012 => ABC 102, 201, ABA 101, 121
        // 1 ABA 010 => ABC 102 201, ABA 101, 121, 202
        
        // dp[i][0] = dp[i-1][0]*2 + dp[i-1][1]*2;
        // dp[i][1] = dp[i-1][0]*2 + dp[i-1][1]*3;
        
        int mod = 1000000007;
        long dp[][] = new long[n][2];
        
        dp[0][0] = 6;
        dp[0][1] = 6;
        
        for (int i = 1; i < n; i++) {
            dp[i][0] = (dp[i-1][0]*2 + dp[i-1][1]*2)%mod;
            dp[i][1] = (dp[i-1][0]*2 + dp[i-1][1]*3)%mod;
        }
        
        return (int)(dp[n-1][0] + dp[n-1][1])%mod;
    }
}

use variables

time: O(n)

space: O(1)

class Solution {
    public int numOfWays(int n) {
        // 0 ABC 012 => ABC 102, 201, ABA 101, 121
        // 1 ABA 010 => ABC 102 201, ABA 101, 121, 202
        
        // dp[i][0] = dp[i-1][0]*2 + dp[i-1][1]*2;
        // dp[i][1] = dp[i-1][0]*2 + dp[i-1][1]*3;
        
        int mod = 1000000007;
        
        long dp0 = 6;
        long dp1 = 6;
        
        for (int i = 1; i < n; i++) {
            long newDp0 = (dp0*2 + dp1*2)%mod;
            long newDp1 = (dp0*2 + dp1*3)%mod;
            dp0 = newDp0;
            dp1 = newDp1;
        }
        
        return (int)(dp0 + dp1)%mod;
    }
}
Logo[Java] Detailed Explanation with Graph Demo - DP - Easy Understand - undefined - LeetCodeLeetCode