Coder Social home page Coder Social logo

leetcode's Introduction

Catalogue

🔍 good algorithm
✏️ smart code design
🎅: good question
❌: not good designed question

几个单独算法:

  1. Trie
  2. Union Find

Breadth-First Search

Title Time Space Difficulty Algorithm Note
102. Binary Tree Level Order Traversal O(n) O(n) Medium
                                                                

Array

Title Time Space Difficulty Algorithm Note
015. 3 Sum O(n^2) O(1) Medium 🔍问题关键是sort + skip duplicate
016. 3 Sum Closest O(n^2) O(1) Medium 🔍sort + two pointer,根据three sum 和sorted list移动两个pointers
018. 4 Sum O(n^3) O(1) Medium 🔍sort + two pointer,思路和015. 3 Sum 一样
026. Remove Duplicates from Sorted Array O(n) O(1) Easy Two pointer
027. Remove Element O(n) O(1) Easy Two pointer
031. Next Permutation O(n) O(1) Medium 556. Next Greater Element III 思路类似, C++可以用is_sorted_until + upper_bound()
041. First Missing Positive O(n) O(1) Hard 🔍先置换, 把每个元素放在合适位置,再看A[i] == i+1 ? 不等于 return i+1, 最后如果还没return, return size +1
048. Rotate Image O(n^2) O(1) Medium 🔍
  • 上下左右四个区域,每个区域相互置换
  • 先以左下到右上对角线置换,然后上下换
054. Spiral Matrix O(m*n) O(1) Medium 🔍定义 up, down, left, right 四个边界,每次loop 在最外围的一圈
059. Spiral Matrix II O(n^2) O(1) Medium 🔍思路跟048. Rotate Image054. Spiral Matrix 类似
066. Plus One O(n) O(1) Easy
073. Set Matrix Zeroes O(m*n) O(1) Medium 🔍two pass:1. 把如果matrix[i][j] == 0, 把matrix[i][0] 和matrix[0][j] 设为0, 如果第一列设0之前,有数为0,设col0 = 0。 2.从下往上loop, 碰到matrix[i][0]] or matrix[0][j] 为0, matrix[i][j] = 0, if col0 == 0, matrix[i][0] = 0
080. Remove Duplicates from Sorted Array II O(n) O(1) Medium
118. Pascal's Triangle O(n^2) O(1) Easy
119. Pascal's Triangle II O(n^2) O(1) Easy Easy DP
121. Best Time to Buy and Sell Stock O(n) O(1) Easy
128. Longest Consecutive Sequence O(n) O(n) Hard 🔍
  • 先把所有数放进hash set 然后每次pop一个数n,设lower = n-1, upper = n+1, 持续pop lower--, upper++,直到lower,upper不在set里, 结果是max(res, upper-lower-1)
  • Onepass: 用hashmap记录以现在点作为边界点最大连续长,一边loop一边update不同左右边界值
169. Majority Element O(n) O(1) Easy
189. Rotate Array O(n) O(1) Easy
209. Minimum Size Subarray Sum O(n) O(1) Medium 🔍
  • sliding window: 到sum >= s, 移动左面, 不断减小window且sum>=s, 寻找最小 r-l+1
  • binary search: l = 1, r= size, while l<=r,检查mid作为窗口size是否满足>=s
  • binary search: 建一个新的vector, newsum[i] 表示nums[0:i]的sum, 从新的newsum的每个点作为起点找最小满足s的窗口
215. Kth Largest Element in an Array O(n) ~ O(n^2) O(1) Medium 🔍
  • quick selection(nth_element)
  • heap: priority queue / multiset
228. Summary Ranges O(n) O(1) Medium
229. Majority Element II O(n) O(1) Medium 🔍Boyer-Moore Majority Vote algorithm
238. Product of Array Except Self O(n) O(1) Medium 🔍res[i]表示 nums[0: i-1]的乘积,right 记录从结尾到nums[i+1: end]的乘积. 最后res[i] = res[i] * right; 也可以用left, right One Pass
240. Search a 2D Matrix II O(n+m) O(1) Medium 🔍sorted matrix题目的关键是从第一行最后一个开始,如果当前数比想要的大, --col, 如果当前数比想要的小,++row
289. Game of Life O(m * n) O(1) Medium 🔍跟238. Product of Array Except Self有一点点类似,先变化matrix到想要的格式, 然后再做transform到结果: 把下一代活的
334. Increasing Triplet Subsequence O(n) O(1) Medium 🔍用两个数表示b, c, c表示当前最小, b表示当前第二小, 当i都大于这两个数,return true, 不用担心i只更新更新c, 因为答案必须要迈过b
384. Shuffle an Array O(n) O(n) Medium C++ srand(time(NULL)); rand(); uniform_int_distribution
396. Rotate Function O(n) O(1) Medium 🔍mathematical induction F(k) = F(k-1) + sum - nBk[-k]
412. Fizz Buzz O(n) O(1) Easy
414. Third Maximum Number O(n) O(1) Easy
419. Battleships in a Board O(n*m) O(1) Medium 🔍看源头,if [i][j] = 'X' 且 [i-1][j] 和 [i][j-1] 如果都不是X,count += 1
442. Find All Duplicates in an Array O(n) O(1) Medium
  • 把nums[i]-1作为Index, 把nums[index] 变成负数,如果即将变得已经是负数,代表重复
  • 把nums[i]-1作为Index,把nums[i] 通过swap到nums[index]上, 第二次pass, 如果nums[i]!=i+1, 表示重复的
448. Find All Numbers Disappeared in an Array O(n) O(1) Medium 思路与442. Find All Duplicates in an Array一模一样,两种方法也一样
565. Array Nesting O(n) O(1) Medium DFS, 把visit的点变为-1, nest array是循环,所以起点无论是哪个点进入都可以得到完整的循环, 比如 a->b->c->d->a 不会有 a->b->c->d->b
566. Reshape the Matrix O(m*n) O(1) Easy
581. Shortest Unsorted Continuous Subarray O(n) O(1) Easy 🔍
  • 从左起, 最后一个小于左侧最大的数为 right,从右起,最后一个大于右侧最小的数为left, res = right - left + 1
  • two pointer, 当有数小于current max, 往回开始找起点start, start只能减小, end只能增加, res = end - start + 1
605. Can Place Flowers O(n) O(1) Easy
643. Maximum Average Subarray I O(n) O(1) Easy 最简单的sliding window
661. Image Smoother O(n) O(1) Easy 289. Game of Life思路一样, 一点不一样的是把下一代的数右移8个bit, 之后再第二次pass matrix, 每个点>>8 左移8个bits
665. Non-decreasing Array O(n) O(1) Easy 🔍两种operation: 1.nums[i-1] = nums[i] (降), nums[i] = nums[i-1] (升), 降优于升
667. Beautiful Arrangement II O(n) O(1) Meidum 🔍brainstorm
670. Maximum Swap O(n) O(1) Medium 🔍
  • Two Pass: 第一个pass 记录每个digit最后出现位置, 第二个pass: 如果有大于当前digit出现, swap & return
  • One Pass: 从后往前, 记录最大数的index,如果当前数小于最大数,更新进行swap的两个index,最后
674. Longest Continuous Increasing Subsequence O(n) O(1) Easy
697. Degree of an Array O(n) O(n) Easy
713. Subarray Product Less Than K O(n) O(1) Medium 🔍😍 Sliding Window
845. Longest Mountain in Array O(n) O(1) Medium 🐸
918. Maximum Sum Circular Subarray O(n) O(1) Medium 🎅🎅 Kadane's algorithm
997. Find the Town Judge O(n+t) O(n) Easy 🎅 In-degree, out-degree
1375. Bulb Switcher III O(n) O(1) Medium
1380. Lucky Numbers in a Matrix O(m*n) O(m+n) Easy zip(*m)获得column in list, set intersection
1389. Create Target Array in the Given Order O(n^2) O(1) Easy  ❌
1394. Find Lucky Integer in an Array O(n) O(n) Easy  :pencil2: Loop C++ Map Key Value
                                                                

Greedy

Title Time Space Difficulty Algorithm Note
011. Container With Most Water O(n) O(1) Medium
042. Trapping Rain Water O(n) O(1) Hard Greedy/Descending Stack
045. Jump Game II O(n) O(1) Hard 🎅
055. Jump Game O(n) O(1) Medium
122. Best Time to Buy and Sell Stock II O(n) O(1) Medium
134. Gas Station O(n) O(1) Medium 🎅
135. Candy O(n) O(n) O(1) Hard 🎅
316. Remove Duplicate Letters O(n) O(k) Hard 🎅🎅🎅 Tricky
321. Create Maximum Number O((m+n)^3) O(k) Hard 🎅🎅Try all and compare(Not a good question)
330. Patching Array O(s + logn) O(1) Hard 🎅🎅🎅Hint
376.Wiggle Subsequence O(n) O(1) Medium 🎅
392. Is Subsequence O(n) O(1) Easy ❌:pencil2: two pointer or C++ iterator; follow-up可以用binary search; iter
397. Integer Replacement O(log(n)) O(1) Medium Math
402. Remove K Digits O(n) O(n) Medium 🎅 ascending stack(string 可以做stack)
435. Non-overlapping Intervals O(nlogn) O(1) Medium Sort 类似的题
452. Minimum Number of Arrows to Burst Balloons O(nlogn) O(1) Medium Sort 类似的题 Python 可以用 iter
455. Assign Cookies O(nlogn) O(1) Easy
621. Task Scheduler O(n) O(1) Medium 🎅
630. Course Schedule III O(nlogn) O(k) Hard 🎅 类似的题
646. Maximum Length of Pair Chain O(nlogn) O(1) Medium 类似的题
649. Dota2 Senate O(n) O(n) Medium Queue
659. Split Array into Consecutive Subsequences O(n) O(n) Medium 🎅
738. Monotone Increasing Digits O(1) O(1) Medium
757. Set Intersection Size At Least Two O(nlogn) O(1) Hard 🎅🎅 边界选最大的两个,而不是一大一小
763. Partition Labels O(n) O(n) Medium hashmap/sliding windows
767. Reorganize String O(n) O(1) Medium priority_queue
798. Smallest Rotation with Highest Score O(n) O(1) Hard 🎅🎅🎅
843. Guess the Word O(n^2) O(n) Hard
861. Score After Flipping Matrix O(m * n) O(1) Medium
870. Advantage Shuffle O(nlogn) O(n) Medium 💜🎅 sort \ maxheap \ minheap
881. Boats to Save People O(nlogn) O(n) Medium two pointer
936. Stamping The Sequence O((n - m) * m)) O((n - m) * m)) Hard 🎅🎅🎅, 还可以用DFS
948. Bag of Tokens O(nlogn) O(1) Medium Bad Problem Description. Rewrite Version
962. Maximum Width Ramp O(n) O(n) Medium 💜🎅🎅
968. Binary Tree Cameras O(n) O(h) Hard 🎅
984. String Without AAA or BBB O(a+b) O(1) Medium
995. Minimum Number of K Consecutive Bit Flips O(n) O(1) Hard 💜🎅
1249. Minimum Remove to Make Valid Parentheses O(n) O(1) Medium Stack
1386. Cinema Seat Allocation O(n) O(n) Medium
1419 Minimum Number of Frogs Croaking O(n) O(1) Medium 需保证 counter 递增 c>r>o>a>k
                                                                

Tree

//Inorder Traversal
//stack, 
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int>res;
        stack<TreeNode*>stk;
        while(root || !stk.empty()){
            if(root){
               // res.push_back(cur->val);  //Preorder
                stk.push(root);
                root = root->left;
            }else{
                root = stk.top(); stk.pop();
               // res.push_back(root->val); //Inorder
                root = root->right;
            }
        }
        return res;
    }
};

//Postorder
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        stack<TreeNode*> stk;
        vector<int>res;
        TreeNode* cur = root;
        while(cur ||!stk.empty()){
            if(cur){
                res.push_back(cur->val);
                stk.push(cur);
                cur = cur->right;
            }else{
                cur = stk.top(); stk.pop();
                cur = cur->left;
            }
        }
        
        reverse(res.begin(), res.end());
        return res;
    }
};

//Morris: 流程图见,  094. Binary Tree Inorder Traversal.cpp
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int>res;
        TreeNode* cur = root;
        while(cur){
            if(!cur->left)
            {
                //res.push_back(cur->val); //Inorder, preorder
                cur = cur->right;
            }else{
                TreeNode* pre = cur->left;
                while(pre->right && pre->right!=cur)
                    pre = pre->right;
                if(pre->right){
                    //res.push_back(cur->val); //Inorder
                    pre->right = NULL; 
                    cur = cur->right;
                }
                else{
                    //res.push_back(cur->val); //Pre-order
                    pre->right = cur;
                    cur = cur->left;
                }
            }
        }
        return res;
    }
};


