Leetcode

# Title Acceptance Difficulty Frequency Tags Done/Lock
1 Two Sum 31.8%  Easy High Array, Hash Table  Done
2  Add Two Numbers  27.0%  Medium  Linked List, Math
3  Longest Substring Without Repeating Characters 24.0%  Medium  High  Hash Table, Two Pointers, String  Done
4  Median of Two Sorted Arrays  21.2%  Hard  Binary Search, Array, Divide and Conquer
5  Longest Palindromic Substring  25.0%  Medium  String
6 ZigZag Conversion  26.3%  Medium  String
7  Reverse Integer  23.9%  Easy  Math
8  String to Integer (atoi)  13.9%  Medium  Math, String
9  Palindrome Number  34.4%  Easy  Math
10  Regular Expression Matching  23.9%  Hard  Dynamic Programming, Backtracking, String
11  Container With Most Water  36.2%  Medium  Array, Two Pointers
12  Integer to Roman  43.5%  Medium  Math, String
13  Roman to Integer  44.4%  Easy  Math, String
14  Longest Common Prefix  31.0%  Easy  String
15  3Sum  21.3%  Medium  Array, Two Pointers
16  3Sum Closest  30.7%  Medium  Array, Two Pointers
17  Letter Combinations of a Phone Number  33.3%  Medium  Backtracking, String
18  4Sum  26.0%  Medium  Array, Hash Table, Two Pointers  Skip
19  Remove Nth Node From End of List  32.6%  Medium Linked List, Two Pointers
20  Valid Parentheses  32.7%  Easy Stack, String
 21  Merge Two Sorted Lists  38.4%  Easy  Linked List
 22  Generate Parentheses  42.9%  Medium  Backtracking, String
 23 Merge k Sorted Lists  26.5%  Hard  Divide and Conquer, Linked List, Heap
 24  Swap Nodes in Pairs  37.5%  Medium  Linked List
 25  Reverse Nodes in k-Group  30.1%  Hard  Linked List
 26  Remove Duplicates from Sorted Array  35.4%  Easy  Array, Two Pointers
 27  Remove Element 37.7%  Easy  Array, Two Pointers
28 Implement strStr()  27.4%  Easy  Two Pointers, String
 29 Divide Two Integers 16.0%  Medium  Math, Binary Search
30  Substring with Concatenation of All Words  21.8%  Hard  Hash Table, Two Pointers, String
 31  Next Permutation  28.4%  Medium  Array
 32  Longest Valid Parentheses  23.0%  Hard  Dynamic Programming, String
 33  Search in Rotated Sorted Array  32.1%  Medium  Binary Search, Array
 34  Search for a Range  31.1%  Medium  Binary Search, Array
 35  Search Insert Position  39.2%  Easy  Array, Binary Search
 36  Valid Sudoku  34.6%  Medium  Hash Table  Done
 37 Sudoku Solver  28.9%  Hard  Backtracking, Hash Table
 38  Count and Say  33.3%  Easy  String
 39  Combination Sum  36.8%  Medium  Array, Backtracking
 40 Combination Sum II  32.1%  Medium  Array, Backtracking
 41  First Missing Positive  25.1%  Hard  Array
 42  Trapping Rain Water  35.9%  Hard  Array, Stack, Two Pointers
 43  Multiply Strings  26.4%  Medium  Math, String
 44  Wildcard Matching  19.5%  Hard  Dynamic Programming, Backtracking, Greedy, String
 45  Jump Game II  26.1%  Hard  Array, Greedy
 46  Permutations  41.6%  Medium  Backtracking
 47  Permutations II  31.6%  Medium  Backtracking
48  Rotate Image  37.7%  Medium Array
 49  Group Anagrams  32.9%  Medium  Hash Table, String  Done
 50  Pow(x, n)  26.8%  Medium  Binary Search, Math
 51  N-Queens  29.7%  Hard  Backtracking
 52  N-Queens II  43.4%  Hard  Backtracking
 53  Maximum Subarray  39.1%  Easy  Array, Dynamic Programming, Divide and Conquer
 54  Spiral Matrix  25.1%  Medium  Array
 55  Jump Game  29.3%  Medium  Array, Greedy
56  Merge Intervals  29.1%  Medium  Array, Sort
 57  Insert Interval  26.8%  Hard  Array, Sort
 58 Length of Last Word  31.4%  Easy  String
 59  Spiral Matrix II  38.5%  Medium  Array
60  Permutation Sequence  27.6%  Medium Backtracking, Math
 61  Rotate List  24.2%  Medium  Linked List, Two Pointers
 62  Unique Paths  39.9%  Medium  Array, Dynamic Programming
 63  Unique Paths II  31.2%  Medium  Array, Dynamic Programming
 64  Minimum Path Sum  37.6%  Medium  Array, Dynamic Programming
 65  Valid Number  12.7%  Hard  Math, String
 66  Plus One 37.6%  Easy Array, Math
 67  Add Binary  31.2%  Easy  Math, String
 68  Text Justification  18.5%  Hard  String
 69  Sqrt(x)  27.3%  Easy  Binary Search, Math
 70  Climbing Stairs  39.1%  Easy Dynamic Programming
 71  Simplify Path  24.5%  Medium  Stack, String
 72  Edit Distance 31.0%  Hard  Dynamic Programming, String
 73  Set Matrix Zeroes  35.4%  Medium  Array
 74  Search a 2D Matrix  35.3%  Medium  Array, Binary Search
 75 Sort Colors  37.1%  Medium  Array, Two Pointers, Sort
76  Minimum Window Substring  24.4%  Hard Hash Table, Two Pointers, String
 77  Combinations  38.5%  Medium  Backtracking
 78  Subsets  38.1%  Medium  Array, Backtracking, Bit Manipulation
 79  Word Search  25.8% Medium  Array, Backtracking
 80  Remove Duplicates from Sorted Array II  35.2%  Medium Array, Two Pointers
 81  Search in Rotated Sorted Array II  32.8%  Medium  Array, Binary Search
 82  Remove Duplicates from Sorted List II  28.9%  Medium  Linked List
 83  Remove Duplicates from Sorted List  39.2%  Easy  Linked List
 84 Largest Rectangle in Histogram  26.0%  Hard  Array, Stack
 85 Maximal Rectangle  26.8%  Hard  Array, Hash Table, Stack, Dynamic Programming
