Code Monkey home page Code Monkey logo

leetcode's Introduction

Catalogue

🔍 ⭐ good algorithm
💥 : hard problem
✏️ smart code design
🎅: good question
❌: not good designed question

几个单独算法:

  1. Trie
  2. Union Find

C++

  • c++ vector 可以作为map的key,但不能作为unordered_map的Key
  • C++ unordered_set 的insert 的return 的pair.second 可以告诉有没有insert 成功,如果原来就有,return false, 如果unordered_set 之前没有, return true 比如 2101. Detonate the Maximum Bombs

KMP

complexity O(m+n), 不是kmp pattern search是O(mn)

作为suffix 放后面, 作为prefix 放前面,比如 a ("abc") + b("bcd") = 最小包含两个是的 = "abcd" , 用kmp时候, b (prefix) + "# + a (suffix)

/*
kmp的逻辑比如 
   text: a b c d a b x a b c d a b c d a b c y
pattern: a b c d a b c y
                     ^
                     |
                  not match 
check if any suffix is also preffix, 发现 abcdab 中 ab 即是prefix 也是suffix 
就可以不用从头搜寻从 a b 开始, move pattern like this
   text: a b c d a b x a b c d a b c d a b c y
pattern:         a b c d a b c y  then check if x and a are the same

   text: a b c d a b x a b c d a b c d a b c y
pattern:               a b c d a b c y
                                     ^
                                     |
                                not match 
check if any suffix is also preffix, 发现 abc即是prefix 也是suffix , 
no reason to compare abc again move pattern like this
   text: a b c d a b x a b c d a b c d a b c y
pattern:                       a b c d a b c y 


calculate pattern's longgest prefix which is a suffix. lps[i]表示在index i结束 prefix也是suffix最大长度

For the pattern “AAAA”, lps[] is [0, 1, 2, 3]
For the pattern “AABAACAABAA”, lps[] is [0, 1, 0, 1, 2, 0, 1, 2, 3, 4, 5]
For the pattern “AAACAAAAAC”, lps[] is [0, 1, 2, 0, 1, 2, 3, 3, 3, 4] 
For the pattern “AAABAAA”, lps[] is [0, 1, 2, 0, 1, 2, 3]
For the pattern "aacaabdaacaac: lps is [0, 1, 0, 1, 2, 0, 0, 1, 2, 3, 4, 5, 3]

a a c a a b d a a c a a c -> 到 c, j = 5, 不match, pattern[j]!=pattern[i] => j = prefix[j-1] = prefix[4] = 2 => ve pattern[2] == pattern[i] 
0 1 0 1 2 0 0 1 2 3 4 5  


*/

int kmp(const string &text, const string & pattern){
    vector<int>prefix = computeLps(pattern);
    int j = 0; 
    for(int i = 0; i<text.size(); i++){  //i start from 0
        while(j>0 && pattern[j]!=text[i])
            j = prefix[j-1];
        if(pattern[j] == text[i])
            j++;
        if(j == pattern.size()){
            cout<<" pattern match at index="<<i - j + 1<<endl;
            j = lps[j-1]; //注意j 跳到上lps[j-1]
            /*
            比如  text = a b a b a b a b
             pattern  = a b a b 
                              |  => move j to 2 
                              v
                   pattern  a b a b 
            
            */
        }
    }
}

vector<int>computeLps(const string& pattern){
    vector<int>lps(pattern.size()); //p 记录 longest proper prefix which is also a suffix. 
    //A proper prefix is a prefix with a whole string not allowed. 
    // For example, prefixes of “ABC” are “”, “A”, “AB” and “ABC”. Proper prefixes are “”, “A” and “AB”. Suffixes of the string are “”, “C”, “BC”, and “ABC”.
    int j = 0; //表示最长prefix 也是suffix的index
    for(int i = 1; i<pattern.size(); i++){ // ** i start from 1
        while(j>0 && pattern[j]!= pattern[i]){
            j = lps[j-1];
        }
        if(pattern[j] ==pattern[i])
            j++;
        //else j = 0;
        lps[i] = j;
    }
    return lps;
}

vector<int>computeLps(const string& pattern){
    vector<int>lps(pattern.size()); //p 记录 longest proper prefix which is also a suffix. 
    for(int i = 1; i<pattern.size(); i++){ // ** i start from 1
        while(j>0 && pattern[j]!= pattern[i]){
            j = lps[j-1];
        }
        j = lps[i] = j+ (pattern[j] ==pattern[i]);
    }
    return lps;
}


void kmp2(const string& pattern, const string& text, vector<int>&res){
    string combine = pattern + "@" + text;
    int pattern_size = pattern.size();
    vector<int>lps(combine.size(), 0);
    
    int j = 0; 
    for(int i = 1; i < combine.size(); ++i){
        while(j > 0 && combine[i]!=combine[j])
            j = lps[j-1];
        if (combine[i] == combine[j])
            ++j;
        lps[i] = j;
    }
    for(int i = pattern.size()+1; i<combine.size(); ++i){
        if(lps[i] == pattern.size()){
            cout<<"find match at text index "<< i - 2*pattern_size<<endl;
            res.push_back(i-2*pattern_size);
        }
    }
    return;
}
Title Time Space Difficulty Algorithm Note
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 的下一位
214. Shortest Palindrome O(n) O(n) Hard ⭐⭐ 可以把此题换一种问法: 以index0 开始最长palindrome 的长度, 最长的开始最长palindrome后面的reverse +s = 答案
  • KMP
  • 马拉车(manacher)
459. Repeated Substring Pattern O(n) O(n) Easy ⭐KMP return 条件
686. Repeated String Match O(n+m) O(n) Medium ⭐⭐
  • Kmp
  • rabin-karp algorithm, rolling hash
796. Rotate String O(n) O(1) Easy ⭐ 两种kmp的解,
  • 686. Repeated String Match一样, 详见686的C++ code 解释
  • pattern = B, text = A + A, 看text中有没有pattern
  • Rabin-Karp Algorithm (rolling hash)