//PostOrder
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int>res;
        TreeNode* cur = root;
        while(cur){
            if(!cur->right){
                res.push_back(cur->val);
                cur = cur->left;
            }else{
                TreeNode* pre = cur->right;
                while(pre->left && pre->left != cur)
                    pre = pre->left;
                if(pre->left){
                    pre->left = NULL;
                    cur = cur->left;
                }else{
                    res.push_back(cur->val);
                    pre->left = cur;
                    cur = cur->right;
                }
            }
        }
        reverse(res.begin(), res.end());
        return res;
    }
};


//如果有right child, 经过root 两次 
//112. Path Sum  https://leetcode.com/problems/path-sum/
class Solution {
public:
    bool hasPathSum(TreeNode* root, int sum) {
        stack<TreeNode*>stk;
        TreeNode* cur = root, *pre = nullptr;
        while(cur || !stk.empty()){
            if(cur){
                stk.push(cur);
                sum -= cur->val;
                cur = cur->left;       
            }else{
                cur = stk.top();
                if(!cur->right && !cur->left && sum == 0)
                     return true;
                
                if(cur->right && cur->right != pre){
                    cur = cur->right;
                }
                else{
                    pre = cur;
                    sum += cur->val;
                    cur = nullptr;
                    stk.pop();
                }
            }
        }
        return false;
    }
};


//In order traversal, 不同于之前的iterative 解, 这是每个node 都先被push 进stack, 只有return back时候才pop
/*
详见  236. Lowest Common Ancestor of a Binary Tree
https://github.com/beckswu/Leetcode/blob/master/DFS/236.%20Lowest%20Common%20Ancestor%20of%20a%20Binary%20Tree.cpp#L32,
     1
    /
    2 
     \
      3  

最上面的inorder 的 stack 到3时候是  [1,3 
        下面解的stack 是 到3是   [1,2,3]

*/

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        //iterative, path comparing
        if(!root ) return root;
        vector<TreeNode*> path;
        if(root)
            path.push_back(root); //temp是stack,元素是从root到现在node上的路径
        TreeNode *prev = nullptr;
        while(!path.empty()){
            root=temp.back();
            if(!root->left && !root->right || !root->right && prev==root->left || root->right && prev==root->right){
                path.pop_back();
                prev=root;
            }
            else{
                if(!root->left || prev==root->left) path.push_back(root->right);
                else path.push_back(root->left);
            }
        }
    }
};


TreeNode* helper(TreeNode** head ){
        int val = *head; //获取值, 比如值是5,
        TreeNode** cur = head; //
        head = &((*head)->left); //不会影响之前cur的值, 把head assign 一个新object, 之前绑定head的地址(cur)的object 并没有删除 
        *head = (*head)->left; //会影响cur的值, *head 取地址, 改变head这个地址绑定的值, 因为cur 和head地址一样 , 所以cur的值也改变
        return cur;
    }

//比如: 
 void helper(int *p){
     int *newp = p;
     *p = 5; //会影响newp的值, 因为newp 和 p地址一样,更改的p的值, newp自动会更改
     p = new int(10); // 不会更改newp 的值, 因为p的地址被换掉了, 之前绑定p的地址并没有删除
 }
Title Time Space Difficulty Algorithm Note
094. Binary Tree Inorder Traversal O(n) O(1) Medium 😍🔍Morris Traversal, 现在点连在 left-child 最右侧的node 右侧, 因为最右侧的node 最后visit
099 Recover Binary Search Tree O(n) O(1) Hard 🔍😚 调换node 之间第一个最错误的(也是最大的prev),和最后一个错误(也是最小的cur),💡顺序一定是inorder,由小到大
144. Binary Tree Preorder Traversal O(n) O(1) Medium Morris Traversal,注意preorder 与inorder push 进vector的顺序的区别
145. Binary Tree Postorder Traversal O(n) O(1) Hard = 先right 再left 的 inorder traversal 🔍Morris Traversal
208. Implement Trie (Prefix Tree) O(n) O(1) Medium Trie
211. Add and Search Word - Data structure design O(min(n, h)) O(min(n, h)) Medium Trie + DFS
226. Invert Binary Tree O(n) O(h), O(w)) Easy 👽 不可以 left = invert(right); right = invert(left);, 因为left 在invert right时候改变
297. Serialize and Deserialize Binary Tree O(n) O(h) Hard ✏️ostringstream & istringstream 用法, BFS-> pointer of pointer 存pointer 地址
307. Range Sum Query - Mutable O(n), O(logn) O(n) Medium ✏️ BIT & Segment Tree; BIT tree 需要arr作为参照物,每次根据val-arr[i]的update, update过后arr[i] = val
525. Contiguous Array O(n) O(n) Medium 😍把所有的0变成-1, 所以当有sum[i,j] = 0时 => [i,j]中有同等的1 和 0, same as 325. Maximum Size Subarray Sum Equals k
529. Minesweeper O(m * n) O(m + n) Medium ❌ 简单DFS
538. Convert BST to Greater Tree O(n) O(h) Easy 😍注意Python BFS
543. Diameter of Binary Tree O(n) O(h) Easy 🔍先尽可能dfs,再比较height 会更快
563. Binary Tree Tilt O(n) O(n) Easy ❌思路跟543. Diameter of Binary Tree 一样
572. Subtree of Another Tree O(m * n) O(h) Easy 😍 seralization
606. Construct String from Binary Tree O(n) O(h) Easy ❌ Easy Recursion
617. Merge Two Binary Trees O(n) O(h) Easy 😍
623. Add One Row to Tree O(n) O(h) Medium 😚
637. Average of Levels in Binary Tree O(n) O(h) Easy
652. Find Duplicate Subtrees O(n) O(n) Medium 😍🔍 Seralization(String的memory 是 O(n^2)) / Hash, C++ 有定义hash. 注: 无须seralize 完整后再寻找, analysis
653. Two Sum IV - Input is a BST O(n) O(h) Easy 😍🔍可以考怎么写 BST Iterator
654. Maximum Binary Tree O(n) O(h) Medium 😍🔍💡 descending stack:
  • 如果现在数 num[i] 小于stack top,stack.top->right = new TreeNode(nums[i])
  • 如果现在num[i] 大于stack top,就不断pop stack 找最后一个小于nums[i]的node,把最后的node 作为nums[i]的left child
655. Print Binary Tree O(n) O(h) Medium Math找规律
662. Maximum Width of Binary Tree O(n) O(h) Medium ❌ Math 找规律, 逻辑跟655. Print Binary Tree类似
677. Map Sum Pairs O(n) O(t) Medium ❌Simple Trie
684. Redundant Connection O(n) O(n) Medium 🔍Union Find 如果两个node 连接之前发现parent 已经一样,表示之前两个nodes已经连接,如果再连接edge,会构成cycle
685. Redundant Connection II O(n) O(n) Hard Union Find 注意构成tree 的条件, 不能有一个child 连上两个parent, 然后去掉这个child一个链,保证都是一个child对应一个parent, 再看有没有cycle, 没有cycle表示去链去成功了, 有cycle 表示去链去错了
687. Longest Univalue Path O(n) O(h) Easy 😍 Really good Recussive Question!
699. Falling Squares O(nlogn) O(n) Hard 😍Good Question! 若想找点属于 哪个范围之中 比如 3∈ (1,5) or (7,9) , 用map + binary search
  • solution 1: 解法与 218. The Skyline Problem相似, 画轮廓
  • Solution 2: Segment Tree using lazy initialization: 需要注意update即使不在范围内,也要返回root.val, update还要更新root.val为max值
814. Binary Tree Pruning O(n) O(h) Medium 😍Really good question!
850. Rectangle Area II O(nlogn) O(h) Hard 🔍💡跟699. Falling Squares思路有点像, 根据height一层一层的算当层长方体面积,算完面积后更新上一层的底curx
863. All Nodes Distance K in Binary Tree O(n) O(h) Medium 😍😍Really good question! 不必纠结于one pass, 需要child -> parent map
865. Smallest Subtree with all the Deepest Nodes O(n) O(h) Medium 🔍 若left, right child 都是最深的, 则root为 最深的node
889. Construct Binary Tree from Preorder and Postorder Traversal O(n) O(h) Medium 😍😍
  • Solution 1: 难点是找到 left 和right的边界: 假定都把下一个assign 给left
  • 用stack
1008. Construct Binary Search Tree from Preorder Traversal O(n) O(h) Medium 🎅Stack, Recursion, Morris Traversal
1028. Recover a Tree From Preorder Traversal O(n) O(h) Hard 😚 stack / DFS, stack逻辑类似889. Construct Binary Tree from Preorder and Postorder Traversal
1409. Queries on a Permutation With Key O(nlogn) O(n) Medium BIT, Fenwick Tree, 🎅 How to Build FenwickTree
                                                                

Math

Title Time Space Difficulty Algorithm Note
007. Reverse Integer O(1) O(1) Easy
009. Palindrome Number O(1) O(1) Easy
012. Integer to Roman O(n) O(1) Medium
013. Roman to Integer O(n) O(1) Easy
964. Least Operators to Express Number O(logn) O(logn) Hard 🎅🎅🎅
1360. Number of Days Between Two Dates O(1) O(1) Easy
1362. Closest Divisors O(sqrt(n)) O(1) Medium
1363. Largest Multiple of Three O(n) O(1) Hard
1390. Four Divisors _O(n * sqrt(n)) _ O(1) Medium

String

Title Time Space Difficulty Algorithm Note
005.Longest Palindromic Substring O(n) O(n) Medium 🔍 manacher(马拉车算法), mx表示当前最长回文外右侧第一点, id是当前回文中心, p[i]表示当前最长回文, if i<mx, p[i] = min(p[2id-i], p[i])
006. ZigZag Conversion O(n) O(n) Medium
  • 把string 循环push到一个长度为nrow的vector当中
  • 用step = 2*nrows - 2 控制每次jump step, 到中间行看是否jump step之间有夹的元素
008. String to Integer (atoi) O(n) O(1) Easy C++可以用find_first_not_of
014. Longest Common Prefix O(n) O(1) Easy loop所有数第0位到第i位,直到不相同,返回str[0].substr(0,i)
028. Implement strStr() O(n+k) O(k) Easy kmp algorithm: prefix array[i]表示i点的最长的prefix 也是suffix长度 比如"ABA", 第三个a的最长的prefix 也是suffix 的长度是1 A 而prefix array[i], 作为index, 是当前最长prefix 也是suffix 的下一位
038. Count and Say O(n * 2^n) O(n2^n) Easy C++ find_if + bind1st
043. Multiply Strings O(m*n) O(m+n) Medium C++ transform, 必须都从个位数(也就是string的最后一位开始算, 否则carry可能会超过10), back_inserter, 相当于按照原来从头到尾顺序push back
058. Length of Last Word O(n) O(1) Easy C++ find if or find if + bind1st or string find_last_not_of + find_last_of
067. Add Binary O(n) O(1) Easy string 加法, 跟415. Add Strings306. Addictive Number 类似
068. Text Justification O(n) O(1) Hard not a hard question, 跟725. Split Linked List in Parts 类似
125. Valid Palindrome O(n) O(1) Easy C++ 跳过非isalnum的
151. Reverse Words in a String O(n) O(1) Medium 先reverse所有的, 再reverse单个每个词, 记录总共len,最后用来截取, C++ find_first_not_of + find_first_of
165. Compare Version Numbers O(n) O(1) Medium c++ 算当前version1,2的substr的数,如果其中一个碰到结尾,设当前数位0。 c, 可以用c_str() + strtol; python3 zip(*itertools.zip_longest(*splits, fillvalue=0))
214. Shortest Palindrome O(n) O(n) Hard 🔍可以把此题换一种问法: 以index0开始最长的部分palindrome 的长度, 部分最长的pal后面的掉个+s = 答案
  • KMP: s+"#"+reverse(s), prefix array最后一位是部分最长的pal的长度, kmp prefix 即是suffix,pal是掉个也相等, 所以最后一位是部分最长
  • 马拉车(manacher): 不断找最大的回文长,但一边更新右边界时, 只更新mxlen 当p[i]==i的时候, 最长回文从0开始