86 Partition List  31.9%  Medium  Linked List, Two Pointers
 87 Scramble String 28.5%  Hard  Dynamic Programming, String
 88 Merge Sorted Array  31.6%  Easy  Array, Two Pointers
 89  Gray Code  40.0%  Medium  Backtracking
 90 Subsets II  34.8%  Medium  Array, Backtracking
 91  Decode Ways  19.2%  Medium  Dynamic Programming, String
 92  Reverse Linked List II  30.1%  Medium  Linked List
 93  Restore IP Addresses  26.3%  Medium  Backtracking, String
94  Binary Tree Inorder Traversal  44.9%  Medium  Tree, Hash Table, Stack
 95  Unique Binary Search Trees II  30.8%  Medium Tree, Dynamic Programming
 96  Unique Binary Search Trees  40.2%  Medium  Tree, Dynamic Programming
 97  Interleaving String  24.2%  Hard  Dynamic Programming, String
 98  Validate Binary Search Tree  22.7%  Medium  Tree, Depth-First Search
 99  Recover Binary Search Tree 29.1%  Hard Tree, Depth-First Search
 100  Same Tree  45.7%  Easy  Tree, Depth-First Search
 101  Symmetric Tree 37.6%  Easy  Tree, Depth-First Search, Breadth-First Search
 102  Binary Tree Level Order Traversal  38.0%  Medium  Tree, Breadth-First Search
 103 Binary Tree Zigzag Level Order Traversal  33.1%  Medium  Tree, Breadth-First Search, Stack
 104 Maximum Depth of Binary Tree 51.5%  Easy  Tree, Depth-First Search
 105  Construct Binary Tree from Preorder and Inorder Traversal  31.2%  Medium  Tree, Array, Depth-First Search
 106 Construct Binary Tree from Inorder and Postorder Traversal  31.3%  Medium  Tree, Array, Depth-First Search
 107  Binary Tree Level Order Traversal II  38.7%  Easy  Tree, Breadth-First Search
 108  Convert Sorted Array to Binary Search Tree  41.1%  Easy Tree, Depth-First Search
 109  Convert Sorted List to Binary Search Tree  33.2% Medium  Depth-First Search, Linked List
 110  110. Balanced Binary Tree  36.6%  Easy  Tree, Depth-First Search
 111  Minimum Depth of Binary Tree  32.6%  Easy Tree, Depth-First Search, Breadth-First Search
 112  Path Sum  33.3%  Easy  Tree, Depth-First Search
 113 Path Sum II  32.3%  Medium  Tree, Depth-First Search
114  Flatten Binary Tree to Linked List 34.1%  Medium  Tree, Depth-First Search
115  Distinct Subsequences  30.9%  Hard  Dynamic Programming, String
116  Populating Next Right Pointers in Each Node  36.9%  Medium Tree, Depth-First Search
117  Populating Next Right Pointers in Each Node II 33.6%  Medium  Tree, Depth-First Search
 118  Pascal’s Triangle  37.4%  Easy  Array
 119  Pascal’s Triangle II  35.7%  Easy  Array
 120  Triangle  32.9%  Medium  Array, Dynamic Programming
 121  Best Time to Buy and Sell Stock  40.0%  Easy  Array, Dynamic Programming
 122  Best Time to Buy and Sell Stock II 46.1%  Easy  Array, Greedy
123  Best Time to Buy and Sell Stock III 28.6%  Hard  Array, Dynamic Programming
 124  Binary Tree Maximum Path Sum 25.4%  Hard Tree, Depth-First Search
125  Valid Palindrome  25.7%  Easy  Two Pointers, String
 126  Word Ladder II  13.7%  Hard  Array, Backtracking, Breadth-First Searching, String
 127  Word Ladder  19.2%  Medium
 128  Longest Consecutive Sequence  35.9%  Hard  Array, Union Find
 129  Sum Root to Leaf Numbers  35.6% Medium Tree, Depth-First Search
 130  Surrounded Regions  17.8% Medium  Breadth-First Search, Union Find
 131 Palindrome Partitioning 31.7%  Medium  Backtracking
132  Palindrome Partitioning II  23.7%  Hard  Dynamic Programming
 133  Clone Graph 25.1%  Medium  Depth-First Search, Breadth-First Search, Graph
134  Gas Station  28.8%  Medium  Greedy
 135  Candy  24.2%  Hard  Greedy
136  Single Number  53.4%  Easy  Hash Table, Bit Manipulation
 137  Single Number II  40.6%  Medium  Bit Manipulation
138  Copy List with Random Pointer  26.5% Medium  Hash, Table, Linked List
 139  Word Break  28.9%  Medium  Dynamic Programming
 140  Word Break II  22.6%  Hard  Dynamic Programming, Backtracking
 141  Linked List Cycle  35.6%  Easy  Linked List, Two Pointers
 142  Linked List Cycle II  31.0%  Medium  Linked List, Two Pointers
 143  Reorder List  24.9%  Medium  Linked List
 144  Binary Tree Preorder Traversal  43.8%  Medium  Tree, Stack
 145  Binary Tree Postorder Traversal 39.1%  Hard  Tree, Stack
 146  LRU Cache  16.7%  Hard  Design
 147  Insertion Sort List  32.2%  Medium  Linked List, Sort
 148  Sort List  27.8%  Medium  Linked List, Sort
 149  Max Points on a Line  15.5%  Hard  Hash Table, Math
 150  Evaluate Reverse Polish Notation  26.4%  Medium  Stack
 151  Reverse Words in a String  15.7%  Medium  String
 152 Maximum Product Subarray  24.9%  Medium  Array, Dynamic Programming
 153  Find Minimum in Rotated Sorted Array  39.1%  Medium  Array, Binary Search
 154  Find Minimum in Rotated Sorted Array II  36.5%  Hard  Array, Binary Search
 155  Min Stack  27.2%  Easy  Stack, Design
 156  Binary Tree Upside Down  43.4%  Medium  Y
 157  Read N Characters Given Read4  29.2%  Easy  Y
 158  Read N Characters Given Read4 II – Call multiple times  24.3%  Hard  Y
 159  Longest Substring with At Most Two Distinct Characters  40.1%  Hard  Y