1392. Longest Happy Prefix O(n) O(n) Hard Easy KMP, Rabin-Karp Algorithm (rolling hash)
1397. Count Number of Teams O(m*n) O(m) Hard DFS /DP + KMP Hard problem💥  
1408. String Matching in an Array O(n) O(n) Easy KMP, Rolling Hash
2800. Shortest String That Contains Three Strings O(a+b+c) O(a+b+c) Medium
3008. Find Beautiful Indices in the Given Array II O(n+ max(na, nb)) O(na+nb) Hard ⭐ KMP + Two pointers
3031. Minimum Time to Revert Word to Initial State II O(n) O(n) Hard ⭐⭐⭐ kmp, z function
3036. Number of Subarrays That Match a Pattern II O(mn) O(n) Hard

Manacher

complexity O(n),

/*
https://segmentfault.com/a/1190000008484167

manacher 算法:
建一个新的string 开头用$, 结尾用^(为了防止越界), 中间用#
这样可以把偶回文 和 奇回文 都转化成奇数,比如
如此,s 里起初有一个偶回文abba和一个奇回文opxpo,被转换为#a#b#b#a#和#o#p#x#p#o#,长度都转换成了奇数。

p[i] 表示以i为中小心的最长回文半径

i	        0	1	2	3	4	5	6	7	8	9	10	11	12	13	14	15	16	17	18	19  20 
s_new[i]	$	#	a	#	b	#	b	#	a	#	h	#	o	#	p	#	x	#	p	#   ^
p[i]		1	1   2	1	2	5	2	1	2	1	2	1	2	1	2	1	4	1	2	1   
两个int mx,和id, right 代表以 center 为中心的最长回文的右边界,也就是mx = center + p[center]。
mx是在当前回文右侧外的第一个点 mx点不包括在当前回文内


假设我们现在求p[i],也就是以 i 为中心的最长回文半径,如果i < mx:
if (i < right)  
    p[i] = min(p[2 * center - i], right - i);

2 * center - i为 i 关于 center 的对称点 ( j+i = 2*center),而p[j]表示以 j 为中心的最长回文半径,
因此我们可以利用p[j]来加快查找。

e.g1 . min(p[2 * center - i], right - i);
比如  c b c d c b z
           -   - | right 
          center     
       p[第一个b] = 3
第二个b的
    p[2 * center - i] =  p [第一个b] = 3, 现在以b 作为中心,右侧没有c,所以 不能等于 3
    right - i = 1   ✅

e.g2. min(p[2 * center - i], right - i);
比如  a b c d c b a d
           -   _   | right 
          center     
还是在 第二个b 点    
p[2 * center - i] =  p [第一个b] = 1,✅
right - i =  2 
*/ 

string manacher(const string& s){
    string s_new;
    init(s, s_new);
    vector<int>p(s_new.size());
    int right = -1, center = -1; 
    int max_len = -1, max_center = -1;
    for(int i = 1; i<s_new.size()-1; ++i){
        if(i < right){
            p[i] = min(p[2*center - i], right - i);
        } else{
            p[i] = 1;
        }
        while(s_new[i + p[i]] == s_new[i-p[i]] )
            ++p[i];
        if (p[i] > right){
            right = p[i];
            center = i;
        }
        if (p[i] > max_len){
            max_len = p[i];
            max_center = i;
        }
    }
    return s.substr((max_center - max_len)/2, max_len - 1);
}

void init(const string& s, string& res){
    res = "$#";
    for(auto c: s){
        res  +=  c;
        res += '#';
    }
    res += "^";
}
Title Time Space Difficulty Algorithm Note
005.Longest Palindromic Substring O(n) O(n) Medium ⭐ manacher(马拉车算法)
214. Shortest Palindrome O(n) O(n) Hard ⭐ 可以把此题换一种问法: 以index0 开始最长palindrome 的长度, 最长的开始最长palindrome后面的reverse +s = 答案
647. Palindromic Substrings O(n) O(n) Medium ⭐⭐⭐ sum(sum(dp, [])) sum 2d array
  • manacher(马拉车算法)
  • DP

Breadth-First Search

Title Time Space Difficulty Algorithm Note
102. Binary Tree Level Order Traversal O(n) O(n) Medium
103. Binary Tree Zigzag Level Order Traversal O(n) O(n) Medium
117. Populating Next Right Pointers in Each Node II O(n) O(1) Medium Traverse through next instead of Traverse from top to down
269. Alien Dictionary O(n) O(1) Medium ⭐⭐⭐Topological sort
310. Minimum Height Trees O(n) O(n) Medium
743. Network Delay Time O(E *logV) O(E + V) Medium Dijkstra's Algorithm
787. Cheapest Flights Within K Stops O(E * logV) O(E + V) Medium ⭐⭐⭐ Dijkstra's Algorithm
1091. Shortest Path in Binary Matrix O(n^2) O(n^2) Medium
1197. Minimum Knight Moves O(n*m) O(n*m) Hard

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不同左右边界值
  • Union Find
169. Majority Element O(n) O(1) Easy
189. Rotate Array O(n) O(1) Easy
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
370. Range Addition O(n) O(n) Medium prefix array
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
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
845. Longest Mountain in Array O(n) O(1) Medium 🐸
918. Maximum Sum Circular Subarray O(n) O(1) Medium 🎅🎅 Kadane's algorithm
957. Prison Cells After N Days O(k*(N, 2^k)) O(k) Medium
974. Subarray Sums Divisible by K O(n) O(n) Medium ⭐⭐C++ 余数可能是负数,python的余数不会是负数
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
1583. Count Unhappy Friends O(n^2) O(n) Medium bad description, better description-for-a-bad-framed-question-%3A()
2373. Largest Local Values in a Matrix O(n) O(1) Easy
3030. Find the Grid of Region Average O(9*n*m) O(n*m) Medium
                                                                

Greedy

Title Time Space Difficulty Algorithm Note
011. Container With Most Water O(n) O(1) Medium
045. Jump Game II O(n) O(1) Hard ⭐⭐⭐
  • greedy
  • DP
Similar Question:
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 ⭐⭐ multiset, priorty_queue 类似的题
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 🎅🎅 边界选最大的两个,而不是一大一小
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 💜🎅
1007. Minimum Domino Rotations For Equal Row O(n) O(1) Medium
1024. Video Stitching O(n) O(n) Hard ⭐⭐⭐
  • greedy
  • DP