242. Valid Anagram O(n) O(1) Easy 经典面试题
273. Integer to English Words O(1) O(1) Hard 无聊的recursion
306. Addictive Number O(n^3) O(n) Medium recursion 从index0开始试所有的digit可能性直到成功, 比如开始是一位+两位, 还是三位+两位 , 需要一个string add的help function; python 可以用itertools.combination + startswith, 跟067. Add Binary 415. Add Strings 类似, 只不过多个recursion
383. Ransom Note O(n) O(n) Easy Hash map
405. Convert a Number to Hexadecimal O(n) O(1) Easy 最后结果需要reverse,因为先插入最小的,注意负数的, -1>>4 = -1, 所以while加个条件 res.length()!=sizeof(int)*2
415. Add Strings O(n) O(1) Easy string加法,跟067. Add Binary 306. Addictive Number 类似
420. Strong Password Checker O(n) O(1) Hard Brain Storm 详见C++ code 解释
434. Number of Segments in a String O(n) O(1) Easy 🔍, 根据s[i] 和 s[i-1]判断, or s[i] 和 s[i+1]判断
443. String Compression O(n) O(1) Easy two pointer + num reverse
459. Repeated Substring Pattern O(n) O(n) Easy KMP
468. Validate IP Address O(1) O(1) Medium 注意IPv4 和IPv6的定义(c++ code里), 判断一个char是不是符合十六进制用isxdigit(c)
520. Detect Capital O(1) O(1) Easy C++ count_if; Python istitle()看是不是只有首字母大写
521. Longest Uncommon Subsequence I O(min(a, b)) O(1) Easy 题出的神经病,逗你玩儿
522. Longest Uncommon Subsequence II _O(l * n^2) _ O(1) Medium 🔍按照字母长度sort, 然后一个一个看str,有没有在list中有subsequence,没有的话, return 这个str长度,直到全部search完, return -1 or C++ equal_range + count_if , python 可以iter()
524. Longest Word in Dictionary through Deleting O((d * l) * logd) O(1) Medium 按照字母长度sort,如果长度一样,按照alphabet sort, 找到第一个符合的 🔍python, max with key, min with key, filter, iter + next with default
539. Minimum Time Difference O(nlogn) O(n) Medium C++ transform 把所有时间变分钟, 然后按minute sort, 答案就出自所有minute[i+1] - minute[i] or 1440 +minute[0] - minute.back()
541. Reverse String II O(n) O(1) Easy
551. Student Attendance Record I O(n) O(1) Easy
556. Next Greater Element III O(1) O(1) Medium 可以用ascending stack or 两个for loop, 寻找i点往后最后一个比i点大的数(也是比i大,最接近i的数)(index j), swap(s[i], s[j]), 这样s[i]后面的数又大到小排序的, 把i往后的数到end全部reverse后变成Int, 就是答案, 跟031. Next Permutation思路类似
564. Find the Closest Palindrome O(l) O(l) Hard Brain Storm: 最接近的pal只可能5中选一, 100..001(l.size()+1), 99..99(l.size()-1), or string的前半部分 +1, +0, -1 加上前半部分的reverse(如果起始长度是奇数,reverse不包括前半部分最后一个,如果长度是偶数,都包括在内)
591. Tag Validator O(n) O(n) Hard cdata 必须以 已 ]]>结束, recursion 找是不是valid tag, valid cdata, valid tagname
647. Palindromic Substrings O(n) O(n) Medium 🔍 manacher(马拉车算法), 在snew中 p[i]表示以id为中心最长回文,到i点,res += p[i] /2
648. Replace Words O(n) O(t) Medium 🔍 Trie; python 可以用reduce + dict.__getitem__
657. Judge Route Circle O(n) O(1) Easy
678. Valid Parenthesis String O(n) O(1) Medium 🔍Three Solutions
  • 用low 和high: low 表示把 '*' 当成 ')', high: 表示把 '*' 当成'(', 如果high小于0,表示有太多的')' '(' + '*' = high < ')'
  • 用两个stack 分别记录 '(' 和 '*'的位置, 如果当前是')', 先pop '(' 再pop '*'; 最后看'(' 有没有对应index往后的的 '*'可以pop掉,
  • Two pass solution 从左向右看是不是所有的')' 都有对应的 '(' 和 '*', 再从右向左看是不是所有的 '(', 都有对应的 ')' 和' *'
680. Valid Palindrome II O(n) O(1) Easy 🔍两个pointer, 检查s[i] == s[j]?, 遇到不等时,再看s[i+1, j], or s[i, j-1]是不是pal
686. Repeated String Match O(n+m) O(n) Easy 🔍
  • Kmp: 然后两个pointer, 一个pointer i 记录A的位置,一个pointer j记录B的位置,每次对比 A[(i + j)%A.size()] 是否等于B[j] 等于就++j., 直到 j = b.size() return ceil((i+j)/a.size())
  • rabin-karp algorithm, 寻找最短的长度一直到最大长度的hash
696. Count Binary Substrings O(n) O(1) Easy manacher(马拉车)算法的变形
720. Longest Word in Dictionary O(n) O(t) Easy Trie or 先按长度sort, 长度越短, 排前面, loop word, loop s[i][0,len), 看是不是每个substr都在,都在话insert to hashset & update result
722. Remove Comments O(n) O(k) Medium
791. Custom Sort String O(n) O(k) Medium 可以当经典面试题, 三种解法:
  1. Custom Sort (or STL inserter + make_pair)
  2. Bucket Sort
  3. Priority Queue
796. Rotate String O(n) O(1) Easy 🔍两种kmp的解,
804. Unique Morse Code Words O(n) O(n) Easy Easy one unordered_set
806.Number of Lines To Write String O(n) O(1) Easy Easy one but stupid question description
809. Expressive Words O(n+s) O(1) Medium Two pointer: 如果word[i]!=S[j] 的时候, 看S的j-1, j, j+1是不是连续是三个,若不是,再看过去是不是连续三个,若不是,break
816. Ambiguous Coordinates O(n^3) O(n) Medium 🔍选择小数点的关键是 不能左面位0, 右面结束也是0,比如00.1230不可以,但是即使左面等于0, 右面最后也不可以是0
819. Most Common Word O(n+m) O(m+n) Easy
820. Short Encoding of Words O(n) O(t) Medium
  • Trie: 看叶子有没有child
  • sort string vector, 只用对比s[i] 和 s[i+1]
824. Goat Latin O(n + w^2) O(l) Easy stringstream 作为string output
831. Masking Personal Information O(1) O(1) Easy C++ transform 把所有字母都小写, s[0] 变成string 可以用 s.substr(0,1) or string(1,S[0])
833. Find And Replace in String O(m+n) O(n) Medium 先sort indexes,然后从后往前loop S,这样可以保持S前面的index不变, python 可以用zip + startswith
839. Similar String Groups O(n^2 * l) O(n) Easy 🔍 Union Find Disjoint Set with Rank Heuristic, string 所在位置为index
848. Shifting Letters O(n) O(1) Medium 加的时候及时%26, 小心overflow
859. Buddy Strings O(n) O(1) Easy 判断条件: 1.长度不一样,false,2. 如果a == b,有没有重复的字母,有的话true, 没有false, 3, 如果不一样的位置个数不等于2, 或者a[diff[0]]!=b[diff[1]] or a[diff[1]]!=a[diff[1]] 返回false, 否则是true
1374 Generate a String With Characters That Have Odd Count O(n) O(1) Easy
1392. Longest Happy Prefix O(n) O(n) Hard KMP, Rolling Hash
1408. String Matching in an Array O(n) O(n) Easy KMP, Rolling Hash
1410. HTML Entity Parser O(n) O(t) Medium
1417. Reformat The String O(n) O(1) Easy
                                                         

Regular Expression Summary

summary
  • regex_match 是从头开始到结尾结束都要match的, 可以用string + regex, regex_match(string, regex()); or Iterator + regex: regex_match ( s.begin(), s.end(), regex()), 返回值match是不是成功
  • regex_search 是寻找entire string, 有没有substring满足regex的, 可以用string + regex, regex_search(string, regex()) or Iterator + regex: regex_search ( s.begin(), s.end(), regex())
  • regex_replace 是寻找entire string match pattern的部分,用其他的string代替它, 返回值新生成的string, replace 不会修改原来string s。 regex_replace(s, regex(), "geek"); 或者把替代的生成到另一个新的string: string result; regex_replace(back_inserter(result), s.begin(), s.end(), regex(), "geek");

    • reference reference2
    • +: 前面的子表达式出现一次或多次 ro+b,可以匹配 roob、rob、rooob
    • *: 前面的子表达式出现0次、或1次、或多次ro+b,可以匹配 rb、rob、rooob
    • ?: 前面的子表达式出现0次、或1次 colou?r,可以匹配 color、colour
    • {n} n 是一个非负整数。匹配确定的 n 次。例如,'o{2}' 不能匹配 "Bob" 中的 'o',但是能匹配 "food" 中的两个 o。
    • {n,} n 是一个非负整数。至少匹配n 次。例如,'o{2,}' 不能匹配 "Bob" 中的 'o',但能匹配 "foooood" 中的所有 o。'o{1,}' 等价于 'o+'。'o{0,}' 则等价于 'o*'。
    • {n,m} m 和 n 均为非负整数,其中n <= m。最少匹配 n 次且最多匹配 m 次。例如,"o{1,3}" 将匹配 "fooooood" 中的前三个 o。'o{0,1}' 等价于 'o?'。请注意在逗号和两个数之间不能有空格。
    • | 指明两项之间的一个选择。比如 "A.|B" 匹配 CAA 也匹配 CB
    • . 匹配除换行符 \n 之外的任何单字符。 比如A. 匹配AD
    • ^ 匹配输入字符串的开始位置,除非在方括号表达式中使用,此时它表示不接受该字符集合。比如^A, 表示字符以A开始, 比如^[0-9] 表示不含有数字
    • $ 匹配输入字符串的结尾位置。如果设置了 RegExp 对象的 Multiline 属性,则 $ 也匹配 '\n' 或 '\r'。比如C$ 字符串以C结尾
    • \w 匹配任何word character short version for [A-Za-z0-9_], \W is short for [^\w]。
    • \s stands for "whitespace character" \S is the equivalent of [^\s]
    • \d is short for [0-9],[0-9] is not always equivalent to \d. In python3, [0-9] matches only 0123456789 characters, while \d matches [0-9] and other digit characters, for example Eastern Arabic numerals ٠١٢٣٤٥٦٧٨٩ \D is the same as [^\d]
difference between () [],
  • [] denotes a character class. () denotes a capturing group.
  • [a-z0-9] -- One character that is in the range of a-z OR 0-9, (a-z0-9) -- Explicit capture of a-z0-9. No ranges.
  • a -- Can be captured by [a-z0-9]., a-z0-9 -- Can be captured by (a-z0-9) and then can be referenced in a replacement and/or later in the expression
    • .

Bit Manipulation

Title Time Space Difficulty Algorithm Note
136. Single Number O(n) O(1) Easy 用xor ^, Python Reduce one line
137. Single Number II O(n) O(1) Medium 🔍
  • 第一次出现-> save it in "ones", 第二次出现 -> clear "ones" but save it in "twos" for later check, 第三次出现 -> try to save in "ones" but value saved in "twos" clear it.
  • loop through 32个bit, 每个bit再loop nums, if bit & nums[i] => c++, 如果c不是3个倍数,最终结果在现在这个bit上位1
190. Reverse Bits O(1) O(1) Easy 一位一位reverse bit, res每次向左移动一位,n向右移动一位
191. Number of 1 Bits O(n) O(1) Easy n = n & (n-1);
201. Bitwise AND of Numbers Range O(1) O(1) Medium 一位一位比较digit,直到移动k位m=n, 那么此时的digit是bitwise and的结果, res = m<<k
231. Power of Two O(1) O(1) Easy n = n & (n-1);
260. Single Number III O(n) O(1) Medium 🔍两个pass,第一个pass, 通过Xor需要区分a 和 b的数 c(是a与b右面第一位不一样的数), 第二次pass, 通过c&nums[i]判断做xor, 找到a和b (binary 负数)
268. Missing Number O(n) O(1) Medium Math, Swap, Xor
318. Maximum Product of Word Lengths O(n^2) O(n) Medium 🔍可以用bit来判断两个string是不是有重合的字母, 用数字表示string, a是第一位被set,z是第26位被set,
342. Power of Four O(1) O(1) Easy 4^n = (3+1)^n, 除了判断(n&n-1) , 还要判断n-1 是不是可以整除3
371. Sum of Two Integers O(1) O(1) Easy (a&b)<<1 表示需要相加进位的(两个1相加), a ^ b 表示相加不进位(保留单个1)
389. Find the Difference O(1) O(1) Easy 🔍找两个string唯一不同不同的char可以通过 xor
393. UTF-8 Validation O(n) O(1) Easy 用count判断是不是起点, count==0 是起点
421. Maximum XOR of Two Numbers in an Array O(nlogk) O(n) Medium 🔍
  • 从第32位开始到第0位逐渐缩小范围, 比如第5位有a,b,c,d 四个数xor都是最大的,第四位就可能会缩减到a,c; 利用性质: a ^ b = c => a ^ c = b
  • Trie
461. Hamming Distance O(1) O(1) Easy 判断有多少bit, 与191. Number of 1 Bits231. Power of Two类似
462 Minimum Moves to Equal Array Elements II O(nlogn) O(1) Medium 🔍Meeting point, 先sort,然后逐个用最大减去最小, e.g [3,6,9], 不管中间点在哪,都要磨平9-3=6的差距
476. Number Complement O(1) O(1) Easy
477. Total Hamming Distance O(nlogk) O(1) Easy 由第32位到第0位,loop每个bit,数当前bit位为1的个数为bitcount, 结果 res+= bitcount*(size-countsize), 与421. Maximum XOR of Two Numbers in an Array类似
645. Set Mismatch O(n) O(1) Easy
  • bit Xor:与260. Single Number III 解法一样, 第一次pass,找到两个数的xor = c, c & (-c)是unique的digit, 第二次pass分别找到这两个数,第三次pass调整两个数return的顺序
  • 改变nums[abs(nums[i])-1] 为负数, 如果发现新找到的已经为负数, 证明是重复的,第二次pass, 如果发现某位为正数, 代表是missing的