160  Intersection of Two Linked Lists  30.2%  Easy  Linked List
 161  One Edit Distance  30.8%  Medium  Y
 162  Find Peak Element  36.4%  Medium  Binary Search, Array
 163  Missing Ranges  25.7%  Medium  Y
 164  Maximum Gap  28.9%  Hard  Sort
 165  Compare Version Numbers  19.6%  Medium  String
 166  Fraction to Recurring Decimal  17.1%  Medium Hash Table, Math
 167  Two Sum II – Input array is sorted  47.5%  Easy  Array, Two Pointers, Binary Search
 168  Excel Sheet Column Title  25.1%  Easy  Math
 169  Majority Element  45.5%  Easy  Array, Divide and Conquer, Bit Manipulation
 170  Two Sum III – Data structure design  23.4%  Easy  Y
 171  Excel Sheet Column Number  46.0%  Easy  Math
 172  Factorial Trailing Zeroes  35.4%  Easy  Math
 173  Binary Search Tree Iterator  40.0%  Medium  Tree, Stack, Design
 174  Dungeon Game  23.2%  Hard  Binary Search, Dynamic Programming
 179  Largest Number  21.9%  Medium  Sort
 186  Reverse Words in a String II  27.9%  Medium  Y
 187  Repeated DNA Sequences  30.3%  Medium  Hash Table, Bit Manipulation
 188  Best Time to Buy and Sell Stock IV  24.0%  Hard  Dynamic Programming
 189  Rotate Array  23.9%  Easy  Array
 190  Reverse Bits  29.5%  Easy  Bit Manipulation
 191  Number of 1 Bits  38.9%  Easy  Bit Manipulation
 198  House Robber  38.0%  Easy  Dynamic Programming
 199  Binary Tree Right Side View  39.6%  Medium  Tree, Depth-First Search, Breadth-First Search
 200 Number of Islands  33.3%  Medium  Depth-First Search, Breadth-First Search, Union Find
201  Bitwise AND of Numbers Range  33.4%  Medium  Bit Manipulation
 202  Happy Number  39.8%  Easy Hash Table, Math
 203  Remove Linked List Elements  31.5%  Easy  Linked List
 204 Count Primes  26.3%  Easy  Hash Table, Math
 205  Isomorphic Strings  33.0%  Easy  Hash Table
 206  Reverse Linked List  44.4%  Easy  Linked List
 207  Course Schedule  31.1%  Medium  Depth-First Search, Breadth-First Search, Graph, Topological Sort
 208  Implement Trie (Prefix Tree)  26.7%  Medium  Design, Tree
 209  Minimum Size Subarray Sum  29.5%  Medium  Array, Two Pointers, Binary Search
 210  Course Schedule II  26.5%  Medium  Depth-First Search, Breadth-First Search, Graph, Topological Sort
 211  Add and Search Word – Data structure design  21.2%  Medium  Backtracking, Trie, Design
 212  Word Search II  22.8%  Hard  Backtracking, Trie
 213  House Robber II  33.4%  Medium  Dynamic Programming
 214  Shortest Palindrome  23.5%  Hard  String
 215  Kth Largest Element in an Array  38.2%  Medium  Heap, Divide and Conquer
 216  Combination Sum III  43.2%  Medium  Array, Backtracking
 217  Contains Duplicate  44.6%  Easy  Array, Hash Table
 218  The Skyline Problem  26.4%  Hard  Binary Indexed Tree, Segment Tree, Heap, Divide and Conquer
 219  Contains Duplicate II  31.9%  Easy  Array, Hash Table
 220 Contains Duplicate III  19.3%  Medium  Binary Search Tree
 221  Maximal Square  27.8%  Medium Dynamic Programming
 222  Count Complete Tree Nodes  27.1%  Medium   Tree, Binary Search
 223  Rectangle Area  32.3%  Medium  Math
 224  Basic Calculator  26.2%  Hard  Stack, Math
 225 Implement Stack using Queues  31.8%  Easy  Stack, Design
 226  Invert Binary Tree  50.6%  Easy  Tree
 227  Basic Calculator II  28.6%  Medium  String
 228  Summary Ranges  28.7%  Medium  Array
 229  Majority Element II  28.1%  Medium  Array
 230  Kth Smallest Element in a BST  42.7%  Medium  Binary Search, Tree
 231  Power of Two  39.6%  Easy  Math, Bit Manipulation
 232  Implement Queue using Stacks  35.7%  Easy  Stack, Design
 233  Number of Digit One  27.7%  Hard  Math
 234  Palindrome Linked List  32.0%  Easy  Linked List, Two Pointers
 235  Lowest Common Ancestor of a Binary Search Tree  38.4%  Easy  Tree
 236  Lowest Common Ancestor of a Binary Tree  29.6%  Medium  Tree
 237  Delete node in a linked list  45.8%  Easy  Linked List
 238  Product of Array Except Self  48.0%  Medium  Array
 239 Sliding Window Maximum  32.0%  Hard  Heap
 240  Search a 2D Matrix II  38.0%  Medium  Binary Search, Divide and Conquer