Similar Question:
1249. Minimum Remove to Make Valid Parentheses O(n) O(1) Medium Stack
1326. Minimum Number of Taps to Open to Water a Garden O(n) O(n) Hard ⭐⭐⭐
  • sort
  • greedy
  • DP
Similar Question:
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
1833. Maximum Ice Cream Bars O(nlogn) O(1) Medium
1846. Maximum Element After Decreasing and Rearranging O(n) O(n) Medium
1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number O(n^2) O(n) Medium
2366. Minimum Replacements to Sort the Array O(n) O(1) Hard
2340. Minimum Adjacent Swaps to Make a Valid Array O(n) O(n) Medium ⭐⭐⭐
2350. Shortest Impossible Sequence of Rolls O(n) O(K) Hard
2375. Construct Smallest Number From DI String O(1) O(1) Medium
2918. Minimum Equal Sum of Two Arrays After Replacing Zeros O(n) O(1) Medium
3002. Maximum Size of a Set After Removals O(n) O(n) Medium ⭐set difference
3035. Maximum Palindromes After Operations O(nlogn) O(n) Medium ⭐Count Pair
                                                                

Tree

//
void helper(TreeNode* root, vector<int>&res){
    if(!root) {return;}
    //res.push_back(root->val); pre order
    helper(root->left, res);
    //res.push_back(root->val); in order
    helper(root->right, res);
    //res.push_back(root->val); post order
    return;
}


//Inorder Traversal
//stack, 
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        TreeNode *cur = root;
        if(!root) return {};
        vector<int>res;
        stack<TreeNode *>stk;
        while(cur || !stk.empty()){ //cur 比如只有右面的,stack只存之后需要返回的 ; !stk.empty() 是看是不是有接下来返回的node,比如到最左侧node 需要返回
            if(cur){
                //res.push_back(cur->val); pre order, post order
                stk.push(cur);
                cur = cur->left;
            }else{//切换到之前的top
                cur = stk.top(); stk.pop();
                res.push_back(cur->val); // in order;
                cur = cur->right;
            }
        }
        return res;
    }
};