693. Binary Number with Alternating Bits O(1) O(1) Easy 🔍
762. Prime Number of Set Bits in Binary Representation O(R-L) O(1) Easy loop[L,R],数每个数多少个bit,因为log2(10^6) < 16, 事先把所有的prime存到hash set里面, 看现在bit数是不是质数,if so res++, 还可以用 __builtin_popcountl(n); bitset<32>(n).count()
                         C++ 0b表示binary number,比如0b10 = 2, 0b111 = 7
python 0b表示binary number,比如0b10 = 2, 0b111 = 7
  • 注意运算顺序
  • +, - 先于 &, |, <<, >>; 所以不用括号 n&n-1
  • << >> == 是优于&,| ; 判断&, 需要加括号,比如(n& n-1) == 0;
  • &,|优于 && || ; (1&2 && 2) = 0 && 2 = false;
bit数1的个数,可以用 n&(n-1); __builtin_popcountl(n); bitset<32>(n).count()

Hash Table

Title Time Space Difficulty Algorithm Note
001 Two Sum O(n) O(n) Easy
003. Longest Substring Without Repeating Characters O(n) O(n) Medium
030. Substring with Concatenation of All Words O((m+n)*k) O(n*k) Hard 🔍k = word[0]长度, n = 整个words长度, m = S的长度。最快的解是两个map, map1记录words的每个string,
036. Valid Sudoku O(9*9) O(9) Medium 🔍 用bit比较快,比如i在横着第2行出现, row[2]
049. Group Anagrams O(n * glogg) O(n) Medium 经典 面试题, python list不能作为字典的key,但是tuple可以
076. Minimum Window Substring O(n) O(k) Hard 🔍sliding windows, 此题没有窗口的size,要去找最小的size,关键是如何确定window valid,记录每次滑到cur char也在T中出现的个数,当个数满足T.size(),证明window valid,然后逐步缩小start与i的距离,找最小点
149. Max Points on a Line O(n^2) O(n) Hard 每到一点,算跟别的点的斜率,注意1. 重合的点,2.斜率没有的定义的点, 在每一点都重新建一个hashmap
187. Repeated DNA Sequences O(n) O(n) Medium 🔍 rolling hash (rabin-karp),
  • A = 00, C = 01, G = 10, T = 11, i大于9后 t>>2 & 0xfffff(2^18-1) 做&运算
  • 直接把A,C,G,T默认转化成ASCII,与&7, 后三位是unique的,i>9后做 t << 3 & 0x3FFFFFFF
202. Happy Number O(k) O(k) Easy 要么是happy number,要么转化过程陷入循环
204. Count Primes O(n) O(n) Easy count从小往大后eliminate,注意要尽可能efficient
205. Isomorphic Strings O(n) O(1) Easy 可以记录相同位置字母出现的上一位,或者把s,t字母相互关联起来, python 可以用find+map or zip+set
217. Contains Duplicate O(n) O(n) Easy easy one, 可以用sort + unique
219. Contains Duplicate II O(n) O(n) Easy easy one
290. Word Pattern O(n) O(n) Easy 思路和205. Isomorphic Strings 一样
299. Bulls and Cows O(n) O(1) Easy One pass: 如果guess[i] 和 secret[i]一样, bull++, 不一样,++m[sec[i]], --m[guess[i]] python 可以用两个collectons.Counter相减, 得到重合的set
336. Palindrome Pairs O(n * k^2) O(n*k) Hard 🔍trie
387. First Unique Character in a String O(n) O(n) Easy 需要 two pass
388. Longest Absolute File Path O(n) O(d) Medium map记录每一层现有的长度,到新的或者原来一层,更新map, res是max(map中含有“.”的一层), 用到string::find, string::find_first_not_of, std::find
409. Longest Palindrome O(n) O(1) Easy 可以用std::count, 或者可以来回flip map, 当map位true +2
424. Longest Repeating Character Replacement O(n) O(1) Medium 🔍sliding window: 记录window的初始点, 如果当前长度 - 最大count > k, ++start(保持windows的最大长度), 如果满足,start不变,结果是s.size()-start
438. Find All Anagrams in a String O(n) O(1) Easy sliding window: 跟567. Permutation in String思路一样
  • 保持window的长度不变, 用l算p中还剩几个点没有被数过
  • 用right和left, 当right和left之间长度 == p的长度,append to result
  • 用两个map 分别记录s 和p,如果s==p,append to result
447. Number of Boomerangs O(n^2) O(n) Easy 可以用hypot
454. 4Sum II O(n^2) O(n) Medium 可以把4sum看成two sum, 把A+B的和绑定,把C+D的和绑定,看-C-D是不是在A+B的map里
473. Matchsticks to Square O(n * s * 2^n) O(n * (2^n + s)) Medium DFS or Bit Mask
523. Continuous Subarray Sum O(n) O(k) Medium 🔍求开始数到所有i的和的余数,如果现在这个的余数之前遇到过,表示,两个数之间有数的和正好整除k
532. K-diff Pairs in an Array O(n) O(n) Easy 🔍one pass解: 两个hashset, lookup 和res, 找的时候既向上数又向下数, 为了避免重复, set(res)只push下限,结果就是res size
554. Brick Wall O(n) O(m) Meidum 相当于求最多经过砖头缝缝
560. Subarray Sum Equals K O(n) O(k) Medium 🔍用hashmap记录每点的rolling sum(0,i), 那么只需要找(0,i)的sum - k在不在map中,在的话 表示存在一点[0,j] + k = (0,i)的sum, res += map[sum-k] (可能一个sum出现很多遍)
561. Array Partition I O(n) O(n) Easy Sort or Bucket Sort
575. Distribute Candies O(n) O(n) Easy 对比set的长度和candies.size()/2的长度, C++可以用bitset
594. Longest Harmonious Subsequence O(n) O(n) Easy
599. Minimum Index Sum of Two Lists O((m + n) * l) O(m * l) Easy
609. Find Duplicate File in System O(n * k) O(n * k) Medium
721. Accounts Merge O(nlogn) O(n) Medium 🔍 Union Find, 不能用简单的hash table 找parent, 比如 (1@com, 2@com), (3@com, 4@com), (4@com, 2@com), 不用Union find分成两组
748. Shortest Completing Word O(n) O(1) Medium
771. Jewels and Stones O(n+m) O(n) Easy
811. Subdomain Visit Count O(n) O(n) Easy
822. Card Flipping Game O(n) O(n) Medium 先把front[i]和end[i] 一样的插入到hash set, 再loop front & end, 选取不在hash set中最小的
825. Friends Of Appropriate Ages O(n+k^2) O(k) Medium 用hash map存age和count, loop两层hashmap, 判断内层和外层key是否满足条件, 满足的话更新结果
1418 Display Table of Food Orders in a Restaurant O(n + tlogt + flogf) O(n) Medium ✏️C++ transform
                                                                                                                                                           

sliding windows Summary

summary
sliding windows: windows都是看以当前字母结尾的window. 比较对象s1, 被比较对象s2
  • 可以记录当前substring的开始位置,
  • 用数字记录substring的长度
  • 用hashset和两个pointer记录当前windows的长度
  • map+pointer 1 map + 2 pointers: map先记录比较对象 map[s1[i]]++, 再对被比较对象 所有字母 / key出现 , map[s2[i]]--
    • 固定windows 长度
      • 一个pointer count(初始值为 count=len), 它的值会变动, 表示固定windows 内多少个满足条件
      • 一个pointer len(不变化)表示s1长度,用来移动窗口,
      • 比较条件: if --map[s2[i]] >= 0 , --count, 当count == 0 i-len + 1 是windows起点
      • 移动窗口条件:if i>=len-1, map[s2[i-len+1]]++
    • 不固定长度.
      • 一个pointerleft(变化) , 记录左侧windows 起始点
      • 一个pointer len 记录s1长度(不变化)
      • 比较条件: if i - left == len - 1 , left表示windows 起点
      • 移动窗口条件: if(map[s2[i]])<0 表示现windows中 s2[i] 个数 大于 s1中个数, or s1中没有 s2[i], 下面两种移动方式都可以
        • 方式一: while(left <= i && map[s2[i]]< 0) map[s2[left++]]++。e.g.1 s1=abc, s2=ababc, 在index=2, 第二个a, 有两个a 多于s1中个数, e.g. 2 s1=abc, s2=abdabc, 在index=2, d在s1中没有出现 )
        • 方式二: while(map[s2[start++]-'a']++ >= 0); 把之前所有满足的都移走,
    • 可以用两个map,一个map记录比较对象(T),一个记录被比较对象(S), 还需要一个count记录S中T出现的个数, start记录windows起始点, 初始化count = len(T);
      只有当sdict[s[i]] < tdict[s[i]], count--; 当count == 0, 满足情况,append to res;
      移动窗口过程中,dict[s[start]]--, start++,只有当sdict[s[start]] < tdict[s[start]]时 ++count,
      比如30题 Substring with Concatenation of All Words, 76题 Minimum Window Substring
      两个题区别是30不能包括多余的string (不可以sdict[s[start]] > tdict[s[start]]), 76是允许的
// 438. Find All Anagrams in a String
//s2: "cbaebabacd"  s1: "abc"
//Output: 0, 6]

//固定windows长度
class Solution {
public:
    vector<int> findAnagrams(string s2, string s1) {
        vector<int>map(26,0);
        for(auto i: s1)
            map[i-'a']++;
        int len = s1.size(), count = s1.size();
        vector<int>res;
        for(int i = 0; i<s2.size();i++){
            if(map[s2[i]-'a']-->0) count--;
            if(count == 0) res.push_back(i-len+1);
            if(i>=len-1){
                if(++map[s2[i-len+1]-'a'] > 0) count++;
            }
        }
        return res;
    }
};

//不固定windows长度, 方法一:

class Solution {
public:
    vector<int> findAnagrams(string s2, string s1) {
        vector<int>map(26,0);
        for(auto i: s1)
            map[i-'a']++;
        int len = s1.size(), left = 0;
        vector<int>res;
        for(int i = 0; i<s2.size();i++){
            map[s2[i]-'a']--;
            if(map[s2[i] - 'a'] <0)
                while(left<= i && map[s2[i]-'a'] < 0) map[s2[left++]-'a']++;
                /* or

                //correct
                while( mp[s2[left]]++ >= 0 )
                    ++left;
                ++left;

                //wrong: 比如 ab: eabc,  left  会一直停在0(e)
                while( mp[s2[left]] >= 0 )
                    mp[s2[left++]]++

                */

            if(i-left+1 == len){
                res.push_back(left);
            }
        }
        return res;
    }
};

//不固定windows长度 方法二:

class Solution {
public:
    vector<int> findAnagrams(string s2, string s1) {
        vector<int>map(26,0);
        for(auto i: s1)
            map[i-'a']++;
        int len = s1.size(), left = 0;
        vector<int>res;
        for(int i = 0; i<s2.size();i++){
            map[s2[i]-'a']--;
            if(map[s2[i] - 'a'] <0)
                while(map[s2[left++]-'a']++ >= 0);
            //cout<<i <<" left "<<left<<endl;
            if(i-left+1 == len){
                res.push_back(left);
            }
        }
        return res;
    }
};
/*
"cbaebabacd"
"abc"
DEBUG stdout
0 left 0
1 left 0
2 left 0
3 left 4
4 left 4
5 left 4
6 left 5
7 left 6
8 left 6
9 left 10
*/
Title Time Space Difficulty Algorithm Note
567. Permutation in String O(n) O(1) Medium 😍sliding Window(长度为len(s1)), 每次移动框,vector减去新来的,加上刚刚pass的,直到l长度为0
                                                 

Stack

Title Time Space Difficulty Algorithm Note
020. Valid Parentheses O(n) O(n) Easy ❌注意return true if stack is empty
032. Longest Valid Parentheses O(1) O(n) Hard 😍
  • DP: dp[i] 代表以current index结束的最大valid substring的长
  • Stack: push的是最近'('的index 和substring的起点 关键点是先pop 再比较
071. Simplify Path O(n) O(n) Medium ✏️ getline可以当做stack, 遇到".." stack pop; vector可以用作stack
084. Largest Rectangle in Histogram O(n) O(n) Hard 😍
  • stack: ascending stack, 难点: 找到left start
  • Divide Conquer:最小的area来自左面,或者来自右面,或者来自area contain middle point
085. Maximal Rectangle O(n*m) O(m) Hard 🔍
  • stack:与084. 类似, matrix有n行,问题可以转换成n个Histogram的问题
  • 😍😍__DP__ : height代表从上到下,有几个连续的1, left: 现在这个height,左侧边界位置, right:这个height,长方形的右侧边界(右侧边界不包括在长方形内,是长方形右外侧第一个点)