241  Different Ways to Add Parentheses  42.3%  Medium  Divide and Conquer
 242  Valid Anagram  45.5%  Easy  Hash Table, Sort
 243  Shortest Word Distance 51.4%  Easy  Y
 244  Shortest Word Distance II  35.8%  Medium  Y
 245  Shortest Word Distance III  49.7%  Medium  Y
 246  Strobogrammatic Number  39.3%  Easy  Y
 247  Strobogrammatic Number II  38.9%  Medium  Y
 248  Strobogrammatic Number III  31.0%  Hard  Y
 249  Group Shifted Strings  40.0%  Medium  Y
 250  Count Univalue Subtrees  41.1%  Medium  Y
 251  Flatten 2D Vector  39.6%  Medium  Y
 252  Meeting rooms  46.4%  Easy  Y
 253  Meeting Rooms II  38.6%  Medium  Y
 254  Factor Combinations  41.5%  Medium  Y
 255  Verify Preorder Sequence in Binary Search Tree  39.4%  Medium  Y
 256  Paint House  45.9%  Easy  Y
 257  Binary Tree Paths  36.5%  Easy  Tree, Depth-First Search
 258  Add Digits  50.6%  Easy  Math
 259  3Sum Smaller  41.0%  Medium  Y
 260  Single Number III  50.2%  Medium  Bit Manipulation
 261 Graph Valid Tree  37.2%  Medium  Y
 263  Ugly Number  38.7%  Easy  Math
 264  Ugly Number II  32.0%  Medium  Dynamic Programming, Heap, Math
 265  Paint House II 37.7%  Hard  Y
 266  Palindrome Permutation  56.1%  Easy  Y
 267  Palindrome Permutation II  31.5%  Medium  Y
 268 Missing Number  43.9%  Easy  Array, Math, Bit Manipulation
 269  Alien Dictionary  22.5%  Hard  Y
 270  Closest Binary Search Tree Value  38.7%  Easy  Y
 271  Encode and Decode Strings  26.2%  Medium  Y
 272  Closest Binary Search Tree Value II  38.2%  Hard  Y
 273  Integer to English Words  21.6%  Hard  Math, String
 274  H-Index 32.6%  Medium  Hash Table, Sort
 275 H-Index II  33.8%  Medium  Binary Search
 276  Paint Fence  34.2%  Easy  Y
 277  Find the Celebrity  35.5%  Medium  Y
 278  First Bad Version  24.7%  Easy  Binary Search
 279 Perfect Squares  35.8%  Medium Dynamic Programming, Breadth-First Search, Math
 280  Wiggle Sort  56.0%  Medium Y
 281  Zigzag Iterator  49.4%  Medium  Y
 282  Expression Add Operators  29.2%  Hard Divide and Conquer
 283 Move Zeroes  48.7%  Easy  Array, Two Pointers
 284  Peeking Iterator  35.2%  Medium Design
 285  Inorder Successor in BST  36.1%  Medium  Y
 286  Walls and Gates  43.3%  Medium  Y
 287  Find the Duplicate Number  42.5%  Medium  Binary Search, Array, Two Pointers
288  Unique Word Abbreviation  15.9%  Medium Y
289  Game of Life  36.5%  Medium  Array
 290  Word Pattern  32.5%  Easy  Hash Table
 291  Word Pattern II  37.8%  Hard Y
 292  Nim Game  54.9%  Easy  Brainteaser
 293  Flip Game  54.7%  Easy  Y
 294  Flip Game II  45.8%  Medium  Y
 295 Find Median from Data Stream  24.7%  Hard  Heap, Design
 296  Best Meeting Point  51.1%  Hard  Y
 297  Serialize and Deserialize Binary Tree  32.4%  Hard  Tree, Design
 298  Binary Tree Longest Consecutive Sequence  40.3%  Medium  Y
 299  Bulls and Cows  33.8%  Medium  Hash Table
 300  Longest Increasing Subsequence  37.7%  Medium  Dynamic Programming, Binary Search
 301  Remove Invalid Parentheses  34.9%  Hard  Depth-First Search, Breadth-First Search
 302  Smallest Rectangle Enclosing Black Pixels  44.6%  Hard  Y
 303  Range Sum Query – Immutable  27.5%  Easy  Dynamic Programming
 304  Range Sum Query 2D – Immutable  23.6%  Medium  Dynamic Programming
 305  Number of Islands II  38.6%  Hard Y
 306  Additive Number 27.3%  Medium  N/A
 307  Range Sum Query – Mutable  19.3%  Medium  Segment Tree, Binary Indexed Tree
 308  Range Sum Query 2D- Mutable  21.3%  Hard  Y
 309  Best Time to Buy and Sell Stock with Cooldown  40.1%  Medium  Dynamic Programming
310  Minimum Height Trees  28.6%  Medium  Breadth-First Search, Graph
 311  50.6%  Medium  Y
 312 Burst Balloons  41.9%  Hard  Dynamic Programming, Divide and Conquer
 313  Super Ugly Number  37.3%  Medium  Math, Heap
 314  36.1%  Medium  Y
 315  34.0%  Hard  Divide and Conquer, Binary Indexed Tree, Segment Tree, Binary Search Tree
 316  Remove Duplicate Letters  29.0%  Hard  Stack, Greedy
 317  Shortest Distance from All Buildings  33.5%  Hard  Y
 318  Maximum Product of Word Lengths  43.1%  Medium  Bit Manipulation
 319  Bulb Switcher  42.1%  Medium  Math, Brainteaser
 320  Generalized Abbreviation  44.1%  Medium  Y
 321  Create Maximum Number  24.2%  Hard  Dynamic Programming, Greedy
 322  Coin Change  26.2%  Medium  Dynamic Programming
 323  47.3%  Medium  Y
 324  Wiggle Sort II  25.5%  Medium  Sort
 325  Maximum Size Subarray Sum Equals k  42.0%  Medium  Y
 326  Power of Three  39.7%  Easy  Math
 327  29.2%  Hard  Divide and Conquer, Binary Search Tree
 328  Odd Even Linked List  42.5%  Medium  Linked List
 329  35.8%  Hard  Depth-First Search, Topological Search, Memoization
 330  Patching Array  31.6%  Hard  Greedy
 331  35.6%  Medium  Stack
 332  28.4%  Medium  Depth-First Search, Graph
 333  Largest BST Subtree  30.1%  Medium  Y
 334  38.4%  Medium  N/A
 335  Self Crossing  24.5%  Hard  Math
 336  25.3%  Hard  Hash Table, String, Trie
 337  42.3%  Medium  Tree, Depth-First Search
 338  60.2%  Medium  Dynamic Programming, Bit Manipulation
 339  Nested List Weight Sum  60.7%  Easy  Y
 340  38.4%  Hard  Y
 341  40.0%  Medium  Stack, Design
 342 37.9%  Easy  Bit Manipulation
 343  45.3%  Medium  Dynamic Programming, Math
 344  58.2%  Easy  Two Pointers, String
 345  37.8%  Easy  Two Pointers, String