//Postorder: 先right 再left 最后reverse
//postorder 是把tree mirror后的pre order
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; //cover所有没有left tree的点
            }else{
                TreeNode* pre = cur->left;
                while(pre->right && pre->right!=cur)
                    pre = pre->right;
                if(pre->right){ //表示cur的left 已经全部visit完成,又回到cur了
                    //res.push_back(cur->val); //Inorder
                    pre->right = NULL;  //cover剩下其他的点
                    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的地址并没有删除
 }

BIT tree (Binary Index Tree)

/*

array 3 2 -1 6 5 4 -3 3 7 2 3
index 0 1  2 3 4 5  6 7 8 9 10

BIT Tree �Visulation (tree 的index = array index + 1)

                0 (0)
        /      |        |      \
    /       /         \         \           
3 (0,0)  5 (0,1)    10 (0,3)         19 (0,7)     -> 存的是它左侧所有属于同一个parent的leaf 和 
    1         2         4                 8            比如 tree index = 6 存的是 array (4,5) 的点
            |        |     \          |     \
        -1 (2,2)  5(4,4)   9 (4, 5) 7 (8,8)  9 (8, 9)
            3        5       6      9          10        
                                |                 | 
                            -3 (6,6)         3 (10,10)
                                7               11
            

Get Parent (把最右侧的bit remove掉,比如 1010 -> 1000, 111->110)
1) 2's complement (= negate 所有bit + 1)
2) AND it with original number 
3) subtract from original number

Parent(7) 
1) 7 (111) complement + 1 = 000 + 1 = 001 
2) 111 & 001 = 001 
3) 111 - 001 = 110 (6) 

Get Next: 
1) 2's complement  (= negate 所有bit + 1)
2) AND it with original number 
3) Add from original number

Get Next(2) move 到最右侧的bit + 1位,且把后面bit 全部抹掉  0011 -> 0100, 0101 -> 0110, 0110 -> 1000
1) 的 2's complement 0011 的negate 是1100  + 1 = 1101
2) 1100 & 0011 = 1
3) 0011 + 1 = 0100


*/



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
Similar Question:
314. Binary Tree Vertical Order Traversal O(n) O(n) Medium minRemoveToMakeValid
426. Convert Binary Search Tree to Sorted Doubly Linked List O(n) O(n) Medium
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
1110. Delete Nodes And Return Forest O(n) O(n) Medium
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 ⭐⭐⭐相当于问queries[i] 前面有几个数 思路 How to Build FenwickTree Double BIT tree size, move forward
Similar Question:
2458. Height of Binary Tree After Subtree Removal Queries O(n) O(n) Hard ⭐⭐⭐ 把左边高度带到右边,把右边高度带到左边, lru_cache, @functools.cache
1825. Finding MK Average O(nlogn) O(n) Hard BIT, Fenwick Tree
Similar Question:
                                                                

Math

Title Time Space Difficulty Algorithm Note
007. Reverse Integer O(1) O(1) Easy
009. Palindrome Number O(1) O(1) Easy
50. Pow(x, n) O(logN) O(1) Medium Divide Conquer
012. Integer to Roman O(n) O(1) Medium
013. Roman to Integer O(n) O(1) Easy
390. Elimination Game O(logn) O(1) Meidum
782. Transform to Chessboard O(n^2) O(1) Hard
829. Consecutive Numbers Sum O(sqrt(n)) O(1) Hard
964. Least Operators to Express Number O(logn) O(logn) Hard 🎅🎅🎅
1041. Robot Bounded In Circle O(n) O(1) Medium
1359. Count All Valid Pickup and Delivery Options O(n) O(1) 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
1808. Maximize Number of Nice Divisors O(log(n)) O(1) Hard
1823. Find the Winner of the Circular Game O(n) O(1) Medium Thinking Process
1837. Sum of Digits in Base K O(logk) O(1) Easy
2344. Minimum Deletions to Make Array Divisible O(O(nlogn + m + gcd) , where gcd = log(max(numsDivide)) O(1) Hard ⭐ gcd, python filter
2335. Minimum Amount of Time to Fill Cups _O(1) O(1) Easy

Trie

Title Time Space Difficulty Algorithm Note
588. Design In-Memory File System
  • ls : O(n)
  • mkdir : O(n + klogk)
  • addContentToFile : O(n)
  • readContentFromFile : O(n)
O(n) Hard
1268. Search Suggestions System O(M) O(n) Medium
3045. Count Prefix and Suffix Pairs II O(n*max(l)) O(n*max(l)) Hard ⭐⭐⭐⭐
  • Trie c++ unordered_map insert 如果key 存在不会改变现有的key,value pair, python Trie and := walrus operator,
  • rolling hash
  • z-function

String

Title Time Space Difficulty Algorithm Note
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)
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
065. Valid Number O(n) O(1) Hard
067. Add Binary O(n) O(1) Easy string 加法, 跟415. Add Strings306. Addictive Number 类似
068. Text Justification O(n) O(1) Hard 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))
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
408. Valid Word Abbreviation O(n) O(1) Easy
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
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
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
681. Next Closest Time O(1) O(1) Medium
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
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
953. Verifying an Alien Dictionary O(n*l) O(1) Easy
1374 Generate a String With Characters That Have Odd Count O(n) O(1) Easy
1410. HTML Entity Parser O(n) O(t) Medium
1417. Reformat The String O(n) O(1) Easy
2272. Substring With Largest Variance O(n) O(1) Hard ⭐⭐Kadane's Algorithm
                                                         

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()
1835. Find XOR Sum of All Pairs Bitwise AND O(n) O(1) Hard
2317. Maximum XOR After Operations O(n) O(1) Medium ⭐ ✏️ c++ reduce
2354. Number of Excellent Pairs O(n) O(1) Hard bits(num1 OR num2) + bits(num1 AND num2) = bits(num1) + bits(num2)
2506. Count Pairs Of Similar Strings O(n) O(n) Easy
2897. Apply Operations on Array to Maximize Sum of Squares O(n) O(1) Hard ⭐⭐
3022. Minimize OR of Remaining Elements Using Operations O(n) O(1) Hard ⭐⭐⭐
                         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
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可以
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
249. Group Shifted Strings O(n) O(n) Medium
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
325. Maximum Size Subarray Sum Equals k O(n) O(1) Medium
Similar Question:
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
409. Longest Palindrome O(n) O(1) Easy 可以用std::count, 或者可以来回flip map, 当map位true +2
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
525. Contiguous Array O(n) O(n) Medium 😍把所有的0变成-1, 所以当有sum[i,j] = 0时 => [i,j]中有同等的1 和 0,
Similar Question:
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出现很多遍)
Similar Question:
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
705. Design HashSet O(1) O(n) Easy ⭐⭐
706. Design HashMap O(1) O(n) Easy ⭐⭐⭐ list find_if, remove_if
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是否满足条件, 满足的话更新结果
1010. Pairs of Songs With Total Durations Divisible by 60 O(n) O(1) Medium
1152. Analyze User Website Visit Pattern O(n^4) O(n) Medium
1347. Minimum Number of Steps to Make Two Strings Anagram O(n) O(n) Medium
1418 Display Table of Food Orders in a Restaurant O(n + tlogt + flogf) O(n) Medium ✏️C++ transform
1711. Count Good Meals O(n) O(n) Medium
2183. Count Array Pairs Divisible by K O(n^2) O(n) Hard
2347. Best Poker Hand O(1) O(1) Easy ❌ Python Switch Case
2357. Make Array Zero by Subtracting Equal Amounts O(n) O(n) Easy
[2365. Task Scheduler II O(n) O(n) Easy ⭐ Python Counter 相加
2364. Count Number of Bad Pairs O(n) O(n) Medium
2365. Task Scheduler II O(n) O(n) Medium ⭐ 公式变形
2367. Number of Arithmetic Triplets O(n) O(n) Easy
2374. Node With Highest Edge Score O(n) O(n) Medium
2661. First Completely Painted Row or Column O(n*m) O(n*m) Medium
2870. Minimum Number of Operations to Make Array Empty O(n) O(1) Medium
                                                                                                                                                           

sliding windows

summary
sliding windows: windows都是看以当前字母结尾的window. 比较对象target(长度为len), 被比较对象s2
  • 可以记录当前substring的开始位置,
  • 用数字记录substring的长度
  • 用hashset和两个pointer记录当前windows的长度
  • map+pointer 1 map + 2 pointers: map先记录比较对象 map[s2[i]]++, 再对被比较对象 所有字母 / key出现 , map[s2[i]]--
    • 固定windows 长度
      • 一个pointer count, 表示固定windows 内多少个满足条件
      • 比较条件: if --map[s2[i]] >= 0 , --count,
      • >满足条件:if count == 0 把起点i-len + 1添加进结果
      • 移动窗口条件:if i>=len-1, map[s2[i-len+1]]++
    • 不固定长度.
      • 一个pointerleft记录左侧windows 起始点
      • 满足条件: if i - left + 1 == len , 把起点left添加进结果
      • 移动窗口条件: while(map[s2[i]])<0 表示现windows中 s2[i] 个数 大于 target中个数, or target中没有 s2[i], 下面两种移动方式都可以
        • 方式一: while(map[s2[i]]< 0) map[s2[left++]]++。e.g.1 target=abc, s2=ababc, 在index=2, 第二个a, 有两个a 多于target中个数, e.g. 2 target=abc, s2=abdabc, 在index=2, d在target中没有出现
        • 方式二: while(map[s2[start++]-'a']++ >= 0); 把之前所有满足的都移走,
    • 可以用两个map,一个map记录比较对象(T),一个记录被比较对象(S),
      • 用一个count记录S中T出现的个数 或者一个left记录左侧边界
      • count == 0 or i - left + 1 == len, 满足情况,,
      比如30题 Substring with Concatenation of All Words, 76题 Minimum Window Substring
      两个题区别是30不能包括多余的string (不可以sdict[s[start]] > tdict[s[start]]), 76是允许的
Title Time Space Difficulty Algorithm Note
003. Longest Substring Without Repeating Characters O(n) O(n) Medium ⭐⭐Sliding Windows
030. Substring with Concatenation of All Words O((m+n)*k) O(n*k) Hard ⭐⭐⭐Sliding Windows
076. Minimum Window Substring O(n) O(k) Hard ⭐⭐⭐
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的窗口
259. 3Sum Smaller O(n^2) O(1) Medium ⭐⭐
346. Moving Average from Data Stream O(1) O(n) Easy
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) Medium ⭐⭐⭐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
567. Permutation in String O(n) O(1) Medium ⭐⭐⭐sliding Window
643. Maximum Average Subarray I O(n) O(1) Easy 最简单的sliding window
683. K Empty Slots O(n) O(n) Hard ⭐⭐⭐
  • Sliding windows: 只能固定长度
  • MinQueue
  • BIT, 第bulbs[i]个灯泡和 第bulbs[i]-k-1 相差1,或第bulbs[i]个灯泡和 第bulbs[i]+ k + 1相差1