101. Symmetric Tree O(n) O(h) Easy ❌ 注: iterative stack push 顺序
150. Evaluate Reverse Polish Notation O(n) O(n) Medium ✏️ Python Lambda Function in dictionary 🔍 C++ recursive solution
155. Min Stack O(n) O(1) Easy 😚 Descending Stack: 两个stack,一个用来放正常的顺序,另一个作为min
173. Binary Search Tree Iterator O(1) O(h) Medium 307. Range Sum Query - Mutable 逻辑类似, 不要先全部走完
232. Implement Queue using Stacks O(1), amortized O(n) Easy 🔍两个stack in & out, in用来push, top: 假如out为空,dump in to out
224. Basic Calculator O(n) O(n) Hard ❌用sign=1记录+, -1记录减, 碰到num乘以res,'('res,sign push进stack, ')'先乘以stack的top(是sign),再加上stack的top(sign之前的res)
227. Basic Calculator II O(n) O(n) Medium ❌ 用sign=1记录+, -1记录减, sign = 2 记录*, 3记录除, 上一个sign是乘或除,先进行operation
331. Verify Preorder Serialization of a Binary Tree O(n) O(n) Medium 😍😍✏️stringstream + getline
  • Stack: 每个node outdegree = 2,in-degree = 1
  • indegree(到parent的) = outdegree(到child的) not NULL node has outdegree
341. Flatten Nested List Iterator O(n) O(h) Medium 😍😍stack + recursion从最后往前loop, queue从前往后loop, ✏️✏️C++/Python Iterator, 要存iterator, 不能存vector, 因为存vector memory会很大
385. Mini Parser O(n) O(h) Medium 遇到',' ']' 把之前的integer add, 比如[-1], [123,456], 遇到']',把现在这个nested list加入上个nested list
394. Decode String O(n) O(h) Medium 🔍可以看看recursive 的解, 程序设计: 怎么设计一个好的stack, 类似726. Number of Atoms
  • 遇到num, push num 进num stack
  • 遇到'[',push “”进pat stack
456. 132 Pattern O(n) O(h) Medium 🎅🎅 寻找 s1 < s3 < s2,从后向前,Descending stack, 难点: 理解stack让s2 逐渐变大, 但s3可增也可减, 因为s2减小前就return true了
636. Exclusive Time of Functions O(n) O(n) Medium 🔍stack 存的是上个job的id
682. Baseball Game O(n) O(n) Easy ❌bad problem description
726. Number of Atoms O(n^2) O(n) Hard 类似 394. Decode String
735. Asteroid Collision O(n) O(n) Medium 🎅 碰撞发生只能是新来的小于0,stack top > 0
736. Parse Lisp Expression O(n) O(n) Hard ❌stack需要两个,一个是存string dict(用来储存let的字典), 一个存string vector(用来储存上个string的split), 遇到'(', 如果之前是let, 先存map, 然后push进两个stack, string vector清空,字典不清空 。 遇到')', 算当前的, 把结果push到上个string(stkstring.top()) 的结尾, pop两个stack
739. Daily Temperatures O(n) O(n) Medium 🔍 Ascending/Descending stack, 可以正向也可以反向
0901. Online Stock Span O(n) O(n) Medium
                                                  Ascending & Descending Stack 按照 container的顺序进行排序

Linked List

Title Time Space Difficulty Algorithm Note
002. Add Two Numbers O(n) O(1) Medium
021. Merge Two Sorted Lists O(n) O(1) Easy
023. Merge k Sorted Lists O(nklogk) O(1) Hard Heap, Divide Conquer, 注: 不能用一直用0作为l 和r比,这样的话,l的size会增加的很快,到最后l size快成位nk了
024. Swap Nodes in Pairs O(n) O(1) Easy 建dummy, 提取往后第二个为nextnext,断第二,三链, nextnext后接上当前的next, 把nextnext接到当前的next, pt往后走两步
025. Reverse Nodes in k-Group O(n) O(1) Hard 类似206 Reverse Linked List
061. Rotate List O(n) O(1) Medium
082. Remove Duplicates from Sorted List II O(n) O(1) Medium
083. Remove Duplicates from Sorted List O(n) O(1) Easy 不能用recusion, recursion的话会用pass n回linked list,用O(n)space, iterative解space只用O(1),tree可以用recursion原因是它的stack space是O(logn)
138. Copy List with Random Pointer O(n) O(1) Medium 1. 先把每个node复制一个,把复制的贴在被复制的后面
2. loop node(现在长度是2n), 把cur->next->random = cur->random->next,因为cur->random->next是复制cur->random过来的
3. 最后结果就是把每个偶数位的node连接起来,同时要消除偶数的node(长度由2n变回n),否则结果是修改了原来的node
147. Insertion Sort List O(n^2) O(1) Medium Sort
148. Sort List O(nlogn) O(logn) Medium Sort
  • top-down,用两个pointer,一个慢,一个快,去split,然后merge, space: O(logn)
  • bottom-up, 第一次只把1和2顺序,3和4顺序,5和6顺序调整,第二次把1,2和3,4顺序调整,5,6和7,8顺序调整,以此类推, space: O(1)
160. Intersection of Two Linked Lists O(n+m) O(1) Easy 利用的是 lA + lB_1 = lA_1 + lB (lenA + B交点前的长度 = lenB + A交点前的长度),
pA,pB 每次都前进一步,pA到end,pA设为Bhead, pB到end,pB设为Aend,
这种尾对头只换一次,第二次pA 或者pB到end 返回NULL(就是没有交点)
203. Remove Linked List Elements O(n) O(1) Easy
206. Reverse Linked List O(n) O(1) Easy
234. Palindrome Linked List O(n) O(1) Easy revese list前面部分,然后reverse之后,逐个对比前半部分是否等于后半部分的值
237. Delete Node in a Linked List O(n) O(1) Easy 把node->next的val提到node val然后delete node->next
328. Odd Even Linked List O(n) O(1) Medium
  • 把even = head->next, odd = head, 然后逐个先断odd和下个even链 和 even和下个odd链(顺序不能反)
  • 把even顺序保留,把odd提出来, 断even和odd的链,然后evenhead 接在odd->next上
445. Add Two Numbers II O(n+m) O(m+n) Medium 用两个stack,把每个list值push 进stack,最后push进的先算
725. Split Linked List in Parts O(n) O(1) Medium 每次前进到此次push进vector的最后一位, 然后断链, 第i个vector长度为 n//k + (i< n%k)
817. Linked List Components O(n+m) O(m) Medium 把vector转化成unordered_set, 然后判断每个val,是不是在unordered_set里面
LinkedList 当head, cur 指向同一点, cur = cur->next; head 不会改变, 但是当cur在head之后,head包含cur, cur = cur->next, head会跳过cur这点
two pointer 1.whiLe(fast->next && fast->Next->next) 是找中点, 比如1-2-3-4-5-6,slow最后等于3
2.whiLe(fast && fast->Next) 是找中后一点,比如1-2-3-4-5-6,slow最后等于4, 1-2-3-4-5 最后是3

Queue

Title Time Space Difficulty Algorithm Note
239. Sliding Window Maximum O(n) O(k) Hard 😍 Monoqueue using Deque
  • Solution 1 deque int : 只存单个index, descending queue
  • Solution 2 deque pair, first是存当前的数, second表示window开始位置到这个数之前,多少个比现在这个数小
    pop: 看top second-- = 0, pop_front()

Heap