346  58.1%  Easy  Y
 347  47.0%  Medium  Hash Table, Heap
 348  45.5%  Medium  Y
 349  46.4%  Easy  Binary Search, Hash Table, Two Pointers, Sort
 350  44.0%  Easy  Binary Search, Hash Table, Two Pointers, Sort
 351  43.2%  Medium  Y
 352  39.3%  Hard  Binary Search Tree
 353  26.0%  Medium
 354  31.9%  Hard  Binary Search, Dynamic Programming
 355  25.1%  Medium  Hash Table, Heap, Design
 356  30.3%  Medium  Y
 357  45.4%  Medium  Dynamic Programming, Backtracking, Math
 358  31.8%  Hard  Y
 359  58.8%  Easy  Y
 360  43.4%  Medium  Y
 361  38.4%  Medium  Y
 362  53.1%  Medium  Y
363  32.5%  Hard  Binary Search,Dynamic Programming, Queue
 364  51.1%  Medium  Y
 365  26.5%  Medium  Math
 366  58.2%  Medium
 367  37.8%  Easy  Binary Search, Math
 368  33.4%  Medium  Dynamic Programming, Math
 369  53.7%  Medium  Y
 370  54.4%  Medium  Y
 371  51.1%  Easy  Bit Manipulation
 372  33.6% Medium  Math
 373  30.3%  Medium  Heap
 374  34.3%  Easy  Binary Search
 375  35.6%  Medium  Dynamic Programming, Minimax
 376  34.9%  Medium  Dynamic Programming, Greedy
 377 41.7%  Medium  Dynamic Programming
 378 43.7%  Medium  Binary Search, Heap
 379  31.1%  Medium  Y
 380  38.9%  Medium  Array, Hash Table, Design
 381  28.4%  Hard  Array, Hash Table, Design
 382  46.5%  Medium  Reservoir Sampling
 383  46.5%  Easy  String
 384  45.5%  Medium  N/A
 385  30.1%  Medium  Stack, String
 386  40.3%  Medium  N/A
 387  46.1%  Easy  N/A
 388  35.6%  Medium  N/A
 389  51.3%  Easy  Hash Table, Bit Manipulation
 390  39.9%  Medium  N/A
 391  25.4%  Hard  N/A
 392  44.2%  Medium  Binary Search, Dynamic Programming, Greedy
 393  34.6%  Medium  Bit Manipulation
 394  40.8%  Medium  Depth-First Search, Stack
 395  35.5%  Medium  N/A
 396  31.2%  Medium  Math
 397  29.6%  Medium  Math, Bit Manipulation
 398  41.5%  Medium  Reservoir Sampling
 399  40.1%  Medium  Math
 400  30.1%  Easy  Math
 401  44.6%  Easy  Backtracking, Bit Manipulation
 402  26.1%  Medium  Stack, Greedy
 403  31.3%  Hard Dynamic Programming
 404  46.4%  Easy  Tree
 405  40.6%  Easy  Bit Manipulation
 406  54.7%  Medium  Greedy
 407  36.1%  Hard  Breadth-First Search, Heap
408  27.5%  Easy  Y
 409  44.9%  Easy  Hash Table
 410  34.6%  Hard  Binary Search, Dynamic Programming
 411  31.7%  Hard  Y
 412  58.7%  Easy  N/A
 413  54.8%  Medium  Dynamic Programming, Math
 414  27.2%  Easy  Array
 415  41.2%  Easy  Math
 416  38.2%  Medium  Dynamic Programming
 417  33.1%  Medium  Depth-First Search, Breadth-First Search
 418  27.3%  Medium  Y
 419  60.6%  Medium  N/A
 420  20.3%  Hard  N/A
 421  44.2%  Medium  Bit Manipulation, Trie
 422  36.1%  Easy  Y
 423  43.1%  Medium  Math
 424  41.1%  Medium  N/A
 425  42.6%  Hard
 432  27.6%  Hard  Design
 434 37.1%  Easy  String
 435  40.1%  Medium  Greedy
 436  41.1%  Medium  Binary Search
 437  39.0%  Easy  Tree
 438  33.5%  Easy  Hash Table
 439  49.9%  Medium  Y
 440  23.0%  Hard N/A
 441  36.0%  Easy  Binary Search, Math
 442  52.9%  Medium  Array
 444  19.7%  Medium  Y
 445  46.2%  Medium  Linked List
 446  24.9%  Hard  Dynamic Programming
 447  43.5%  Easy  Hash Table
 448  52.8%  Easy  Array
 449  42.2%  Medium  Tree
 450  35.5%  Medium  Tree
 451  50.3%  Medium Hash Table, Heap
 452  42.7%  Medium  Greedy
 453  46.6%  Easy  Math
 454  45.4%  Medium  Binary Search, Hash Table
 455  47.2%  Easy Greedy
 456  28.2%  Medium  Stack
 459  38.4%  Easy  String
 460  22.1%  Hard  Design
461 70.6%  Easy  Bit Manipulation
 462  51.2%  Medium  Math