Similar Question
713. Subarray Product Less Than K O(n) O(1) Medium 🔍 Sliding Window
862. Shortest Subarray with Sum at Least K O(n) O(k) Hard
763. Partition Labels O(n) O(n) Medium hashmap/sliding windows
904. Fruit Into Baskets O(n) O(1) Medium Rephrase Question: return the longest subarray's length which only contains 2 different elements
numSubarraysWithSum. Binary Subarrays With Sum O(n) O(1) Medium
992. Subarrays with K Different Integers O(n) O(1) Medium
1004. Max Consecutive Ones III O(n) O(1) Medium
1234. Replace the Substring for Balanced String O(n) O(t) Medium
1248. Count Number of Nice Subarrays O(n) O(k) Medium
1358. Number of Substrings Containing All Three Characters O(n) O(1) Medium
1425. Constrained Subsequence Sum O(n) O(1) Medium
1493. Longest Subarray of 1's After Deleting One Element O(n) O(1) Medium
1838. Frequency of the Most Frequent Element O(logn) O(1) Medium
1839. Longest Substring Of All Vowels in Order O(n) O(1) Medium
// 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( map[s2[i]-'a'] < 0) map[s2[left++]-'a']++;
                /* or

                //correct
                while( map[s2[left] - 'a']++ >= 0 )
                    ++left;
                ++left;

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

                */

            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
*/

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的长, 非经典dp
  • Stack
042. Trapping Rain Water O(n) O(1) Hard Greedy/Descending Stack
071. Simplify Path O(n) O(n) Medium ✏️ Split stringstream + getline 可以处理连续的delimiter 比如delimiter是/, 可以parse//c/d//cd, vectro<string>join
084. Largest Rectangle in Histogram O(n) O(n) Hard
  • ⭐__stack__: ascending stack
  • Divide Conquer:最小的area来自左面,或者来自右面,或者来自area contain middle point
085. Maximal Rectangle O(n*m) O(m) Hard
  • stack:与084. 类似
  • 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/Medium ⭐ 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
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了
503. Next Greater Element II O(n) O(n) Medium
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
1063. Number of Valid Subarrays O(n) O(n) Hard Ascending Stack
Similar Question:
1762. Buildings With an Ocean View O(n) O(n) Medium
2281. Sum of Total Strength of Wizards O(n) O(n) Hard
Similar Question:
                                                  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了, ✏️ vectormake_heap, heap_push, pop_heap
024. Swap Nodes in Pairs O(n) O(1) Easy ⭐ recursion 解
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 priority_queue vs multiset comparator
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 remove cur->next
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里面
1171. Remove Zero Sum Consecutive Nodes from Linked List O(n) O(n) Medium
1836. Remove Duplicates From an Unsorted Linked List O(n) O(n) Medium
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()
362. Design Hit Counter O(1) O(1) Medium Should consider remove performance

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相反
253. Meeting Rooms II O(nlogn) O(n) Medium ⭐⭐
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 当前最小值
759. Employee Free Time O(klogk) O(k) Hard Heap O(Nlogk) or SweepLine O(klogk)
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, Multiset Comparator
1046. Last Stone Weight O(nlogn) O(n) Easy
1834. Single-Threaded CPU O(nlogn) O(n) Medium
2402. Meeting Rooms III O(mlogm + n + mlogn) O(n) Hard
2519. Count the Number of K-Big Indices O(nlogn) O(n) Hard
                                                 

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
1570. Dot Product of Two Sparse Vectors O(n) O(n) Medium
1750. Minimum Length of String After Deleting Similar Ends O(n) O(1) Easy
2337. Move Pieces to Obtain a String O(n) O(1) Medium
2348. Number of Zero-Filled Subarrays O(n) O(1) Medium
2781. Length of the Longest Valid Substring O(n^2) O(k) Hard
2825. Make String a Subsequence Using Cyclic Increments O(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 priority_queue vs multiset comparator
  • 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)