Title Time Space Difficulty Algorithm Note
  • C++ priority_queue default是max heap
  • Python的heapq default是min heap.
  • priority_queue<int, vector<int>, less<int>> 是max_heap, greater<int`>是min_heap
  • multiset<int, greater<int>> 是max_heap
  • multiset和priority_queue用的default comparator相反
264. Ugly Number II O(n) O(1) Medium 😍🎅🎅
  • dp: loop n 而不是 loop 1 到 n-th ugly number
  • heap 的解::alien: 避免heap中出现重复数
295. Find Median from Data Stream O(nlogn) O(1) Medium 虽是hard, 逻辑简单, 两个heap, minheap, maxheap,
✏️可以看看python heapq用法 heappushpop
313. Super Ugly Number O(n*k) O(n+k) Medium 类似 264. Ugly Number II
373. Find K Pairs with Smallest Sums O(k * log(min(n, m, k))) O(min(n, m, k)) Medium 🔍注: 不用hashset, 可不重复push 进heap
🎅不能用two pointer, 比如[1,7], [2,6], 结果是[1,2],[1,6],[2,7], two pointer给的是[1,2],[1,6],[6,7]
✏️: python itertools.product, itertools.islice
O(k) solution
378. Kth Smallest Element in a Sorted Matrix O(k * log(min(n, m, k))) O(min(n, m, k)) Medium Binary Search, Heap, ZigZag Search
407. Trapping Rain Water II O(m * n * (logm + logn)) O(m*n) Hard 😍🎅
  • 难点: 点hold水的高度 取决于 min(周围四个方向上最大高度), 而不是min(四个邻居的高度), 再push进queue(push的height是当前height和cell的最大值)
  • 先把长方形四条边 push进min heap; 要heap top高度是递增的途径: BFS push 时候push max(heap top 高度, heights[i][j])
  • visualization
632. Smallest Range Covering Elements from K Lists O(nklogk) O(k) Hard 😍🎅
  • 难点: 缩小windows, windows需要包含每个list内一个数
  • 用heap, heap中包含每个list中当前最小数
  • 不能用two pointer, two pointer: 每个list每个数 包含在windwos内, 此题是 每个list至少一个数 含在windwos内
  • vector[i][0]的数push进minheap, 一个int 记录最大值, heap top 当前最小值
846. Hand of Straights O(nlogn) O(n) Medium 🔍
  • Solution 1: set, set.begin 为每个group 的起点
  • 😍Solution 2: set + queue, queue记录每个点的windows 每个点 新增加windows数
846. Hand of Straights O(nlogn) O(n) Hard
973. K Closest Points to Origin O(n) average O(1) Easy ✏️Quick-Select
1046. Last Stone Weight O(nlogn) O(n) Easy
                                                 

Two pointer 用于

  • detect cycle
  • sorted array比大小,一个array一个pointer
  • linked list找到middle point

Two Pointer

Title Time Space Difficulty Algorithm Note
019. Remove Nth Node From End of List O(n) O(1) Medium 🔍two pointer, list总长l, 需要remove的index是l-n, slow要前进到l-n-1, 所以先前进n个,再前进到尾部就是l-n-1
086. Partition List O(n) O(1) Medium 🔍
  • 先把head所有小于x的pass掉,slow,head=first大于等于x的node, loop fast 当fast小于x,把这个放在slow上,slow前进一位
  • 建两个node,一个small,一个big,把所有小于的head放在small,其他的放在big,最后把所有big挂在small的后面
141. Linked List Cycle O(n) O(1) Easy
142. Linked List Cycle II O(n) O(1) Medium 🔍具体数学解释, 类似287. Find the Duplicate Number
143. Reorder List O(n) O(1) Medium 😚🎅 用fast & slow先找到medium的点,slow到结尾所有的点reverse, 然后p1 = head, p2 = middle后一点,一个p1, 一个p2 插进pointer,就是结果
167.Two Sum II - Input array is sorted O(n) O(1) Easy ❌ two pointer, 一个从开始位置,一个从末尾的位置
283. Move Zeroes O(n) O(1) Easy ❌ 记录swap后第一个0位置
287. Find the Duplicate Number O(n) O(1) Easy 😍🎅 类似142. Linked List Cycle II ,有duplicate一定会有cycle, 难点: 找起点
  • 所有数都在[0,n], nextIndex = num-1,从n+1(index为n)开始,就不会上来进入循环
  • 从0开始进入,nextIndex = num
  • 每个数数都在[1,n],从0开始
344. Reverse String O(n) O(1) Easy 🔍bit来进行swap
349. Intersection of Two Arrays O(n+m) O(min(m, n)) Easy
  • 用hashmap, O(N)
  • binary search, 要sort两个vector,然后loop v1, 到v2中找有没有v1[i]这个数
  • two pointer, sort两个vector,it1=v1.begin(), it2=v2.begin(),然后根据it1,it2大小,更新结果和自增it1和it2
350.Intersection of Two Arrays II O(n+m) O(1) Easy
  • 如果没有sort, space: O(1) complexity O(max(n,n)*log(max(m,n)) 的解为binary search, two pointer
  • 如果有sort, space: O(1) complexity O(m+n)的解为two pointer
  • ✏️C++ Set Intersection
457. Circular Array Loop O(n) O(1) Medium ❌array loop必须是单向的, 比如1->2, 2->1 不算是loop,循环array每次两个pointer检查有没有loop,如果没有loop,把这次所有走过的点都标成0,下次不用再走了, 类似141. Linked List Cycle
611. Valid Triangle Number O(n^2) O(1) Medium 🎅(无法达到O(n)),先sort然后两个pointer,每一个都指向一个边,
777. Swap Adjacent in LR String O(n) O(1) Medium 🎅 难点是: 寻找left 和 right. R是向前走,L是向后走(swap R 和L都需要X), 两个pointer,遇到X往前跳
826. Most Profit Assigning Work O(mlogm + nlogn) O(1) Medium 😍🔍
  • sort jobs & work, 两个pt,一个指worker, 一个指jobs, profit记录到worker i之前最大的收益
  • 用一个size=10001的vector, v[i]表示第difficulty为i时,最大的profit
828. Unique Letter String O(n) O(1) Hard 😍🎅
  • 难点:转换思路: 数每个substring 中unqiue 个数 = 每个位置的char在多少个substring中unique
  • Solution 1: 需要char 上一次 和上上一次出现的位置, 比如ABAB, (i=3的B 算的i=1 的B在几个substring中unique, 可以(ABA)B, A(BA)B, (AB)AB, A(B)AB, ()表示substring
  • Solution 2 DP:
    • contribution[s[i]]s[i]结束, s[i]为unique的substring个数
    • cur: 以s[i]为end, 每个substring中unique个数
    • lastPost[s[i]]: 上次s[i]出现的位置
    • 难点: 找到contributioncur的关系
838. Push Dominoes O(n) O(n) Medium 🎅🎅🎅
844. Backspace String Compare O(m+n) O(1) Easy 两个pt,都从s,t 从后往前对比
986. Interval List Intersections O(m+n) O(1) Medium

Sort

Title Time Space Difficulty Algorithm Note
056. Merge Intervals O(nlogn) O(n) Medium 类似的题
057. Insert Interval O(nlogn) O(n) Hard 类似的题
075. Sort Colors O(n) O(1) Medium 🎅 Tri Partition, 小的放前面, 大的放最后
088. Merge Sorted Array O(n) O(1) Easy ❌从后往前
147. Insertion Sort List O(n^2) O(1) Medium 148. Sort List 一样
148. Sort List O(nlogn) O(logn) Medium
  • top-down,用两个pointer,一个慢,一个快,去split,然后merge, space: O(logn)
  • bottom-up, 第一次只把1和2顺序,3和4顺序,5和6顺序调整,第二次把1,2和3,4顺序调整,5,6和7,8顺序调整,以此类推, space: O(1)
164. Maximum Gap O(n) O(n) Hard 😍🔍
  • Bucket Sort, double minstep = (max-min)/(n-1) = bucket_step, bucket (0,1) 0是bucket minvalue, 1 是max value, 结果max gap=相邻两个bucket的min[i]-max[i-1]
  • 🔍🔍radix sort, res = 最大两个相邻的点, radix sort排序是从后往前loop,因为之前的digit的是sort,大的digit在最后面,count[i]是从ith-digit的最后一个位置
164. Maximum Gap O(n) O(n) Hard 😍🔍
  • Bucket Sort, double minstep = (max-min)/(n-1) = bucket_step, bucket (0,1) 0是bucket minvalue, 1 是max value, 结果max gap=相邻两个bucket的min[i]-max[i-1]
  • 🔍🔍radix sort, res = 最大两个相邻的点, radix sort排序是从后往前loop,因为之前的digit的是sort,大的digit在最后面,count[i]是从ith-digit的最后一个位置
179. Largest Number O(nlogn) O(n) Medium ✏️✏️ Python Lambda Sort
218. The Skyline Problem O(nlogn) O(logn) Hard 😍😍 priority_queue or multiset(看critical point)
274. H-Index O(n) O(n) Medium ❌counting Sort
315. Count of Smaller Numbers After Self O(nlogn) O(n) Hard MergeSort, BIT
324. Wiggle Sort II O(n) average O(1) Medium ❌(1 + 2*index) % (n | 1)保证median左面数map奇数位,mediam右面的数map偶数位
  • (1)elements smaller than the 'median' are put into the last even slots
  • (2) elements larger than the 'median' are put into the first odd slots
  • (3) the medians are put into the remaining slots.
327. Count of Range Sum O(nlogn) O(n) Hard MergeSort with Count, BIT
347. Top K Frequent Elements O(n) O(n) Medium 😍 Bucket Sort, Quick Select,
  • C++: n-th elements, priority_queue (maxheap: priority_queue, minheap: multiset),
  • python: collections.Count, heapq, most_common(k)
451. Sort Characters By Frequency , 692. Top K Frequent Words 类似
406. Queue Reconstruction by Height O(n * sqrt(n))~O(n^2) O(n) Medium 😚 关键是认清sort的顺序 先把height大的安排了,如果height一样再sort k有小到大。 sqrt(n)解是一样的sort,但是把sort之后的插入到不同的组中,每个组不超过sqrt(n)个元素
462. Minimum Moves to Equal Array Elements II O(nlogn) O(n) Medium Medium是最小化Sum of Absolute Deviations; Quick Select: O(n) on average
451. Sort Characters By Frequency O(n) O(n) Medium Bucket Sort, Quick Select(n-th elements) O(nlogn), priority_queue O(nlogn)
692. Top K Frequent Words O(nlogk) O(n) Medium Bucket Sort, Quick Select(n-th elements), priority_queue
853. Car Fleet O(nlogn) O(n) Medium Greedy: sort postion又大到小,再sort到target的时间由小到大
1029. Two City Scheduling O(n) average O(n) Easy Greedy**,quick select
C++priority_queue<pair<int,int>>pq 先对比first, top是first最大的,
constructor: greater<int>是让top返回最小的数,大的数放后面
python的heappop()先pop对比first,then second, top是first最小的
1365 How Many Numbers Are Smaller Than the Current Number O(n+m) O(m) Easy 🔍O(n+m) Solution Counting Sort 🔍Python Counting Sort
1366. Rank Teams by Votes O(n) O(1) Medium 🔍Python Sort list based on Dictonary value

Recursion

Title Time Space Difficulty Algorithm Note
095. Unique Binary Search Trees II O(4^n / n^(3/2)) O(4^n / n^(3/2)) Medium 😍 🔍loop start -> end. Generate vector of left subtree 和right subtree, 然后排列组合把他们弄在一起
096. Unique Binary Search Trees O(n) O(1) Medium DP, cartesian product
作为root,sum(#left + #right) Catalan number
098. Validate Binary Search Tree O(n) O(1) Medium 用prev 点, iterative + recurssion
100. Same Tree O(n) O(h) Easy
104. Maximum Depth of Binary Tree O(n) O(h) Easy
105. Construct Binary Tree from Preorder and Inorder Traversal O(n) O(h) Medium 😍😍 🔍🔍注意和889. Construct Binary Tree from Preorder and Postorder Traversal stack的区别. preorder 第一个是tree的root, inorder 中root->val左面root的left tree,右面root的right tree,
106. Construct Binary Tree from Inorder and Postorder Traversal O(n) O(h) Medium 😍😍 🔍🔍 O(1) memory 和 stack
108. Convert Sorted Array to Binary Search Tree O(n) O(logn) Easy ❌ 跟095. Unique Binary Search Trees II逻辑一样 binary tree height 需要balanced
109. Convert Sorted List to Binary Search Tree O(n) O(logn) Medium 🔍注意O(N)的解,不是two pointer的
110. Balanced Binary Tree O(n) O(h) Medium 😚 跟095. Unique Binary Search Trees II类似 用bottom-up 比top-down 更efficient
111. Minimum Depth of Binary Tree O(n) O(h) Medium if not left: return h(r.right)+1; , if not right: return h(r.left)+1; else: return min(h(r.right), h(r.left))+1;
114. Flatten Binary Tree to Linked List O(n) O(h) Medium 🔍😍 preorder 的reverse
116. Populating Next Right Pointers in Each Node O(n) O(1) Medium 审题: perfect binary tree
  • 每层横着走, 连left 到right, 连right 到next left
  • 或者是阶梯式向下connect root1 left和 root1 right & root1 right和root2 left & root2 left和root2 right
124. Binary Tree Maximum Path Sum O(n) O(h) Hard 🔍not hard question
129. Sum Root to Leaf Numbers O(n) O(h) Medium O(1) extra memory
241. Different Ways to Add Parentheses O(n* 4^n / n^(3/2)) O(n * 4^n / n^(3/2)) Medium 😍 算sign前的,算sign后的,然后做前和后的permutation和
337. House Robber III O(n) O(h) Medium 🎅Greedy Algorithm. 返回vector, vector[0]存的是用上一个最大的获取值,vector[1]存的是不用上一个 最大的获取值
395. Longest Substring with At Least K Repeating Characters O(n) O(n) Medium 😍😍
  • Solution 1 Divide-conquer 一旦小于k, 就split成left和right,然后返回left和right的max值
  • Solution 2 two pointer
404. Sum of Left Leaves O(n) O(h) Easy
437. Path Sum III O(n) O(h) Easy 🔍一定用unorderedmap , 不能用unordered_set, 比如 -5,5,-6,6,4, 要sum = 4, 可以从-5到4 或者-6 到4
669. Trim a Binary Search Tree O(n) O(h) Easy 😚
671. Second Minimum Node In a Binary Tree O(n) O(h) Easy
761. Special Binary String O(n^2) O(n) Hard ❌Bad problem description Divide-conquer, 把每个special string 再分成小的special string,然后sort


Binary Search

Title Time Space Difficulty Algorithm Note
004. Median of Two Sorted Arrays O(log(min(m, n))) O(1) Hard 💜🎅🎅
033. Search in Rotated Sorted Array O(log(n)) O(1) Medium 💜🎅Similar Question:
034. Find First and Last Position of Element in Sorted Array O(log(n)) O(1) Medium lowerbound/upperbound/EqualRange, lowerbound 可以convert to int
35. Search Insert Position O(log(n)) O(1) Easy
069. Sqrt(x) O(log(n)) O(1) Easy 🎅 Bit Solution similar Question
074. search a 2D Matrix O(logm + logn) O(1) Medium lower_bound, upper_bound lambda
081. Search in Rotated Sorted Array II O(logn) O(1) Medium 💜🎅 Similar Question:
153. Find Minimum in Rotated Sorted Array O(logn) O(1) Medium Similar Question:
154. Find Minimum in Rotated Sorted Array II O(logn) ~ O(n) O(1) Hard Similar Question:
162. Find Peak Element O(logn) O(1) Medium
222. Count Complete Tree Nodes O((logn)^2) O(1) Medium 注意审题 complete tree
275. H-Index II O(logn) O(1) Medium
278. First Bad Version O(logn) O(1) Easy
300. Longest Increasing Subsequence O(nlogn) O(n) Medium 💜🎅🎅🎅 similar question
354. Russian Doll Envelopes O(nlogn) O(n) Hard 💜🎅similar question
363. Max Sum of Rectangle No Larger Than K O(min(m, n)^2 * max(m, n) * logn(max(m, n))) O(max(m, n)) Hard 💜🎅🎅, 利用Set
367. Valid Perfect Square O(logn) O(1) Easy Similar Question
374. Guess Number Higher or Lower O(logn) O(1) Easy
378. Kth Smallest Element in a Sorted Matrix O(n * log(MAX - MIN) O(1) Medium l=m[0][0], r=m[-1][-1], binary search 是否至少有k个数小于等于mid
410. Split Array Largest Sum O(nlogn) O(1) Hard 💜
436. Find Right Interval O(nlogn) O(n) Medium map lower bound
475. Heaters O((m + n) * logn) O(1) Easy
  • sort heater + lower_bound
  • sort house sort heaters,逐渐递增index
540. Single Element in a Sorted Array O(logn) O(1) Medium
658. Find K Closest Elements O(logn+k) O(1) Medium x-arr[left-1]<=arr[right]-x 保证left一定是起点,right是最后数后面一位
668. Kth Smallest Number in Multiplication Table O(log(mn)*min(n,n)) O(1) Hard binary search [1,m*n], isValid判断是否有至少有k个element在乘法表中
719. Find K-th Smallest Pair Distance O(nlogn + nlogw) O(1) Hard sort nums, l=0, r = nums[-1]-nums[0], binary search是否有k个数大于等于mid在num中
744. Find Smallest Letter Greater Than Target O(logn) O(1) Easy 判断最后一个字母是不是大于target, 大于的话用upperbound,否则返回第一个char
786. K-th Smallest Prime Fraction O(nlogr) O(1) Hard
  • 用priority_queue, 先push进最小的,每次push前extract当前最小的, 保证push进去的比pop的大,最多max(n,k)次pop+push
  • binary search l=0, r=1, 看是不是有n个pair小于等于mid,i=0,增加j,减小A[i]/[j]的值,一旦A[i]/[j]小于等于mid,增加i,就是增加A[i]/[j], 再增加j, 如果count==k, 返回k中最大的那个pair
    793.Preimage Size of Factorial Zeroes Function O((logk)^2) O(1) Hard l = 0, r=5*k, binary search mid是否有k个零的0,有的话r=mid, 否则l = mid+1, 最后再判断l是否有k个0, 有的话返回5,没有的话返回0
    1385. Find the Distance Value Between Two Arrays O((n + m) * logm) O(1) Easy 🎅Binary Search, Two pointer


    Binary Search Tree

    Title Time Space Difficulty Algorithm Note
    220. Contains Duplicate III O(nlogn) O(n) Medium set/multiset lower_bound  或者python OrderedDict, 每次popitem(false) pop 最先insert的
    230 Kth Smallest Element in a BST O(max(h, k)) O(min(h, k)) Medium inorder traversals(从最小的travel到最大的) / stack
    235. Lowest Common Ancestor of a Binary Search Tree O(h) O(1) Easy 利用 binary search tree的性质
    352. Data Stream as Disjoint Intervals O(logn) O(n) Hard
    449. Serialize and Deserialize BST O(n) O(h) Medium preorder traversals
    450. Delete Node in a BST O(h) O(h) Medium
    • swap key 和比key大的最小值,然后recursively删除swap的值
    • 把key的left tree 挂在key->right的leftmost tree下面(比key大的最小数下面)
    530. Minimum Absolute Difference in BST O(n) O(h) Easy 利用binary search tree的性质 或者inorder traversal 带着前面prev的node val
    783. Minimum Distance Between BST Nodes O(n) O(h) Easy 利用binary search tree的性质 或者inorder traversal 带着前面prev的node val(与530题 解法一样)
    1382 Balance a Binary Search Tree O(n) O(h) Medium


    Tree Relevant

    Title Time Space Difficulty Algorithm Note
    094. Binary Tree Inorder Traversal O(n) O(1) Medium Tree
    095. Unique Binary Search Trees II O(4^n / n^(3/2)) O(4^n / n^(3/2)) Medium 😍 🔍loop start -> end. Generate vector of left subtree 和right subtree, 然后排列组合把他们弄在一起
    098. Validate Binary Search Tree O(n) O(1) Medium 用prev 点, iterative + recurssion
    099 Recover Binary Search Tree O(n) O(1) Hard Tree
    100. Same Tree O(n) O(h) Easy
    104. Maximum Depth of Binary Tree O(n) O(h) Easy
    101. Symmetric Tree O(n) O(h) Easy ❌ 注: iterative stack push 顺序
    108. Convert Sorted Array to Binary Search Tree O(n) O(logn) Easy ❌ 跟095. Unique Binary Search Trees II逻辑一样 binary tree height 需要balanced
    109. Convert Sorted List to Binary Search Tree O(n) O(logn) Medium 🔍注意O(N)的解,不是two pointer的
    110. Balanced Binary Tree O(n) O(h) Medium 😚 跟095. Unique Binary Search Trees II类似 用bottom-up 比top-down 更efficient
    111. Minimum Depth of Binary Tree O(n) O(h) Medium if not left: return h(r.right)+1; , if not right: return h(r.left)+1; else: return min(h(r.right), h(r.left))+1;
    112. Path Sum O(n) O(h) Easy 🔍(iterative Solution: 如果有right会经过root 两次)[https://github.com/beckswu/Leetcode/blob/master/DFS/112.%20Path%20Sum.cpp#L74]
    124. Binary Tree Maximum Path Sum O(n) O(h) Hard 🔍not hard question
    129. Sum Root to Leaf Numbers O(n) O(h) Medium O(1) extra memory
    144. Binary Tree Preorder Traversal O(n) O(1) Medium Tree
    145. Binary Tree Postorder Traversal O(n) O(1) Hard Tree
    199 Binary Tree Right Side View O(n) O(h) Medium ❌ Easy
    222. Count Complete Tree Nodes O((logn)^2) O(1) Medium
    257 Binary Tree Paths O(n * h) O(h) Easy ❌ Easy
    404. Sum of Left Leaves O(n) O(h) Easy
    437. Path Sum III O(n) O(h) Easy unorderedmap 存的在现在点之前的 <prefix sum, frequency> pairs. 从中间某点到现在sum = 从root到现在点sum - root到中间某点的sum
    515. Find Largest Value in Each Tree Row O(n) O(h) Medium ❌ DFS / BFS
    538. Convert BST to Greater Tree O(n) O(h) Easy Tree
    543. Diameter of Binary Tree O(n) O(h) Easy Tree
    572. Subtree of Another Tree O(m * n) O(h) Easy
    617. Merge Two Binary Trees O(n) O(h) Easy
    623. Add One Row to Tree O(n) O(h) Medium
    637. Average of Levels in Binary Tree O(n) O(h) Easy
    653. Two Sum IV - Input is a BST O(n) O(h) Easy
    671. Second Minimum Node In a Binary Tree O(n) O(h) Easy
    687. Longest Univalue Path O(n) O(h) Easy
    669. Trim a Binary Search Tree O(n) O(h) Easy 😚
    814. Binary Tree Pruning O(n) O(h) Medium
    863. All Nodes Distance K in Binary Tree O(n) O(h) Medium 😍😍Really good question! 不必纠结于one pass, 需要child -> parent map
    865. Smallest Subtree with all the Deepest Nodes O(n) O(h) Medium 🔍DFS, left level == right level 返回root, if left level > right level, 返回left dfs的node else返回right dfs的
    889. Construct Binary Tree from Preorder and Postorder Traversal O(n) O(h) Medium 😍😍
    • Solution 1: 难点是找到 left 和right的边界: 假定都把下一个assign 给left
    • 用stack
    1008. Construct Binary Search Tree from Preorder Traversal O(n) O(h) Medium 🔍Stack / Morris Traversal
    1028. Recover a Tree From Preorder Traversal O(n) O(h) Hard 😚 stack / DFS, stack逻辑类似889. Construct Binary Tree from Preorder and Postorder Traversal
    1367 Linked List in Binary Tree O(n+l) O(h+l) Medium
                                                                    

    Depth-First Search

    Title Time Space Difficulty Algorithm Note
    112. Path Sum O(n) O(h) Easy 🔍iterative Solution: 如果有right会经过root 两次
    113 Path Sum II O(n) O(h) Medium 🔍iterative Solution: 如果有right会经过root 两次
    199 Binary Tree Right Side View O(n) O(h) Medium ❌ Easy
    200 Number of Islands O(m * n) O(m * n) Medium ✏️ Union Find with Rank Heuristics, ✏️Python Complex number 表示四个DFS 方向
    236 Lowest Common Ancestor of a Binary Tree O(n) O(h) Medium 🔍 Iterative Solution
    257 Binary Tree Paths O(n * h) O(h) Easy ❌ Easy
    282 Expression Add Operators O(4^n) O(n) Hard 🎅难点: 弄清 cv (cumulative sum), pv(previous sum) 关系,
    pos 到现在process的index,注意:
    • 现在是'*', cv = cv - pv + p*n, pv = pv*n
    • 现在是'-', cv = cv - pv + n, pv = -n
    301. Remove Invalid Parentheses O(C(n, c)) O(c) Hard 😍😍Complexity Analysis
    • 🎅DFS: 开始DFS前记录left_removed,
      right_removed, 这样可以保证删除的parenthese 最短,
      再记录pair,'(' 时候pair+1, ')'时候pair-1, pair最后等于0, 表示valid
    • 🔍BFS, First try all possible results当移走一个括号, 当两个括号...until find valid 用unordered_set 记录所有被visited的string,Or TLE
    • 🎅BrainStorming More Efficient DFS
    329. Longest Increasing Path in a Matrix O(m * n) O(m * n) Hard 😍
    332. Reconstruct Itinerary O(t! / (n1! * n2! * ... nk!)) O(t) Medium 😍
    399. Evaluate Division O(q*|V|!) O(e) Medium DFS with memiozation 用unordered_map, vector, unordered_set记录是否经过, 跟329. Longest Increasing Path in a Matrix类似
    417. Pacific Atlantic Water Flow O(m * n) O(m * n) Medium 😍🎅 bit mask, 难点: 起点必须是四个边
    440. K-th Smallest in Lexicographical Order O(logn) O(logn) Hard 找规律, 不能一个一个算, 要跳缩减区间
    464. Can I Win O(n!) O(n) Medium 😚DFS+Memoization 难点: Memoization记录的不能是还剩多少到target, 记录是现在可选择的set能不能赢
    515. Find Largest Value in Each Tree Row O(n) O(h) Medium ❌ DFS / BFS
    547. Friend Circles O(n^2) O(n) Medium Union Find with Rank Heuristic / DFS
    638. Shopping Offers O(n * 2^n) O(n) Medium 🎅✏️ [设计一个好的DFS structure](https://github.com/beckswu/Leetcode/blob/master/DFS/638.%20Shopping%20Offers.cpp#L42]
    690. Employee Importance O(n) O(h) Easy 需要用unordered_map, 因为vector index 不等同于 id
    695. Max Area of Island O(m*n) O(m*n) Medium ✏️Python Complex number 表示四个DFS 方向
    733. Flood Fill O(m*n) O(m*n) Easy
    749. Contain Virus O((m * n)^(4/3)) O(m * n) Hard 😚 DFS/BFS, every step try each possibility see where is max new Infection area, then build wall and update grid
    753. Cracking the Safe O(k^n) O(k^n) Hard 🎅 Greedy + BrainStorming, 难点:如果设置起始数字,如何Loop 不会有deadlock
    756. Pyramid Transition Matrix O(a^b) O(a^b) Medium bottom-up, bit mask
    785. Is Graph Bipartite? O(|V+E|) O(|V|) Medium DFS/BFS + Bit Mask, 用红蓝两色表vertex,如果相邻的node 一样颜色 return false
    797. All Paths From Source to Target O(p + r * n) O(n) Medium
    802. Find Eventual Safe States O(|V+E|) O(|V|) Medium 😚 DFS + bit mask 需要定义state 0:unvisited, 1 visited not safe, 2 visited not safe, 3 visited and safe 注意不能用visited 的value 代替boolean 的value
    886. Possible Bipartition O(|V+E|) O(|V+E|) Medium DFS, BFS
    980. Unique Paths III O((m * n) * 2^(m * n)) O((m * n) * 2^(m * n)) Medium DFS, BFS
    1367 Linked List in Binary Tree O(n+l) O(h+l) Medium KMP 🔍C++ 用const auto [] get function return pair
    1368 Minimum Cost to Make at Least One Valid Path in a Grid O(m*n) O(m*n) Medium BFS + DFS
    1377. Frog Position After T Seconds O(n) O(n) Hard ✏️Python Set
    1391. Check if There is a Valid Path in a Grid O(m*n) O(1) Medium
    1397. Count Number of Teams O(m*n) O(m) Hard DFS /DP + KMP 🎅🎅 


    Backtracking

    Title Time Space Difficulty Algorithm Note
    017. Letter Combinations of a Phone Number O(n * 4^n) O(n) Medium ✏️Python Lambda Function
    022. Generate Parentheses O(4^n / n^(3/2)) O(n) Medium ✏️Python Trick
    037. Sudoku Solver O((9!)^9) O(1) Hard 可以用bit mask
    039. Combination Sum O(k * n^k) O(k) Medium ✏️Python Trick, Difference between yield and return
    040. Combination Sum II O(n * n!) O(n) Medium
    216. Combination Sum III O(k * C(n, k)) O(k) Medium 🔍Python itertools.combination
    046. Permutations O(\n * n!) O(n) Medium
    047. Permutations II O(\n * n!) O(n) Medium
    051. N-Queens O(n!) O(n) Hard 🔍Python Solution
    052. N-Queens-II O(n!) O(n) Hard ❌ 与051. N-Queens 逻辑一样
    077. Combinations O(k * C(n, k)) O(k) Medium 😍 Python Multiple Solution
    079. Word Search O(m * n * l) O(l) Medium Simple DFS. smart way: 把visited的字母改了 省掉了hashset, visited
    093. Restore IP Addresses O(1) O(1) Medium recursive & iterative
    078. Subsets O(n * 2^n) O(1) Medium 😍😍
    • recursive
    • iterative
    • bit trick 第一个数每2次出现1次,第二个数每4次出现2次,第二个数每8次出现4次
    090. Subsets II O(n * 2^n) O(1) Medium recursive(逻辑类似040. Combination Sum II) & 😍😍 iterative(插数)
    126. Word Ladder II O(n * d) O(d) Hard
    131. Palindrome Partitioning O(n^2) ~ O(2^n) O(n^2) Medium 😍Python Solution
    140. Word Break II O(n * l^2 + n * r) O(n^2) Hard 🎅DFS with Memoization, 没有memoization TLE, ✏️C++ Std:function
    212. Word Search II O(m * n * l) O(l) Hard Suffix Trie (backtracking 是把board 暂时改了, 省去了hashset visited), 难度medium左右, ✏️Python Complex number 表示四个DFS 方向, Dictionary setdefault
    526. Beautiful Arrangement O(n!) O(n) Medium swap, 注意if 条件, 🔍Python Solution
    676. Implement Magic Dictionary O(n) O(d) Medium
    • 😚Suffix Trie
    • instead search every chars from A-Z, search hello as ello, hllo
    679. 24 Game O(1) O(1) Hard Complexity: upper bound of 12* 6 * 2 * 4 * 4 * 4 = 9216 possibilities🔍🔍 Python Solution
    698. Partition to K Equal Sum Subsets O(n* 2^n) O(2^n) Medium 😍😍 非常经典题目,
    • 🔍Solution 1: Bucket, 需要sort, 否则TLE
    • Solution 2: 要有start index, 否则time out
    718. Maximum Length of Repeated Subarray O(m * n) O(min(m, n)) Medium 🔍 DP
    784. Letter Case Permutation _O(n * 2^n) _ O(1) Easy ✏️Python itertools.product

    Graph

    Title Time Space Difficulty Algorithm Note
    1361. Validate Binary Tree Nodes O(n) O(n) Medium DFS


    DFS 是看有没有path,DP是看有几个path

    Dynamic Programming

    Title Time Space Difficulty Algorithm Note
    010. Regular Expression Matching O(m*n) O(n) Hard 🎅🎅
    044. Wildcard Matching O(n*m) O(1) Hard dp or greedy (Greedy也是 O(n*m) )
    053. Maximum Subarray O(n) O(1) Easy 😍 更新res, minsum 的顺序
    062. Unique Paths O(m * n) O(m + n) Medium
    063. Unique Paths II O(m * n) O(m + n) Medium
    064. Minimum Path Sum O(m * n) O(m + n) Medium
    070. Climbing Stairs O(n) O(1) Easy
    072. Edit Distance O(m*n) O(m+n) Hard 类似的题:
    087. Scramble String O(n^4) O(n^3) Hard 🎅 Memoization
    091. Decode Ways O(n) O(1) Medium 😍😍🎅 similar question: 062. Unique Paths, 070. Climbing Stairs 509. Fibonacci Number
    097. Interleaving String O(m*n) O(m+n) Hard 🎅 DP, DFS, BFS
    115. Distinct Subsequences O(n^2) O(n) Hard 🎅🎅
    类似的题:
    120. Triangle O(m*n) O(n) Medium Bottom-up DP
    123. Best Time to Buy and Sell Stock III O(n) O(n) Hard 🎅🎅Why variables order doesn't matter
    类似
    132. Palindrome Partitioning II O(n^2) O(n)
    ~O(n)
    Hard 🎅🎅
    类似的题:
    139. Word Break O(n^2) O(n) Medium
    • DP
    • Suffix Trie + DP
    152. Maximum Product Subarray O(n) O(1) Medium 🎅🎅Prefix Product, Suffix Product
    174. Dungeon Game O(n+m) O(n)~O(1) Hard 🎅 bottom-up DP, Can't start at (0,0)
    188. Best Time to Buy and Sell Stock IV O(k*n) O(n) Hard 类似的题
    198. House Robber O(n) O(1) Easy Top-down / bottom-up
    类似的题:
    213. House Robber II O(n) O(1) Medium 分成两个house rob问题,
    • Rob houses 0 to n - 2
    • Rob houses 1 to n - 1

    类似的题:
    221. Maximal Square O(n^2) O(n) Medium 类似的题:
    279. Perfect Squares O(n * sqrt(n) O(n) Medium Bottom-Up DP, Top-Down DP,BFS. Similar Question
    304. Range Sum Query 2D - Immutable ctor: O(m * n), lookup: O(1) O(m+n) Medium 类似的题:
    309. Best Time to Buy and Sell Stock with Cooldown O(n) O(1) Medium
    312. Burst Balloons O(n^3) O(n^2) Hard Top-Down / Bottom-up, Similar Question: 546. Remove Boxes
    322. Coin Change O(n*k) O(k) Medium Bottom-up, Top-Down, BFS, Similar Question
    338. Counting Bits O(n) O(n) Medium Math 找规律
    357. Count Numbers with Unique Digits O(n) O(1) Medium 🎅DP, Static DP, backtracking
    368. Largest Divisible Subset O(n^2) O(n) Medium 🎅🎅Key: a < b < c, if c % b = 0 and b % a = 0 Then c % a == 0
    类似题:
    375. Guess Number Higher or Lower II O(n^2) O(n^2) Medium 🎅
    377. Combination Sum IV O(nlogn + n * t) O(t) Medium Similar Question
    403. Frog Jump O(n^2) O(n^2) Hard 经典, TopDown, Bottom-up, BFS
    416. Partition Equal Subset Sum O(n*s) O(s) Medium backtracking / DP
    446. Arithmetic Slices II - Subsequence O(n^2) O(n*d) Hard 🎅
    466. Count The Repetitions O(s1 * min(s2, n1)) O(s2) Hard 🎅🎅
    467. Unique Substrings in Wraparound String O(n) O(1) Medium 经典🎅🎅
    472. Concatenated Words O(n * l^2) O(l) hard suffix Trie
    474. Ones and Zeroes O(s *m * n) O(s *m * n) Medium 经典🎅, Top-Down, Bottom-up
    486. Predict the Winner O(n^2) O(n) Medium 经典🎅🎅, DP解, DFS
    514. Freedom Trail O(k) ~ O(k * r^2) O(r) Hard 经典🎅🎅, Top-Down, Bottom-up 
    516. Longest Palindromic Subsequence O(n^2) O(n) Medium 经典🎅, Bottom-up, Top-Down
    类似的题:
    518. Coin Change 2 O(n^2) O(n) Medium 经典🎅TopDown, Bottom-up
    546. Remove Boxes O(n^3) ~ O(n^4) O(n^3) Hard 🎅🎅🎅 Top-Down, Bottom-up, Similar Question: 312. Burst Balloons
    552. Student Attendance Record II O(n) O(1)~O(n) Hard 🎅 Derive Relation
    576. Out of Boundary Paths O(N * m * n) O(m * n) Medium DP, DFS, BFS
    583. Delete Operation for Two Strings O(m*n) O(n) Medium Edit Distance without replace
    类似题:
    600. Non-negative Integers without Consecutive Ones O(1) O(1) Hard 🎅🎅 Math & Bit
    629. K Inverse Pairs Array O(n*k) O(k) Hard 🎅找规律
    639. Decode Ways II O(n) O(1) Hard 🎅 巧解
    类似的题: 091. Decode Ways
    650. 2 Keys Keyboard O(sqrt(n)) O(1) Medium 🎅 Greedy / DP prime factoring
    664. Strange Printer O(n^3) O(n^2) Hard 🎅🎅
    类似的题:
    673. Number of Longest Increasing Subsequence O(n^2) O(n) Medium 💜🎅🎅
    688. Knight Probability in Chessboard O(k*n^2) O(k*n^2)
    ~O(n^2)
    Medium 💜 Bottom-up, Top-Down
    689. Maximum Sum of 3 Non-Overlapping Subarrays O(n) O(n) Hard 🎅🎅🎅 sliding windows/ DP similar to Stock Purchasing
    类似的题
    691. Stickers to Spell Word O(2^T*S*T) O(2^T) Hard 🎅🎅🎅
    712. Minimum ASCII Delete Sum for Two Strings O(m*n) O(m*n)
    ~O(n)
    Medium Edit Distance
    类似的题:
    714. Best Time to Buy and Sell Stock with Transaction Fee O(n) O(n) Medium
    730. Count Different Palindromic Subsequences O(n^2) O(n) Hard Hard中Hard 🎅🎅🎅
    740. Delete and Earn O(n) O(n) Medium 类似的题:
    741. Cherry Pickup O(n^3) O(n^2) Hard 🎅🎅🎅
    746. Min Cost Climbing Stairs O(n) O(1) Easy
    764. Largest Plus Sign O(n^2) O(n^2) Medium Maximal Square, 从左到右,从上到下,从右到左,从下到上,更新最小的count 类似的题:
    788. Rotated Digits O(n)~O(logn) O(n)~O(logn) Easy 🎅🎅🎅
    790. Domino and Tromino Tiling O(n) O(n)~O(1) Medium 🎅🎅 Math 找规律
    799. Champagne Tower O(n^2) O(n^2)~O(n) Medium
    801. Minimum Swaps To Make Sequences Increasing O(n) O(1) Medium 🎅
    805. Split Array With Same Average O(n^4) O(n^3) Hard 💜 🎅🎅🎅 totalSum/n = Asum/k = Bsum/(n-k)
    808. Soup Servings O(1) O(1) Medium
    813. Largest Sum of Averages O(k*n^2) O(n) Medium 💜🎅🎅🎅
    818. Race Car O(nlogn) O(n) Hard 🎅🎅🎅
    823. Binary Trees With Factors O(n^2) O(n) Medium 类似题:  
    837. New 21 Game O(n) O(n) Medium 🎅🎅🎅
    847. Shortest Path Visiting All Nodes O(n*2^n) O(n*2^n) Hard BFS/DP🎅
    877. Stone Game O(n^2) O(n) Medium Strategy
    879. Profitable Schemes O(n*g*p) O(g*p) Hard 💜🎅
    903. Valid Permutations for DI Sequence O(n^2) O(n) Hard 💜🎅🎅
    920. Number of Music Playlists O(n*l) O(n) Hard 🎅🎅🎅
    926. Flip String to Monotone Increasing O(n) O(n) Medium 💜🎅🎅
    931. Minimum Falling Path Sum O(n^2) O(n) Medium
    926. Flip String to Monotone Increasing O(n) O(n) Medium 💜
    935. Knight Dialer O(logn) O(1) Medium 💜Citadel真题. Matrix Exponentiation 
    940. Distinct Subsequences II O(n) O(1) Medium 💜🎅 
    943. Find the Shortest Superstring O(n^2 * 2^n) O(n^2) Medium 🎅🎅🎅 Travelling Salesman Problem 
    956. Tallest Billboard O(n * 3^(n/2)) O(3^(n/2)) Hard 🎅🎅🎅 Knapsnack 
    960. Delete Columns to Make Sorted III O(n * l^2) O(l) Hard 🎅类似的题:  
    975. Odd Even Jump O(nlogn) O(n) Hard 💜🎅🎅🎅, Mono Stack/BST
    983. Minimum Cost For Tickets O(n) O(1) Medium 💜🎅🎅 Similar Question
    1277. Count Square Submatrices with All Ones O(m*n) O(1) Medium  类似的题:
    1387. Sort Integers by The Power Value O(n) average O(n) Medium nth_element, ✏️✏️C++ Static Variable Python Static Variable 
    1388. Pizza With 3n Slices O(n^2) O(n) Hard 😍😍 类似213. House Robber II 和 188. Best Time to Buy and Sell Stock IV
    1395. Count Number of Teams O(n^2) O(1) Medium  
    1411. Number of Ways to Paint N × 3 Grid O(logn) O(1) Medium 😍😍 Matrix Exponentiation 
    1420. Build Array Where You Can Find The Maximum Exactly K Comparisons O(n*m*k) O(m*k) Hard 🎅 
                                                                    


    Design

    Title Time Space Difficulty Algorithm Note
    146. LRU Cache O(1) O(k) Medium
    380. Insert Delete GetRandom O(1) O(1) O(1) Medium 🎅🎅
    1381. Design a Stack With Increment Operation ctor: O(1)
    push: O(1)
    pop: O(1)
    increment: O(1) O(n) Medium Lazy increment
    [1396. Design Underground System](1396 Design Underground System) ctor: O(1)
    checkin: O(1)
    checkout: O(1)
    getaverage: O(1) O(n) Medium


    Bash

    Title Time Space Difficulty Algorithm Note
    192 Word Frequency O(n) O(k) Medium switch column awk, remove whitespace sed
    193. Valid Phone Numbers O(n) O(1) Easy grep
    194 Transpose File Shell O(n^2) O(n^2) Medium paste & cut
    195. Tenth Line O(n) O(1) Easy awk, sed

    leetcode's People

    Recommend Projects

    • React photo React

      A declarative, efficient, and flexible JavaScript library for building user interfaces.

    • Vue.js photo Vue.js

      🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

    • Typescript photo Typescript

      TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

    • TensorFlow photo TensorFlow

      An Open Source Machine Learning Framework for Everyone

    • Django photo Django

      The Web framework for perfectionists with deadlines.

    • D3 photo D3

      Bring data to life with SVG, Canvas and HTML. 📊📈🎉

    Recommend Topics

    • javascript

      JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

    • web

      Some thing interesting about web. New door for the world.

    • server

      A server is a program made to process requests and deliver data to clients.

    • Machine learning

      Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

    • Game

      Some thing interesting about game, make everyone happy.

    Recommend Org

    • Facebook photo Facebook

      We are working to build community through open source technology. NB: members must have two-factor auth.

    • Microsoft photo Microsoft

      Open source projects and samples from Microsoft.

    • Google photo Google

      Google ❤️ Open Source for everyone.

    • D3 photo D3

      Data-Driven Documents codes.