463  56.6%  Easy  Hash Table
 464  23.6%  Medium  Dynamic Programming, Minimax
 465  33.2%  Hard  Y
 466  25.7%  Hard  Dynamic Programming
 467  31.5%  Medium  Dynamic Programming
 468  20.2%  Medium  String
 469  30.1%  Medium
 471  42.0%  Hard
 472  29.7%  Hard  Dynamic Programming, Trie, Depth-First Search
 473  34.1%  Medium  Depth-First Search
 474  37.3%  Medium  Dynamic Programming
 475  29.7%  Easy  Binary Search
 476  61.0%  Easy  Bit Manipulation
 477 46.0%  Medium  Bit Manipulation
 480  31.5%  Hard  N/A
 481  45.3%  Medium  N/A
 482  41.1%  Medium  N/A
 483  30.9%  Hard  Binary Search, Math
 484  52.0%  Medium  Y
 485  54.7%  Easy  Array
 486  44.2%  Medium  Dynamic Programming, Minimax
 487  44.2%  Medium  Y
 488  37.0%  Hard  Depth-First Search
 490  42.1%  Medium  Y
 491  38.6%  Medium  Depth-First Search
 492  48.9%  Easy  N/A
 493  18.5%  Hard  Binary Indexed Tree, Segment Tree, Binary Search Tree, Divide and Conquer
 494  44.0%  Medium  Depth-First Search, Dynamic Programming
 495  51.5%  Medium  Array
 496  57.6%  Easy  Stack
 498  46.4%  Medium  N/A
 499  31.6%  Hard  Y
 500  60.3%  Easy  Hash Table
 501  38.9%  Easy  Tree
 502  33.6%  Hard  Heap, Greedy
 503  46.6%  Medium  Stack
 504  45.7%  Easy  N/A
505  35.5%  Medium  Y
 506  47.4%  Easy  N/A
 507 29.5%  Easy  Math
 508  51.7%  Medium  Tree, Hash Table
 513  55.6%  Medium  Tree, Depth-First Search, Breadth-First Search
 514  33.0%  Hard  “Dynamic Programming”, Depth-First Search, Divide and Conquer
 515  53.1%  Medium  Tree, Depth-First Search, Breadth-First Search
 516  42.0%  Medium  Dynamic Programming
 517  35.4%  Hard  Dynamic Programming, Math
 520  52.7%  Easy  String
 523  21.3%  Medium  Dynamic Programming, Math
 524  40.3%  Medium  Two Pointers, Sort
 525  34.5%  Medium Hash Table
 526  53.4%  Medium  Backtracking
 527  34.1%  Hard  Y
 529  51.8%  Medium  Depth-First Search, Breadth-First Search
 530  48.2%  Easy  Binary Search Tree
 531  50.4%  Medium  Y
 532  27.2%  Easy  Two Pointers, Array
 533  38.9%  Medium
 535  75.9%  Medium  Hash Table, Math
 536  36.6%  Medium  Y
 537  66.3%  Medium  Math, String
 538  52.6%  Medium  Tree
 539  44.8%  Medium  String
 541  44.4%  Easy  String
 542  32.5%  Medium  Depth-First Search, Breadth-First Search
 543  42.6%  Easy  Tree
 544  73.2%  Medium  Y
 545  23.6%  Medium  Y
 546  21.3%  Hard  Dynamic Programming, Depth-First Search

277. (Locked)Find the Celebrity

Difficulty: Medium

Frequency: N/A

Suppose you are at a party with n people (labeled from 0 to n - 1) and among them, there may exist one celebrity. The definition of a celebrity is that all the other n - 1 people know him/her but he/she does not know any of them.

Now you want to find out who the celebrity is or verify that there is not one. The only thing you are allowed to do is to ask questions like: “Hi, A. Do you know B?” to get information of whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense).

You are given a helper function bool knows(a, b) which tells you whether A knows B. Implement a functionint findCelebrity(n), your function should minimize the number of calls to knows.

Note: There will be exactly one celebrity if he/she is in the party. Return the celebrity’s label if there is a celebrity in the party. If there is no celebrity, return -1.


Test Cases:


Solution 1:

Data structure:
Steps:
Complexity:
Runtime:
Space:
Code:
// Forward declaration of the knows API.  
bool knows(int a, int b);  
  
class Solution {  
public:  
    int findCelebrity(int n) { 
        if (n <= 1) return n;
        int cand = 0;
        for (int i = 1; i < n; i++) {
            if (!know(i, cand) {
                cand = i;
            }
        }
        for (int j = 0; j < n; j++) {
            if (j == cand) continue;
            if (!know(j, cand) || know(cand, j)) return -1;
        }
        return cand;
    }
};

Solution 2:

Data structure:
steps:
Complexity:
Runtime:
Space:
Code:


Submission errors:

 

Things to learn:

289. Game of Life

Difficulty: Medium

Frequency: N/A

According to the Wikipedia’s article: “The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.”

Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):

  1. Any live cell with fewer than two live neighbors dies, as if caused by under-population.
  2. Any live cell with two or three live neighbors lives on to the next generation.
  3. Any live cell with more than three live neighbors dies, as if by over-population..
  4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.

Write a function to compute the next state (after one update) of the board given its current state.

Follow up:

  1. Could you solve it in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells.
  2. In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array. How would you address these problems?

Test Cases:


Solution 1:

Data structure:
Steps:
Complexity:
Runtime:
Space:
Code:
class Solution {
public:
    void gameOfLife(vector<vector<int>>& board) {
        int m = board.size(), n = m ? board[0].size() : 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                int count = 0;
                for (int I = max(i - 1, 0); I < min(i + 2, m); I++) {
                    for (int J = max(j - 1, 0); J < min(j + 2, n); J++) {
                        count += board[I][J] & 1;
                    }
                }
                if (count == 3 || count - board[i][j] == 3) {
                    board[i][j] |= 2;
                }
            }
        }
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                board[i][j] >>= 1;
            }
        }
    }
};

Solution 2:

Data structure:
steps:
Complexity:
Runtime:
Space:
Code:


Submission errors:

 

Things to learn:

239. Sliding Window Maximum

Difficulty: Hard

Frequency: N/A

Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.

For example,
Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.

Window position                Max
---------------               -----
[1  3  -1] -3  5  3  6  7       3
 1 [3  -1  -3] 5  3  6  7       3
 1  3 [-1  -3  5] 3  6  7       5
 1  3  -1 [-3  5  3] 6  7       5
 1  3  -1  -3 [5  3  6] 7       6
 1  3  -1  -3  5 [3  6  7]      7

Therefore, return the max sliding window as [3,3,5,5,6,7].

Note:
You may assume k is always valid, ie: 1 ≤ k ≤ input array’s size for non-empty array.

Follow up:
Could you solve it in linear time?

Hint:

  1. How about using a data structure such as deque (double-ended queue)?
  2. The queue size need not be the same as the window’s size.
  3. Remove redundant elements and the queue should store only elements that need to be considered.