252. Meeting Rooms O(nlogn) O(1) Easy
274. H-Index O(n) O(n) Medium ❌counting Sort
315. Count of Smaller Numbers After Self O(nlogn) O(n) Hard MergeSort, BIT
Similar Question:
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
Similar Question:
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的时间由小到大
937. Reorder Data in Log Files O(nlogn) O(n) Medium stable_partition, string_view
910. Smallest Range II O(nlogn) O(1) Medium ⭐⭐⭐
1029. Two City Scheduling O(n) average O(n) Easy Greedy**,quick select
1170. Compare Strings by Frequency of the Smallest Character O(q+w) O(1) Mediem Count Sort
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
1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts O(hlogh + vlogv) O(1) Medium
1840. Maximum Building Height O(nlogn) O(1) Hard
1851. Minimum Interval to Include Each Query O(nlogn + qlogq) O(n) Hard
2268. Minimum Number of Keypresses O(n) O(1) Medium

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
528. Random Pick with Weight O((n*logn) O(n) Medium
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在乘法表中
715. Range Module O(n) O(n) Hard ⭐⭐⭐
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
    875. Koko Eating Bananas O(NlogW) O(1) Medium
    981. Time Based Key-Value Store O(nlogn) O(n) Medium
    1060. Missing Element in Sorted Array O((logN) O(1) Medium 🎅
    1385. Find the Distance Value Between Two Arrays O((n + m) * logm) O(1) Easy 🎅Binary Search, Two pointer
    1818. Minimum Absolute Sum Difference O((n * logn) O(n) Medium
    2055. Plates Between Candles O((max(q * logn, n)) O(n) Medium
    2358. Maximum Number of Groups Entering a Competition O(logN) O(1) Medium Math / Brain Teaser
    3048. Earliest Second to Mark Indices I O(mlogm) O(m) Medium ⭐⭐⭐ key: 根据bound,每次last_index 是需要更新的
    3049. Earliest Second to Mark Indices II O(mlogm) O(m) Hard ⭐⭐⭐
    • key: 需要看first_index, 尽早set to 0. 循环需要从后往前。
    • ✏️ c++ vector heap, 是max_heap, std::pop_heap 不会从vector中pop element, 需要再call pop_back
    3116. Kth Smallest Amount With Single Denomination Combination O(2^n * log(k)) O(2^n) Hard itertools.combinations, math.lcm
    3134. Find the Median of the Uniqueness Array O(nlogn) O(n) Hard


    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](https://leetcode.com/problems/recover-a-tree-from-preord er-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
    2265. Count Nodes Equal to Average of Subtree O(n) O(n) 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 😍
    339. Nested List Weight Sum O(n) O(n) 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能不能赢
    489. Robot Room Cleaner O(n*m) O(n*m) Hard ⭐⭐⭐
    515. Find Largest Value in Each Tree Row O(n) O(h) Medium ❌ DFS / BFS
    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
    694. Number of Distinct Islands O(m*n) O(m*n) Medium
    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
    1136. Parallel Courses O(V+E) O(V+E) Medium topological sort
    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
    1806. Minimum Number of Operations to Reinitialize a Permutation O(n) O(1) Medium Reverse
    2359. Find Closest Node to Given Two Nodes O(n) O(n) Medium
    2360. Longest Cycle in a Graph O(n) O(n) Hard
    2368. Reachable Nodes With Restrictions O(V+E) O(V+E) Medium BFS / DFS


    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
    Similar Question
    040. Combination Sum II O(n * n!) O(n) Medium
    Similar Question
    046. Permutations O(\n * n!) O(n) Medium
    Similar Question
    047. Permutations II O(\n * n!) O(n) Medium ⭐⭐⭐
    Similar Question
    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次

    Similar Question
    090. Subsets II O(n * 2^n) O(1) Medium ⭐⭐⭐ recursive(逻辑类似040. Combination Sum II) & 😍😍 iterative(插数)
    Similar Question
    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
    Similar Question
    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
    216. Combination Sum III O(k * C(n, k)) O(k) Medium 🔍Python itertools.combination
    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
    784. Letter Case Permutation _O(n * 2^n) _ O(1) Easy ✏️Python itertools.product
    1087. Brace Expansion O(n * l *log(n *l)) O(n * l) Medium
    2352. Equal Row and Column Pairs O(n^2) O(n^2) Medium suffix Trie / Python Zip

    Graph

    (注directed vs undirected 区别) undirected graph 设置global visited, directed graph 设置local visited

    Title Time Space Difficulty Algorithm Note
    133. Clone Graph O(N+M) O(N) Medium
    261. Graph Valid Tree O(V+E) O(V+E) Medium
    Similar Question
    277. Find the Celebrity O(n) O(1) Medium
    323. Number of Connected Components in an Undirected Graph O(V+E) O(V+E) Medium undirected graph connected component, union find
    332. Reconstruct Itinerary O(t! / (n1! * n2! * ... nk!)) O(t) Medium 😍⭐⭐⭐
    Similar Question
    499. The Maze III O(nlogn) O(n) Hard
    505. The Maze II O(mnlog(nn)) O(mn) Medium
    529. Minesweeper O(m * n) O(m + n) Medium ⭐⭐简单DFS,
    Similar Question
    547. Number of Provinces O(n^2) O(n) Medium ⭐⭐⭐ Union Find with Rank Heuristic / DFS, undirected graph 设置global visited, b/c A不能到B 不代表 B 不能到A
    Similar Question
    695. Max Area of Island O(m*n) O(m*n) Medium ✏️Python Complex number 表示四个DFS 方向
    Similar Question
    834. Sum of Distances in Tree O(n) O(n) Hard
    841. Keys and Rooms O(V+E) O(V+E) Medium
    947. Most Stones Removed with Same Row or Column O(k) O(k) Medium ⭐⭐
    Similar Question Union find
    994. Rotting Oranges O(m*n) O(m*n) Medium ⭐⭐ BFS乘以列的个数, 而不是行数
    Similar Question
    1245. Tree Diameter O(n) O(n) Medium
    1361. Validate Binary Tree Nodes O(n) O(n) Medium
    1466. Reorder Routes to Make All Paths Lead to the City Zero O(n) O(n) Medium ⭐⭐⭐ no cycle
    Similar Question
    1494. Parallel Courses II O(2^n) O(2^n) Hard
    1786. Number of Restricted Paths From First to Last Node O(M*(V + ElogV)) O(n) Hard ⭐⭐⭐ Dijkstra's Algorithm, Floyd–Warshall algorithm
    Similar Question
    1971. Find if Path Exists in Graph O(V + E) O(V +E) Easy ⭐Union Find
    2101. Detonate the Maximum Bombs O(V*(V+E)) O(V+E) Medium ⭐⭐⭐ directed graph, 每个dfs 前设置visited, b/c A不能到B 不代表 B 不能到A , count the max number of child from a node
    Similar Question
    2050. Parallel Courses III O(n + e) O(n + e) Hard ⭐⭐⭐
    2065. Maximum Path Quality of a Graph O(V+E + 4^10) O(V + E) Medium
    2092. Find All People With Secret O(M*log M + N) O(M + N) Hard ⭐⭐⭐ undirected graph Union Find
    2097. Valid Arrangement of Pairs O(M+N) O(M + N) Hard ⭐⭐⭐ directed graph Eulerian Path
    Similar Question
    2115. Find All Possible Recipes from Given Supplies O(V+E) O(V + E) Medium ⭐⭐⭐ directed graph Union Find,topoloigical sort
    2316. Count Unreachable Pairs of Nodes in an Undirected Graph O(V+E) O(V + E) Medium ⭐⭐⭐ undirected graph Union Find
    2204. Distance to a Cycle in Undirected Graph O(E + n) O(n) Hard ⭐⭐⭐ undirected graph 用indegree 来 detect cycle
    Similar Question
    2421. Number of Good Paths O(E + nlogn) O(n) Hard ⭐⭐⭐ undirected graph union find
    Similar Question Union find
    2642. Design Graph With Shortest Path Calculator O(M*(V + ElogV)) O(n) Hard ⭐⭐⭐ Dijkstra's Algorithm, Floyd–Warshall algorithm
    Similar Question
    2685. Count the Number of Complete Components O(V+E) O(V+E) Medium ⭐⭐⭐ c++ all_of, 如果每个都在cycle中, 每个node的outgoing size = 总共的node - 1
    2858. Minimum Edge Reversals So Every Node Is Reachable O(n) O(n) Hard ⭐⭐⭐ no cycle
    Similar Question
    2976. Minimum Cost to Convert String I O(26^3) O(26^2) Medium ⭐⭐⭐Floyd-Warshall
    2977. Minimum Cost to Convert String II O(n^3) O(n^2) Hard ⭐⭐⭐Floyd-Warshall
    3108. Minimum Cost Walk in Weighted Graph O(V*(V+E)) O(V+E) Medium ⭐⭐⭐ undirected graph union find
    3123. Find Edges in Shortest Paths O(V + ElogV) O(V+E) Hard ⭐⭐⭐ undirected graph union find

    undirected graph

    //undirected graph
    //detect cycle
    
    bool dfs(unordered_map<int, unordered_set<int>>&graph, vector<int>&visited, int cur, int parent){
        //cout<<" in "<<cur<<endl;
        visited[cur] = 1;
        for(auto nxt: graph[cur]){
            if(nxt == parent) continue;
            if (visited[nxt]) return false;
            if (!dfs(graph, visited, nxt, cur)){
                return false;
            }
        }
        return true;
    }
    
    //detect cycle node 
    int find_cycle(unordered_map<int,unordered_set<int>>&graph, int cur, int parent, vector<int>&visited, unordered_set<int>&cycle){
        if(visited[cur]){
            return cur;
        }
        visited[cur] = 1;
        for(auto &nxt: graph[cur]){
            if(nxt == parent) continue;
            int cycle_node = find_cycle(graph, nxt, cur, visited, cycle);
            if(cycle_node >= 0){
                cout<<" find cycle node " << cur<<endl;
                cycle.insert(cur);
            }
            if(cycle_node >= 0){ 
                //比如 1-> 2 -> 3 -> 4 -> 1, 当4 ->1 返回1, 当 cur = 1 时候, cycle_node = 1是cycle 的起点
                return cur == cycle_node? -1: cycle_node;
            }
        }
        return -1;
    }
    
    
    //BFS find cycle node
    void find_cycle(int n, vector<vector<int>>& edges) {
        unordered_map<int, unordered_set<int>>graph;
        vector<int>degree(n,0);
        for(auto & edge: edges){
            graph[edge[0]].insert(edge[1]);
            graph[edge[1]].insert(edge[0]);
            ++degree[edge[0]]; 
            ++degree[edge[1]];
        }
        queue<int>q;
        for(int i = 0; i<n; ++i){
            if(degree[i] == 1) {
                q.push(i);
            }
        }
        while(!q.empty()){
            int top = q.front(); q.pop();
            for(auto nxt: graph[top]){
                if(--degree[nxt] == 1){
                    q.push(nxt);
                }
            }
        }
        vector<int>res(n, 2*n);
        for(int i = 0; i < n; ++i){
            if(degree[i]>1){
                cout<<" find cycle node " << i<<endl;
            }
        }
    }
    


    DFS 是看有没有path,DP是看有几个path, 如果不要连续的dp[i][j] = max(dp[i-1][j], dp[i][j-1])

    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
    718. Maximum Length of Repeated Subarray O(m * n) O(min(m, n)) Medium 🔍 DP
    类似的题:
    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 类似题:  
    827. Making A Large Island O(n^2) O(n^2) Hard
    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
    1048. Longest String Chain O(n*(logn + L^2)) O(n) Medium
    1062. Longest Repeating Substring O(n*m) O(n) Medium ⭐⭐⭐binary search (while l<=r, r=r-1, l=l+1, 返回r) + DP
    Similar Question
    1092. Shortest Common Supersequence O(n*m) O(max(n,m)) Hard ⭐⭐⭐ Similar Question
    1143. Longest Common Subsequence O(n*m) O(n) Medium ⭐⭐⭐ Similar Question
    1235. Maximum Profit in Job Scheduling O(nlogn) O(n) Hard  
    1277. Count Square Submatrices with All Ones O(m*n) O(1) Medium  类似的题:
    1335. Minimum Difficulty of a Job Schedule O(dn) O(n) Hard
    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 🎅 
    1531. String Compression II O(n^2*k) O(n*k) Hard 🎅🎅 
    1824. Minimum Sideway Jumps O(n) O(1) Medium
    2369. Check if There is a Valid Partition For The Array O(n) O(1) Medium
    2466. Count Ways To Build Good Strings O(n) O(1) Medium
    2533. Number of Good Binary Strings O(n) O(n) Medium
    2370. Longest Ideal Subsequence O(kn) O(1) Medium ⭐ TopDown
    2771. Longest Non-decreasing Subarray From Two Arrays O(n) O(n) Medium ⭐⭐⭐
    3003. Maximize the Number of Partitions After Operations O(2^26n) O(2^26n) Hard TopDown, Bottomup
    3149. Find the Minimum Cost Array Permutation O(n^2*2^n) O(n*2^n) Hard TopDown, Bottomup
                                                                    


    Design

    Title Time Space Difficulty Algorithm Note
    146. LRU Cache O(1) O(k) Medium
    359. Logger Rate Limiter O(1) O(n) Easy
    380. Insert Delete GetRandom O(1) O(1) O(1) Medium 🎅🎅
    460. LFU Cache O(1) O(1) Hard ⭐⭐⭐ remove element from list 不会invalidate iterator
    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
    2349. Design a Number Container System ctor: O(1)
    change: O(logn)
    find: O(1)
    O(n) Medium Python SortedList
    2353. Design a Food Rating System ctor: O(nlogn)
    changeRating: O(logn)
    highestRated: O(1)
    O(n) Medium Python SortedList


    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

    Concurrency

    • c++ parameter to thread always pass by value. need std::ref(x) to pass by reference. Thread cannot be copied cannot only be moved
    • Future .get() 只能被call 一次,call多次会crash
    • c++ wait lambda是release的条件,python 的wait_for也是release的条件

    Python

    • 第一个Lock.acquire() 不会block thread, 第二个Lock.acquire() 会block
    • 第一个Event.wait() 会block thread, thread process 当 Event.set()(Set the internal flag to true), 用完一次后需要 Event.clear()(Reset the internal flag to false). 需要先clear 才能再次set
    • Semphore 初始值默认1, Semphore.acquire() decrement value, thread block 当 value == 0, Semphore.release() increent value
    • Python Barrier release 当初始的counter == barrier.wait()的call时候
    Title Time Space Difficulty Algorithm Note
    1114. Print in Order O(1) O(1) Easy Python的多种写法
    1115. Print FooBar Alternately O(n) O(1) Medium Python的多种写法
    1116. Print Zero Even Odd O(n) O(1) Medium
    1117. Building H2O O(n) O(1) Medium ⭐⭐
    1188. Design Bounded Blocking Queue O(n) O(n) Medium ⭐⭐⭐ 解释python 为什么notify 需要before lock.release
    1195. Fizz Buzz Multithreaded O(n) O(1) Medium ⭐ ✏️ c++ python thread lambda function
    1226. The Dining Philosophers O(n) O(1) Medium ⭐⭐ ✏️ C++ semaphore 写法
    1242. Web Crawler Multithreaded O(V+E) O(V) Medium ⭐⭐⭐ vector<thread>emplace_back 后就开始工作了
    1279. Traffic Light Controlled Intersection O(n) O(n) Easy ❌ bad question description

    release increment value

    #下面code thread 1 先run, thread 2后run
    
    # Condition, 必须 notifyAll() under with self.cv:
    cv = threading.Condition()
    isFoo = True
    
    def thread1():
        with cv:
            cv.wait_for(lambda: isFoo) #when isFoo = True, acquire lock and continue work 
            """
            do some thing
            """ 
            print("先print")
            global isFoo
            isFoo = not isFoo
            cv.notify()
    
    def thread2():
        with cv:
            cv.wait_for(lambda: not isFoo)  #when isFoo = False, acquire lock and continue work 
            """
             do some thing
             """     
            print("后print")
            global isFoo
            isFoo = not isFoo
            cv.notify()
    
    t = threading.Thread(target = thread1).start()
    t2 = threading.Thread(target = thread2).start()
    
    
    
    # Event
    
    # Event.set()
    # Event.clear()
     
    # An event manages a flag that can be set to true with the set() method and
    # reset to false with the clear() method. 
    # The wait() method blocks until the flag is true. The flag is initially false.
    
    e = (threading.Event(), threading.Event())
    e[0].set()
    
    def thread1():
        e[0].wait() # wait until e[0] flag is true by set, pass because e[0] has been set
        """
        do some thing
        """ 
        print("先print")
        e[1].set() 
        e[0].clear() #set e[0] flag false
    
    def thread2():
        e[1].wait() # wait until e[1] flag is true by set
        """
        do some thing
        """
        print("后print")
        e[0].set() 
        e[1].clear() #set e[1] flag false
    
    t = threading.Thread(target = thread1).start()
    t2 = threading.Thread(target = thread2).start()
    
    """
    Barrier: 
    
    used as to wait for a fixed number of thread before any particular thread can proceed
    
    keep track of wait() call. If wait () call大于 number of thread initialized.
    
    wait(): Wait until notified or a timeout occurs. 当代n 个 thread 到wait 后一起释放 工作, simultaneously released.
            比如 n = 5, 现在有3个到了wait, 等待另外两个到wait 才工作
    
    """
    
    
    barrier = threading.Barrier(2)
    
    i = 0
    
    def run(id):
        print("enter ",id)
        barrier.wait()
        print("process  ",id)
    		
    thread1 = threading.Thread(target=run, args=(1,)).start()
    
    time.sleep(5)
    thread2 = threading.Thread(target=run, args=(2,)).start()
    
    """
    先打印 enter id = 1, 然后wait
    5 秒后,
    打印 enter id = 2, release all simultaneously
    print :  process 2
             process 1
    
    """
    
    
    
    
    """
    Lock, default is release 
    
    lock.acquire()
    lock.release()
    """
    
    e =  (threading.Lock(), threading.Lock())
    e[1].acquire()
    
    def thread1():
        e[0].acquire()
        """
        do some thing
        """ 
        print("先print")
        e[1].release()
    
    def thread2():
        e[1].acquire() 
        """
        do some thing
        """
        print("后print")
        e[0].release
    
    t = threading.Thread(target = thread1).start()
    t2 = threading.Thread(target = thread2).start()
    
    # Semaphore 
    """
    Semaphore(value=1)
    
    acquire()
    release(n=1)
    
    A semaphore manages an internal counter which is decremented by each acquire() call 
    and incremented by each release() call. 
    The counter can never go below zero; 
    when acquire() finds that it is zero, it blocks, waiting until some task calls release().
    
    """
    
    e =  (threading.Semaphore(1), threading.Semaphore(1))
    e[1].acquire()
    
    def thread1():
        e[0].acquire()
        """
        do some thing
        """ 
        print("先print")
        e[1].release()
    
    def thread2():
        e[1].acquire() 
        """
        do some thing
        """
        print("后print")
        e[0].release
    
    t = threading.Thread(target = thread1).start()
    t2 = threading.Thread(target = thread2).start()
    
    """
    Lock vs Semaphore
    1. Locks cannot be shared between more than one thread processes but semaphores 
        can have multiple processes of the same thread.
    2. Only one thread works with the entire buffer at a given instance of time 
        but semaphores can work on different buffers at a given time.
    3. Lock takes care of the locking system however semaphore takes care of the signal system.
    4. we consider lock as an object whereas we consider semaphore as an integer with values.
    5, The lock has 2 principles that are acquire and release however semaphore has two principles
         which are wait() and signal().
    6. The lock does not have any subtypes of its own however semaphore has 2 subtypes.
         They are binary semaphores and counting semaphores.
    7. Locks can have multiple programs at a time but it cannot perform them all at the same time.
         Whereas semaphores can have multiple programs and can perform them all at the same time. 
    
    """
    

    leetcode's People

    Contributors

    mycuteguineapig avatar

    Stargazers

     avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

    Watchers

     avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

    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.