Test Cases:


Solution 1:

Data structure:
Steps:
Complexity:
Runtime:
Space:
Code:
class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        deque<int> dq;
        vector<int> results;
        for (int i = 0; i < nums.size(); i++) {
            if (!dq.empty() && dq.front() == i - k) dq.pop_front();
            while (!dq.empty() && nums[dq.back()] < nums[i]) {
                dq.pop_back();
            }
            dq.push_back(i);
            if (i >= k - 1) {
                results.push_back(nums[dq.front()]);
            }
        }
        return results;
    }
};

Solution 2:

Data structure:
steps:
Complexity:
Runtime:
Space:
Code:


Submission errors:

 

Things to learn:

229. Majority Element II

Difficulty: Medium

Frequency: N/A

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.

Hint:

  1. How many majority elements could it possibly have?
  2. Do you have a better hint? Suggest it!

Test Cases:


Solution 1:

Data structure:
Steps:
Complexity:
Runtime:
Space:
Code:
class Solution {
public:
    vector<int> majorityElement(vector<int>& nums) {
        int cnt1 = 0, cnt2 = 0, a = 0, b = 1;
        for (int n : nums) {
            if (a == n) cnt1++;
            else if (b == n) cnt2++;
            else if (cnt1 == 0) {
                a = n;
                cnt1 = 1;
            } else if (cnt2 == 0) {
                b = n;
                cnt2 = 1;
            } else {
                cnt1--;
                cnt2--;
            }
        }
        cnt1 = cnt2 = 0;
        for (int n : nums) {
            if (n == a) cnt1++;
            else if (n == b) cnt2++;
        }
        vector<int> results;
        if (cnt1 > nums.size() / 3) results.push_back(a);
        if (cnt2 > nums.size() / 3) results.push_back(b);
        return results;
    }
};

Solution 2:

Data structure:
steps:
Complexity:
Runtime:
Space:
Code:


Submission errors:

 

Things to learn:

218. The Skyline Problem

Difficulty: Hard

Frequency: N/A

A city’s skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Now suppose you are given the locations and height of all the buildings as shown on a cityscape photo (Figure A), write a program to output the skyline formed by these buildings collectively (Figure B).

Buildings Skyline ContourThe geometric information of each building is represented by a triplet of integers [Li, Ri, Hi], where Li and Ri are the x coordinates of the left and right edge of the ith building, respectively, and Hi is its height. It is guaranteed that 0 ≤ Li, Ri ≤ INT_MAX, 0 < Hi ≤ INT_MAX, and Ri - Li > 0. You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0.

For instance, the dimensions of all buildings in Figure A are recorded as: [ [2 9 10], [3 7 15], [5 12 12], [15 20 10], [19 24 8] ] .

The output is a list of “key points” (red dots in Figure B) in the format of [ [x1,y1], [x2, y2], [x3, y3], ... ] that uniquely defines a skyline. A key point is the left endpoint of a horizontal line segment. Note that the last key point, where the rightmost building ends, is merely used to mark the termination of the skyline, and always has zero height. Also, the ground in between any two adjacent buildings should be considered part of the skyline contour.

For instance, the skyline in Figure B should be represented as:[ [2 10], [3 15], [7 12], [12 0], [15 10], [20 8], [24, 0] ].

Notes:

  • The number of buildings in any input list is guaranteed to be in the range [0, 10000].
  • The input list is already sorted in ascending order by the left x position Li.
  • The output list must be sorted by the x position.
  • There must be no consecutive horizontal lines of equal height in the output skyline. For instance, [...[2 3], [4 5], [7 5], [11 5], [12 7]...] is not acceptable; the three lines of height 5 should be merged into one in the final output as such: [...[2 3], [4 5], [12 7], ...]

Test Cases:


Solution 1:

Data structure:
Steps:
Complexity:
Runtime:
Space:
Code:
class Solution {
public:
    vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) {
        multimap<int, int> coords;
        for (auto& b : buildings) {
            coords.emplace(b[0], b[2]);
            coords.emplace(b[1], -b[2]);
        }
        
        multiset<int> heights = {0};
        vector<pair<int, int>> corners;
        int x = -1, y = 0;
        for (auto& p : coords) {
            if ((x >= 0) && (p.first != x) && (corners.empty() || corners.rbegin()->second != y)) {
                corners.emplace_back(x, y);
            }
            if (p.second >= 0) {
                heights.insert(p.second);
            } else {
                heights.erase(heights.find(-p.second));
            }
            x = p.first;
            y = *heights.rbegin();
        }
        
        if ((!corners.empty()) && (corners.rbegin()->second != 0)) {
            corners.emplace_back(x, 0);
        }

        return corners;
    }
};

Solution 2:

Data structure:
steps:
Complexity:
Runtime:
Space:
Code:


Submission errors:

 

Things to learn:

126. Word Ladder II

Difficulty: Hard

Frequency: N/A

Given two words (beginWord and endWord), and a dictionary’s word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:

  1. Only one letter can be changed at a time
  2. Each intermediate word must exist in the word list

For example,

Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]

Return

  [
    ["hit","hot","dot","dog","cog"],
    ["hit","hot","lot","log","cog"]
  ]

Note:

  • All words have the same length.
  • All words contain only lowercase alphabetic characters.

Test Cases:


Solution 1:

Data structure:
Steps:
Complexity:
Runtime:
Space:
Code:
class Solution {
public:
    vector<vector<string>> findLadders(string beginWord, string endWord, unordered_set<string> &wordList) {
        m.clear();
        results.clear();
        path.clear();
        
        wordList.insert(beginWord);
        wordList.insert(endWord);
        
        unordered_set<string> cur_lev;
        cur_lev.insert(beginWord);
        unordered_set<string> next_lev;
        path.push_back(endWord);
        
        while (true) {
            // delete previous level words
            for (auto it = cur_lev.begin(); it != cur_lev.end(); it++) {
                wordList.erase(*it);
            }
            // find current level words
            for (auto it = cur_lev.begin(); it != cur_lev.end(); it++) {
                findDict(*it, wordList, next_lev);
            }
            if (next_lev.empty()) {
                return results;
            }
            // if find endWord
            if (next_lev.find(endWord) != wordList.end()) {
                output(beginWord, endWord);
                return results;
            }
            cur_lev.clear();
            cur_lev = next_lev;
            next_lev.clear();
        }
        return results;
    }
private:
    unordered_map<string, vector<string>> m;
    vector<vector<string>> results;
    vector<string> path;
    void findDict(string word, unordered_set<string>& wordList, unordered_set<string>& next_level) {
        int n = word.size();
        string s = word;
        for (int i = 0; i < n; i++) {
            s = word;
            for (int j = 0; j < 26; j++) {
                s[i] = 'a' + j;
                if (wordList.find(s) != wordList.end()) {
                    next_level.insert(s);
                    m[s].push_back(word);
                }
            }
        }
    }
    void output(string& start, string last) {
        if (last == start) {
            reverse(path.begin(), path.end());
            results.push_back(path);
            reverse(path.begin(), path.end());
        } else {
            for (int i = 0; i < m[last].size(); i++) {
                path.push_back(m[last][i]);
                output(start, m[last][i]);
                path.pop_back();
            }
        }
    }
};

Solution 2:

Data structure:
steps:
Complexity:
Runtime:
Space:
Code:


Submission errors:

 

Things to learn:

210. Course Schedule II

Difficulty: Medium

Frequency: N/A

There are a total of n courses you have to take, labeled from 0 to n - 1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.

There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.

For example:

2, [[1,0]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]

4, [[1,0],[2,0],[3,1],[3,2]]

There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is[0,2,1,3].

Note:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.

click to show more hints.

Hints:

  1. This problem is equivalent to finding the topological order in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses.
  2. Topological Sort via DFS – A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort.
  3. Topological sort could also be done via BFS.

Test Cases:


Solution 1:

Data structure:
Steps:
Complexity:
Runtime:
Space:
Code:
class Solution {
private:
    vector<unordered_set<int>> make_graph(int numCourses, vector<pair<int, int>>& prerequisites) {
        vector<unordered_set<int>> graph(numCourses);
        for (auto pre : prerequisites) {
            graph[pre.second].insert(pre.first);
        }
        return graph;
    }
    bool dfs(vector<unordered_set<int>>& graph, int node, vector<bool>& onpath, vector<bool>& visited, vector<int>& result) {
        if (visited[node]) return false;
        visited[node] = onpath[node] = true;
        for (int neighbor : graph[node]) {
            if (onpath[neighbor] || dfs(graph, neighbor, onpath, visited, result)) {
                return true;
            }
        }
        result.push_back(node);
        return onpath[node] = false;
    }
public:
    vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
        vector<unordered_set<int>> graph = make_graph(numCourses, prerequisites);
        vector<bool> onpath(numCourses, false), visited(numCourses, false);
        vector<int> result;
        for (int i = 0; i < numCourses; i++) {
            if (!visited[i] && dfs(graph, i, onpath, visited, result)) {
                return {};
            }
        }
        reverse(result.begin(), result.end());
        return result;
    }
};

Solution 2:

Data structure:
steps:
Complexity:
Runtime:
Space:
Code:


Submission errors:

 

Things to learn:

207. Course Schedule

Difficulty: Medium

Frequency: N/A

There are a total of n courses you have to take, labeled from 0 to n - 1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?

For example:

2, [[1,0]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.

2, [[1,0],[0,1]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.

Note:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.

click to show more hints.

Hints:

  1. This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses.
  2. Topological Sort via DFS – A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort.
  3. Topological sort could also be done via BFS.

Test Cases:


Solution 1:

Data structure:
Steps:
Complexity:
Runtime:
Space:
Code:
class Solution {
private:
    vector<unordered_set<int>> make_graph(int numCourses, vector<pair<int, int>>& prerequisites) {
        vector<unordered_set<int>> graph(numCourses);
        for (auto pre : prerequisites) {
            graph[pre.second].insert(pre.first);
        }
        return graph;
    }
    bool dfs_cycle(vector<unordered_set<int>>& graph, int node, vector<bool>& onpath, vector<bool>& visited) {
        if (visited[node]) return false;
        onpath[node] = visited[node] = true;
        for (int neighbor : graph[node]) {
            if (onpath[neighbor] || dfs_cycle(graph, neighbor, onpath, visited)) {
                return true;
            }
        }
        return onpath[node] = false;
    }
    
public:
    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
        vector<unordered_set<int>> graph = make_graph(numCourses, prerequisites);
        vector<bool> onpath(numCourses, false), visited(numCourses, false);
        for (int i = 0; i < numCourses; i++) {
            if (!visited[i] && dfs_cycle(graph, i, onpath, visited)) {
                return false;
            }
        }
        return true;
    }
};

Solution 2:

Data structure:
steps:
Complexity:
Runtime:
Space:
Code:


Submission errors:

 

Things to learn:

188. Best Time to Buy and Sell Stock IV

Difficulty: Hard

Frequency: N/A

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most k transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).


Test Cases:


Solution 1:

Data structure:
Steps:
Complexity:
Runtime:
Space:
Code:
class Solution {
public:
    int maxProfit(int k, vector<int>& prices) {
        int n = prices.size();
        if (k >= n / 2) return helper(prices);
        vector<vector<int>> dp(k + 1, vector<int>(n, 0));
        for (int i = 1; i <= k; i++) {
            int tmpMax = -prices[0];
            for (int j = 1; j < n; j++) {
                dp[i][j] = max(dp[i][j - 1], tmpMax + prices[j]);
                tmpMax = max(tmpMax, dp[i - 1][j - 1] - prices[j]);
            }
        }
        return dp[k][n - 1];
    }
    int helper(vector<int>& prices) {
        int n = prices.size(), result = 0;
        for (int i = 1; i < n; i++) {
            if (prices[i] > prices[i - 1]) {
                result += prices[i] - prices[i - 1];
            }
        }
        return result;
    }
};

Solution 2:

Data structure:
steps:
Complexity:
Runtime:
Space:
Code:


Submission errors:

 

Things to learn: