Cram Mode
Each problem (and learning guide) is collapsed to its key facts. Expand for the full solution. Great for a last-minute pass.
Arrays & Hashing (13)
○ 1. Two Sum Easy
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
std::unordered_map<int, int> umap;
int n = nums.size();
for (int i = 0; i < n; ++i) {
int complement = target - nums[i];
if (umap.count(complement)) // O(1)
return {i, umap[complement]};
umap[nums[i]] = i; // O(1)
}
return {}; // No solution found
}
};
// Time Complexity: O(n). Single pass through the array.
// Space Complexity: O(n). In the worst case, the hash map stores all elements. ○ 36. Valid Sudoku Medium
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
std::unordered_set<char> uset;
// search rows
for(int row=0; row<9; ++row){
for(int col=0; col<9; ++col){
char c=board[row][col];
if(c=='.')
continue;
else if(uset.count(c))
return false;
else
uset.insert(c);
}
uset.clear();
}
// search cols
for(int col=0; col<9; ++col){
for(int row=0; row<9; ++row){
char c=board[row][col];
if(c=='.')
continue;
else if(uset.count(c))
return false;
else
uset.insert(c);
}
uset.clear();
}
// search grids
for(int i=0; i<3; ++i){
for(int j=0; j<3; ++j){
for(int row=0; row<3; ++row){
for(int col=0; col<3; ++col){
char c=board[i*3+row][j*3+col];
if(c=='.')
continue;
else if(uset.count(c))
return false;
else
uset.insert(c);
}
}
uset.clear();
}
}
return true;
}
};
// Time Complexity: O(1), since the board size is fixed (9x9).
// Space Complexity: O(1), since the maximum size of the hash set is limited to 9 elements for each row, column, or grid. ○ 49. Group Anagrams Medium
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
std::unordered_map<string, vector<string>> umap;
for(const string& s: strs){
string t=s;
sort(t.begin(), t.end());
umap[t].push_back(s);
}
vector<vector<string>> res;
for(const auto p: umap){
res.push_back(p.second);
}
return res;
}
};
// Time Complexity: O(N * K log K) where N is the number of strings and K is the maximum length of a string
// Space Complexity: O(N * K) ○ 128. Longest Consecutive Sequence Medium
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> uset(nums.begin(), nums.end());
int maxSeqLength=0; // longest consecutive sequence
for(const int& n: uset){
if(!uset.count(n-1)){
int curSeqLength=1;
int curNum=n+1;
while(uset.count(curNum)){
++curNum;
++curSeqLength;
}
maxSeqLength=std::max(maxSeqLength, curSeqLength);
}
}
return maxSeqLength;
}
};
// Time Complexity: O(n)
// Space Complexity: O(n) ○ 217. Contains Duplicate Easy
#include <vector>
#include <unordered_set>
using namespace std;
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_set<int> uset;
for(const int n: nums){
if(uset.count(n)){
return true;
}
uset.insert(n);
}
return false;
}
};
// Time Complexity: O(N)
// Space Complexity: O(N) ○ 238. Product of Array Except Self Medium
#include <vector>
using namespace std;
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
// use two vectors to store the prefix prod and suffix prod
// specifically, prefix[i]=nums[0]*nums[1]*...*nums[i-1]
// right[i]=nums[i+1]*nums[i+2]*...*nums[n-1]
// to acheive the O(1) space, we must utilize the output array
// for example, nums = [1,2,3,4]
// init: ans = [1, 1, 1, 1]
// calc the prefix prod: ans = [1, 1, 2, 6]
// calc the suffix prod: use extra var "suffix"
// from the back, ans[n-1] is unchanged, suffix=nums[n-1]
// ans[n-2]*=suffix, suffix*=nums[n-2]
// keep the loop until hit the beginning
int n=nums.size();
vector<int> ans(n, 1);
for(int i=1; i<n; ++i){
ans[i]=ans[i-1]*nums[i-1];
}
int suffix=nums[n-1];
for(int j=n-2; j>=0; --j){
ans[j]*=suffix;
suffix*=nums[j];
}
return ans;
}
};
// Time Complexity: O(N)
// Space Complexity: O(1) ○ 242. Valid Anagram Easy
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.size() != t.size()) return false;
int count[26] = {0};
for (char c : s) count[c - 'a']++;
for (char c : t) {
if (--count[c - 'a'] < 0) return false;
}
return true;
}
}; ○ 271. Encode and Decode Strings Medium
class Codec {
public:
string encode(vector<string>& strs) {
string result;
for (const string& s : strs) {
result += to_string(s.size());
result += '#';
result += s;
}
return result;
}
vector<string> decode(string& s) {
vector<string> result;
int i = 0, n = s.size();
while (i < n) {
int j = i;
while (s[j] != '#') j++;
int len = stoi(s.substr(i, j - i));
result.push_back(s.substr(j + 1, len));
i = j + 1 + len;
}
return result;
}
}; ○ 347. Top K Frequent Elements Medium
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int,int> freq;
for (int x : nums) freq[x]++;
int n = nums.size();
vector<vector<int>> buckets(n + 1);
for (auto& [val, cnt] : freq) buckets[cnt].push_back(val);
vector<int> result;
for (int f = n; f >= 1 && (int)result.size() < k; --f) {
for (int val : buckets[f]) {
result.push_back(val);
if ((int)result.size() == k) break;
}
}
return result;
}
}; ○ 1394. Find Lucky Integer in an Array Easy
#include <vector>
using namespace std;
class Solution {
public:
int findLucky(vector<int>& arr) {
int count[501] = {0}; // index 0 is unused
for (int n : arr)
++count[n];
for (auto n = arr.size(); n > 0; --n)
if (n == count[n])
return n;
return -1;
}
};
// Time Complexity: O(n). Since MAX_VAL is constant.
// Space Complexity: O(MAX_VAL). ○ 1603. Design Parking System Easy
class ParkingSystem {
private:
int parkingSpace[3];
public:
ParkingSystem(int big, int medium, int small) {
parkingSpace[0]=big;
parkingSpace[1]=medium;
parkingSpace[2]=small;
}
bool addCar(int carType) {
if(parkingSpace[carType-1]>0){
--parkingSpace[carType-1];
return true;
}
return false;
}
};
/**
* Your ParkingSystem object will be instantiated and called as such:
* ParkingSystem* obj = new ParkingSystem(big, medium, small);
* bool param_1 = obj->addCar(carType);
*/
// Time Complexity: O(1)
// Space Complexity: O(1) ○ 1865. Finding Pairs With a Certain Sum Medium
class FindSumPairs {
public:
vector<int> v1, v2;
unordered_map<int, int> umap1, umap2;
FindSumPairs(vector<int>& nums1, vector<int>& nums2): v1(nums1), v2(nums2) {
for(const int n: v1){
++umap1[n];
}
for(const int n: v2){
++umap2[n];
}
}
void add(int index, int val) {
--umap2[v2[index]];
v2[index]+=val;
++umap2[v2[index]];
}
int count(int tot) {
int res=0;
for(auto const& [num, freq]: umap1){
res+=freq*(umap2[tot-num]);
}
return res;
}
};
//
// Time Complexity
// FindSumPairs: O(N1 + N2) on average
// add: O(1) on average
// count: O(U1) on average, where U1 is the number of unique elements in nums1
//
// Space Complexity: O(N1+N2)
/**
* Your FindSumPairs object will be instantiated and called as such:
* FindSumPairs* obj = new FindSumPairs(nums1, nums2);
* obj->add(index,val);
* int param_2 = obj->count(tot);
*/ ○ 1929. Concatenation of Array Easy
class Solution {
public:
vector<int> getConcatenation(vector<int>& nums) {
/* Method 1: consider cache locality
// 1. get the len of the nums
// 2. init a vector with size len*2
// 3. fill the 0 ~ len*2
int len=nums.size();
vector<int> res(len*2, 0);
for(int i=0; i<len; ++i){
res[i]=nums[i];
}
for(int i=0; i<len; ++i){
res[i+len]=nums[i];
}
return res;
*/
/* Method 2: standard library */
vector<int> res;
res.reserve(nums.size()*2);
res.insert(res.end(), nums.begin(), nums.end());
res.insert(res.end(), nums.begin(), nums.end());
return res;
}
};
// Time Complexity: O(N)
// Space Complexity: O(N) Two Pointers (8)
○ 11. Container With Most Water Medium
class Solution {
public:
int maxArea(vector<int>& height) {
int numOfLines=height.size();
int left=0;
int right=numOfLines-1;
int maxWater=0;
while(right>left){
maxWater=max(maxWater, (right-left)*min(height[left], height[right]));
if(height[right]<height[left])
right--;
else
left++;
}
return maxWater;
}
};
// Time: O(N)
// Space: O(1) ○ 15. 3Sum Medium
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> result;
int n=nums.size();
if(n<3)
return result;
sort(nums.begin(), nums.end());
for(int i=0; i<n; ++i){
// reduce to two-sum problem
if(i>0 && nums[i]==nums[i-1])
continue;
// early exit
if(nums[i]>0)
break;
int j=i+1;
int k=n-1;
while(j<k){
int curSum=nums[i]+nums[j]+nums[k];
if(curSum==0){
result.push_back({nums[i], nums[j], nums[k]});
++j;
while(j<k && nums[j-1]==nums[j])
++j;
--k;
while(k>j && nums[k+1]==nums[k])
--k;
}
else if(curSum<0)
++j;
else
--k;
}
}
return result;
}
};
// Time: O(N^2)
// Space: O(1) ○ 16. 3Sum Closest Medium
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int n=nums.size();
int closetSum=nums[0]+nums[1]+nums[2];
sort(nums.begin(), nums.end());
for(int i=0; i<n-2; ++i){
int j=i+1;
int k=n-1;
while(j<k){
int curSum=nums[i]+nums[j]+nums[k];
int curDiff=curSum-target;
if(abs(curDiff)<abs(closetSum-target))
closetSum=curSum;
if(curDiff==0)
return target;
else if(curDiff>0)
k--;
else
j++;
}
}
return closetSum;
}
};
// Time: O(N^2)
// Space: O(1) ○ 42. Trapping Rain Water Hard
class Solution {
public:
int trap(vector<int>& height) {
int n=height.size();
int left=0, right=n-1;
int maxLeft=height[0], maxRight=height[n-1];
int sum=0;
if(n<=2)
return 0;
while(left<right){
if(maxLeft<maxRight){
int cur=maxLeft-height[left];
if(cur>0)
sum+=cur;
++left;
}
else{ // maxLeft>=maxRight
int cur=maxRight-height[right];
if(cur>0)
sum+=cur;
--right;
}
maxLeft=std::max(maxLeft,height[left]);
maxRight=std::max(maxRight,height[right]);
}
return sum;
}
};
// Time Complexity: O(N)
// Space Complexity: O(1) ○ 125. Valid Palindrome Easy
class Solution {
public:
bool isAlphaNum(const char &c){
if((c<='z' && c>='a')||(c<='Z' && c>='A')||(c<='9' && c>='0')){
return true;
}
return false;
}
char toLowercase(const char &c){
if(c<='Z' && c>='A'){
return c-'A'+'a';
}
return c;
}
bool isPalindrome(string s) {
int l=0, r=s.length();
while(l<r){
while(l<r && !isAlphaNum(s[l])){
++l;
}
while(l<r && !isAlphaNum(s[r])){
--r;
}
if(toLowercase(s[l])!=toLowercase(s[r])){
return false;
}
++l;
--r;
}
return true;
}
};
// Time Complexity: O(N)
// Space Complexity: O(1) ○ 167. Two Sum II - Input Array Is Sorted Medium
#include <vector>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int i=0;
int j=numbers.size()-1;
while(i<j){
int sum=numbers[i]+numbers[j];
if(sum==target)
return {i+1, j+1};
else if(sum>target)
j--;
else
i++;
}
return {};
}
};
// Time: O(n)
// Space: O(1) ○ 283. Move Zeroes Easy
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int slow=0;
for(int fast=0; fast<nums.size(); ++fast){
if(nums[fast]!=0){
if(slow!=fast){
std::swap(nums[slow], nums[fast]);
}
++slow;
}
}
}
};
// Time Complexity: O(N)
// Space Complexity: O(1) ○ 696. Count Binary Substrings Easy
class Solution {
public:
int countBinarySubstrings(string s) {
vector<int> groups;
char prev=s[0];
int count=0;
int i=0;
while(i<s.length()){
while(s[i]==prev){
++count;
++i;
}
prev=s[i];
groups.push_back(count);
count=0;
}
int res=0;
for(int i=0; i<groups.size()-1; ++i){
res+=std::min(groups[i], groups[i+1]);
}
return res;
}
};
// Time Complexity: O(n)
// Space Complexity: O(n) Sliding Window (7)
○ 3. Longest Substring Without Repeating Characters Medium
#include <string>
#include <unordered_map>
#include <algorithm>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int len = s.length();
int maxLen = 0;
unordered_map<char, int> umap; // store the last seen index of each char
int left = 0;
for (int right = 0; right < len; ++right) {
char cur = s[right];
if (umap.count(cur) && umap[cur] >= left) { // note that `umap[cur]>=left` is important to keep `left` not going back
left = umap[cur] + 1;
}
maxLen = std::max(maxLen, right - left + 1);
umap[cur] = right;
}
return maxLen;
}
};
// Time: O(n) on average
// Space: O(1), since the size of ASCII code (256) is often consider constant. ○ 76. Minimum Window Substring Hard
class Solution {
public:
string minWindow(string s, string t) {
int len1=s.length();
int len2=t.length();
if(len1<len2){
return "";
}
// record frequency in t
// unordered_map<char, int> umap;
vector<int> umap(256, 0);
for(const char& c: t){
++umap[c];
}
// int matchCount=umap.size();
int matchCount=0;
for(const int& i: umap){
if(i!=0){
++matchCount;
}
}
// sliding window
int left=0;
int right=0;
int curMinWindow=INT_MAX;
int startIdx=0;
while(right<len1){
--umap[s[right]];
if(umap[s[right]]==0){
--matchCount;
}
while(matchCount==0){ // move left pointer
if(right-left+1<curMinWindow){
curMinWindow=right-left+1;
startIdx=left;
}
if(++umap[s[left]]>0){
++matchCount;
}
++left;
}
++right;
}
if(curMinWindow==INT_MAX){
return "";
}
return s.substr(startIdx, curMinWindow);
}
};
// Time Complexity: O(n)
// Space Complexity: O(1) ○ 121. Best Time to Buy and Sell Stock Easy
class Solution {
public:
int maxProfit(vector<int>& prices) {
int curMaxProfit=0;
int curMinPrice=prices[0];
for(int price: prices){
curMaxProfit=std::max(curMaxProfit, price-curMinPrice);
curMinPrice=std::min(curMinPrice, price);
}
return curMaxProfit;
}
};
// Time Complexity: O(n)
// Space Complexity: O(1) ○ 209. Minimum Size Subarray Sum Medium
#include <vector>
#include <climits>
using namespace std;
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int minLen=INT_MAX;
int left=0;
int curSum=0;
for(int right=0; right<nums.size(); ++right){
// expand window
curSum+=nums[right];
if(curSum>=target){
// reduce window
while(curSum>=target){
curSum-=nums[left];
++left;
}
minLen=std::min((right-left+2), minLen);
}
}
if(minLen==INT_MAX){
return 0;
}
return minLen;
}
};
// Time Complexity: O(N)
// Space Complexity: O(1) ○ 239. Sliding Window Maximum Hard
#include <vector>
#include <deque>
using namespace std;
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
// use monotonic deque
// the idea is to maintain a deque in decrease order
// the deque size is at most k
// in each iteration:
// 1. remove the expired number from the front (if exist)
// 2. start from the back, remove all values smaller than the current value
// 3. insert the current value
// 4. read the max from the front
// note: in dq, store index instead value
deque<int> dq;
vector<int> ans;
int n=nums.size();
ans.reserve(n+k-1);
for(int i=0; i<n; ++i){
// 1.
if(!dq.empty() && i-dq.front()>=k){
dq.pop_front();
}
// 2.
while(!dq.empty() && nums[dq.back()]<nums[i]){
dq.pop_back();
}
// 3.
dq.push_back(i);
// 4.
if(i>=k-1){
ans.push_back(nums[dq.front()]);
}
}
return ans;
}
};
// Time Complexity: O(N), the pop_back() and pop_front() are amortized O(1) since each index is pushed and popped at most once
// Space Complexity: O(K) ○ 424. Longest Repeating Character Replacement Medium
class Solution {
public:
int characterReplacement(string s, int k) {
int count[26] = {0};
int left = 0, maxCount = 0, best = 0;
for (int right = 0; right < (int)s.size(); ++right) {
maxCount = max(maxCount, ++count[s[right] - 'A']);
while ((right - left + 1) - maxCount > k) {
count[s[left] - 'A']--;
left++;
}
best = max(best, right - left + 1);
}
return best;
}
}; ○ 567. Permutation in String Medium
class Solution {
public:
bool checkInclusion(string s1, string s2) {
unordered_map<int, int> umap; // may improve by using vector<int> (26, 0);
int len1=s1.length();
int len2=s2.length();
if(len1>len2){
return false;
}
// use hashmap to record char freq in s1
for(const char& c: s1){
++umap[c];
}
// use matchCount to record if all the chars in this window are matched
int matchCount=0;
// keep a window to check
int left=0;
for(int right=0; right<len2; ++right){
if(umap[s2[right]]>0){
++matchCount;
}
--umap[s2[right]];
if(matchCount==len1){
return true;
}
if(right-left+1==len1){
++umap[s2[left]];
if(umap[s2[left]]>0){
--matchCount;
}
++left;
}
}
return false;
}
};
// Time Complexity: O(n)
// Space Complexity: O(1), the number of entries in the hash map is at most 26. Stack (10)
○ 20. Valid Parentheses Easy
class Solution {
public:
bool isValid(string s) {
vector<char> stack; // we can also use stack<char>
for(char c: s){
if(c=='('){
stack.push_back(')');
}
else if(c=='{'){
stack.push_back('}');
}
else if(c=='['){
stack.push_back(']');
}
else{
if(stack.empty() || stack.back()!=c)
return false;
stack.pop_back();
}
}
return stack.empty();
}
};
// Time Complexity: O(n)
// Space Complexity: O(n) ○ 22. Generate Parentheses Medium
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> result;
backtrack(result, "", n, 0, 0);
return result;
}
void backtrack(vector<string>& result, string current, int n, int leftNum, int rightNum){
if(current.length()==2*n){
result.push_back(current);
return;
}
if(leftNum<n){
current.push_back('(');
backtrack(result, current, n, leftNum+1, rightNum);
current.pop_back();
}
if(rightNum<leftNum){
current.push_back(')');
backtrack(result, current, n, leftNum, rightNum+1);
current.pop_back();
}
return;
}
};
// Time Complexity: O(4^N / sqrt(N)), or O(n*C_n) where C_n is the n-th Catalan number.
// Space Complexity: O(N) for auxiliary space, O(4^N / sqrt(N)) for the result. ○ 84. Largest Rectangle in Histogram Hard
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
// use monotonic stack
// the stack stores the index of bars
stack<int> s;
int maxArea=0;
// key details
s.push(-1);
heights.push_back(0);
for(int i=0; i<heights.size(); ++i){
while(s.top()!=-1 && heights[i]<=heights[s.top()]){
int height=heights[s.top()];
s.pop();
int left=s.top();
int width=(i-1)-left;
maxArea=std::max(maxArea, width*height);
}
s.push(i);
}
return maxArea;
}
};
// Time Complexity: O(N). Each bar is pushed and popped exactly once.
// Space Complexity: O(N). The stack can contain at most N elements. ○ 150. Evaluate Reverse Polish Notation Medium
#include <vector>
#include <stack>
using namespace std;
class Solution {
public:
int evalRPN(vector<string>& tokens) {
std::stack<int> st;
for(const string& t: tokens){
if(t=="+"){
int a=st.top();
st.pop();
int b=st.top();
st.pop();
st.push(b+a);
}
else if(t=="-"){
int a=st.top();
st.pop();
int b=st.top();
st.pop();
st.push(b-a);
}
else if(t=="*"){
int a=st.top();
st.pop();
int b=st.top();
st.pop();
st.push(b*a);
}
else if(t=="/"){
int a=st.top();
st.pop();
int b=st.top();
st.pop();
st.push(b/a);
}
else{
st.push(std::stoi(t));
}
}
return st.top();
}
};
// Time Complexity: O(N)
// Space Complexity: O(N) ○ 155. Min Stack Medium
#include <stack>
using namespace std;
class MinStack {
public:
stack<int> s1;
stack<int> s2;
MinStack() {}
void push(int val) {
s1.push(val);
if(s2.empty() || s2.top()>=val){
s2.push(val);
}
}
void pop() {
if(s2.top()==s1.top()){
s2.pop();
}
s1.pop();
}
int top() {
return s1.top();
}
int getMin() {
return s2.top();
}
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(val);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/
// Time: O(1) for all operations
// Space: O(n) for the two stacks, where n is the number of elements in the MinStack ○ 224. Basic Calculator Hard
#include <string>
#include <stack>
using namespace std;
class Solution {
public:
int calculate(string s) {
long long res=0;
long long cur=0;
int sign=1;
stack<long long> st;
for(const char c: s){
if(isdigit(c)){
cur=cur*10+(c-'0');
}
else if(c=='+'){
res+=cur*sign;
cur=0;
sign=1;
}
else if(c=='-'){
res+=cur*sign;
cur=0;
sign=-1;
}
else if(c=='('){
st.push(res);
st.push(sign);
res=0;
sign=1;
}
else if(c==')'){
res+=cur*sign;
cur=0;
long long prev_sign=st.top();
st.pop();
long long prev_res=st.top();
st.pop();
res=prev_res+prev_sign*res;
}
}
res+=sign*cur;
return res;
}
};
// Time: O(N)
// Space: O(N) ○ 227. Basic Calculator II Medium
#include <string>
using namespace std;
class Solution {
public:
int calculate(string s) {
long long res=0;
long long cur=0;
long long last=0;
char op='+';
for(int i=0; i<s.length(); ++i){
char c=s[i];
if(isdigit(c)){
cur=cur*10+(c-'0');
}
if(c=='+' || c=='-' || c=='*'|| c=='/' || i==s.length()-1){
if(op=='+'){
res+=last;
last=cur;
}
else if(op=='-'){
res+=last;
last=-cur;
}
else if(op=='*'){
last*=cur;
}
else if(op=='/'){
last/=cur;
}
cur=0;
op=c;
}
}
res+=last;
return res;
}
};
// Time Complexity: O(N)
// Space Complexity: O(1) ○ 341. Flatten Nested List Iterator Medium
// This is the interface that allows for creating nested lists.
// You should not implement it, or speculate about its implementation
class NestedInteger {
public:
// Return true if this NestedInteger holds a single integer, rather than a nested list.
bool isInteger() const;
// Return the single integer that this NestedInteger holds, if it holds a single integer
// The result is undefined if this NestedInteger holds a nested list
int getInteger() const;
// Return the nested list that this NestedInteger holds, if it holds a nested list
// The result is undefined if this NestedInteger holds a single integer
const vector<NestedInteger> &getList() const;
};
#include <vector>
#include <stack>
using namespace std;
class NestedIterator {
private:
stack<NestedInteger> st;
public:
NestedIterator(vector<NestedInteger> &nestedList) {
for(int i=nestedList.size()-1; i>=0; --i){
st.push(nestedList[i]);
}
}
int next() {
int top=st.top().getInteger();
st.pop();
return top;
}
bool hasNext() {
while(!st.empty()){
NestedInteger cur=st.top();
if(cur.isInteger()){
return true;
}
// if not
st.pop();
vector<NestedInteger> curList=cur.getList();
for(int i=curList.size()-1; i>=0; --i){
st.push(curList[i]);
}
}
return false;
}
};
/**
* Your NestedIterator object will be instantiated and called as such:
* NestedIterator i(nestedList);
* while (i.hasNext()) cout << i.next();
*/
// Time Complexity: O(1) amortized for next() and hasNext()
// Space Complexity: O(D) where D is the maximum depth of the nested list
// Another possible approach is dfs (to flatten the entire list in the constructor)
// but that would use O(N) space where N is the total number of integers in the nested list. ○ 739. Daily Temperatures Medium
#include <vector>
using namespace std;
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
int n=temperatures.size();
vector<int> res(n, 0);
vector<int> st;
st.reserve(n);
for(int i=0; i<n; ++i){
int cur=temperatures[i];
while(!st.empty() && temperatures[st.back()]<cur){
res[st.back()]=i-st.back();
st.pop_back();
}
st.push_back(i);
}
return res;
}
};
// Time: O(N), where N is the length of the input array, since each index is pushed and popped at most once.
// Space: O(N), in the worst case when the input array is strictly decreasing, the stack will hold all indices, and the output array also takes O(N) space. ○ 853. Car Fleet Medium
class Solution {
public:
int carFleet(int target, vector<int>& position, vector<int>& speed) {
int n = position.size();
vector<pair<int,double>> cars(n);
for (int i = 0; i < n; ++i) {
cars[i] = {position[i], (double)(target - position[i]) / speed[i]};
}
sort(cars.begin(), cars.end(), [](const auto& a, const auto& b) {
return a.first > b.first;
});
int fleets = 0;
double lead = 0.0;
for (auto& [pos, time] : cars) {
if (time > lead) {
fleets++;
lead = time;
}
}
return fleets;
}
}; Binary Search (10)
○ 4. Median of Two Sorted Arrays Hard
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int MAX = 1e7;
int findKthMin(vector<int>& nums1, int start1, vector<int>& nums2, int start2, int k) {
if (nums1.size() - start1 == 0)
return nums2[start2 + k - 1];
if (nums2.size() - start2 == 0)
return nums1[start1 + k - 1];
if (k == 1)
return std::min(nums1[start1], nums2[start2]);
int idx1 = start1 + k / 2 - 1;
int idx2 = start2 + k / 2 - 1;
int val1 = (idx1 < nums1.size()) ? nums1[idx1] : MAX;
int val2 = (idx2 < nums2.size()) ? nums2[idx2] : MAX;
if (val1 < val2)
return findKthMin(nums1, idx1 + 1, nums2, start2, k - k / 2);
return findKthMin(nums1, start1, nums2, idx2 + 1, k - k / 2);
}
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
// use binary tree to solve the problem
int m = nums1.size();
int n = nums2.size();
int k = (m + n + 1) / 2;
int med = findKthMin(nums1, 0, nums2, 0, k); // k is 1-index
bool isOdd = (m + n) % 2;
if (isOdd)
return med;
else
return (med + findKthMin(nums1, 0, nums2, 0, k + 1)) / 2.0;
}
};
// Time: O(log(m+n))
// Space: O(log(m+n)) ○ 33. Search in Rotated Sorted Array Medium
class Solution {
public:
int search(vector<int>& nums, int target) {
int left=0, right=nums.size()-1;
while(left<=right){
int mid=(left+right)/2;
if(nums[mid]==target){
return mid;
}
else if(nums[left]<=nums[mid]){ // left side sorted
if(nums[left]<=target && nums[mid]>target)
right=mid-1;
else
left=mid+1;
}
else{ // right side sorted
if(nums[mid]<target && nums[right]>=target)
left=mid+1;
else
right=mid-1;
}
}
return -1;
}
};
// Time Complexity: O(log n)
// Space Complexity: O(1) ○ 35. Search Insert Position Easy
#include <vector>
using namespace std;
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int left=0;
int right=nums.size()-1;
while(left<=right){
int mid=(left+right)/2;
if(nums[mid]==target){
return mid;
}
else if(nums[mid]>target){
right=mid-1;
}
else{
left=mid+1;
}
}
return left;
}
};
// nums = [1,3,5,6], target = 5
// l=0 -> 2
// r=3
// mid=1 -> 2
// nums = [1,3,5,6], target = 2
// l=0
// r=3 -> 0
// mid=1 -> 0
// Time Complexity: O(logN)
// Space Complexity: O(1)
○ 69. Sqrt(x) Easy
class Solution {
public:
int mySqrt(int x) {
if(x<2){
return x;
}
int left=2;
int right=x/2;
while(left<=right){
int mid=left+(right-left)/2;
if(x/mid>mid){
left=mid+1;
}
else if(x/mid<mid){
right=mid-1;
}
else{
return mid;
}
}
return right;
}
};
// Time Complexity: O(log x)
// Space Complexity: O(1) ○ 74. Search a 2D Matrix Medium
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int m=matrix.size();
int n=matrix[0].size();
// do 2 binary searchs
int top=0;
int down=m-1;
int targetRow=-1;
while(top<=down){
int mid=(top+down)/2;
int val=matrix[mid][0];
if(val==target){
return true;
}
else if(val<target){
targetRow=mid; // temporarily keep it
top=mid+1;
}
else{
down=mid-1;
}
}
if(targetRow==-1){
return false;
}
int left=0;
int right=n-1;
while(left<=right){
int mid=(left+right)/2;
int val=matrix[targetRow][mid];
if(val==target){
return true;
}
if(val<target){
left=mid+1;
}
else{
right=mid-1;
}
}
return false;
}
};
// Time Complexity: O(log m + log n)=O(log mn)
// Space Complexity: O(1) ○ 153. Find Minimum in Rotated Sorted Array Medium
#include <vector>
using namespace std;
class Solution {
public:
int findMin(vector<int>& nums) {
int l=0, r=nums.size()-1;
while(l<r){
int lval=nums[l];
int rval=nums[r];
if(lval<rval){
return lval;
}
int mid=(l+r)/2;
if(nums[mid]>=lval){
l=mid+1;
}
else{
r=mid;
}
}
return nums[l];
}
};
// Time: O(log n)
// Space: O(1) ○ 528. Random Pick with Weight Medium
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
vector<int> prefixSum;
public:
Solution(vector<int>& w) {
prefixSum.resize(w.size());
prefixSum[0]=w[0];
for(int i=1; i<w.size(); ++i){
prefixSum[i]=prefixSum[i-1]+w[i];
}
}
int pickIndex() {
int target=rand()%prefixSum.back();
auto it=std::upper_bound(prefixSum.begin(), prefixSum.end(), target);
return distance(prefixSum.begin(), it);
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(w);
* int param_1 = obj->pickIndex();
*/
// Time Complexity: O(N) for constructor, O(logN) for pickIndex() where N is the size of the input vector w.
// Space Complexity: O(N) for storing the prefix sum array. ○ 704. Binary Search Easy
class Solution {
public:
int search(vector<int>& nums, int target) {
int lo = 0, hi = nums.size() - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] == target) return mid;
if (nums[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
}; ○ 875. Koko Eating Bananas Medium
class Solution {
public:
int minEatingSpeed(vector<int>& piles, int h) {
int lo = 1, hi = *max_element(piles.begin(), piles.end());
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
long long hours = 0;
for (int p : piles) hours += (p + mid - 1) / mid;
if (hours <= h) hi = mid;
else lo = mid + 1;
}
return lo;
}
}; ○ 981. Time Based Key-Value Store Medium
class TimeMap {
unordered_map<string, vector<pair<int,string>>> store;
public:
TimeMap() {}
void set(string key, string value, int timestamp) {
store[key].push_back({timestamp, value});
}
string get(string key, int timestamp) {
auto it = store.find(key);
if (it == store.end()) return "";
auto& vec = it->second;
int lo = 0, hi = vec.size() - 1;
string result = "";
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (vec[mid].first <= timestamp) {
result = vec[mid].second;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return result;
}
}; Linked List (11)
○ 2. Add Two Numbers Medium
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* dummyNode = new ListNode(0);
ListNode* current=dummyNode;
int carry=0;
while(l1 || l2 || carry){
int val1 = l1 ? l1->val : 0;
int val2 = l2 ? l2->val : 0;
int sum=val1+val2+carry;
carry=sum/10;
sum%=10;
current->next=new ListNode(sum);
l1= l1 ? l1->next : nullptr;
l2= l2 ? l2->next : nullptr;
current=current->next;
}
ListNode* res=dummyNode->next;
delete dummyNode;
return res;
}
};
// Time: O(max(M,N))
// Space: O(max(M,N)) ○ 19. Remove Nth Node From End of List Medium
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode dummy(0, head);
ListNode* tmp=head;
int total=0;
while(tmp){
++total;
tmp=tmp->next;
}
tmp=&dummy;
int target=total-n;
for(int i=0; i<target; i++) // prev node of target
tmp=tmp->next;
if(tmp->next){
ListNode* to_delete=tmp->next;
tmp->next=tmp->next->next;
delete to_delete;
}
return dummy.next;
}
};
// Time Complexity: O(N)
// Space Complexity: O(1) ○ 21. Merge Two Sorted Lists Easy
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
ListNode dummy(0);
ListNode* cur=&dummy;
while(list1 && list2){
if(list1->val<=list2->val){
cur->next=list1;
list1=list1->next;
}
else{
cur->next=list2;
list2=list2->next;
}
cur=cur->next;
}
if(list1)
cur->next=list1;
else if(list2)
cur->next=list2;
return dummy.next;
}
};
// Time Complexity: O(m+n)
// Space Complexity: O(1) ○ 23. Merge k Sorted Lists Hard
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
int listNum=lists.size();
for(int i=listNum-1; i>=0; i--){
if(lists[i]==nullptr)
lists.erase(lists.begin()+i);
}
if(lists.empty())
return nullptr;
auto comp = [](ListNode* a, ListNode* b){
return a->val > b->val; // Min-heap logic
};
std::priority_queue<ListNode*, vector<ListNode*>, decltype(comp)> pq(comp);
for(ListNode* head: lists){
pq.push(head);
}
ListNode dummy(0);
ListNode* cur=&dummy;
while(!pq.empty()){
ListNode* minNode=pq.top();
pq.pop();
cur->next=minNode;
cur=cur->next;
if(minNode->next){
pq.push(minNode->next);
}
}
return dummy.next;
}
};
// Time Complexity: O(KlogK) for initializing the priority queue, and O(NlogK) for the while loop. So total time complexity is O(NlogK).
// Space Complexity: O(K) for the priority queue. ○ 25. Reverse Nodes in k-Group Hard
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if(k<=1)
return head;
ListNode dummyNode(0, head);
ListNode* group_start=&dummyNode;
ListNode* group_end=head;
int count=0;
while(group_end){
group_end=group_end->next;
++count;
if(count%k==0){
ListNode* group_start_next=group_start->next;
ListNode* new_group_start=reverseAGroup(group_start->next, k);
group_start->next=new_group_start;
group_start=group_start_next;
group_start->next=group_end;
}
}
return dummyNode.next;
}
ListNode* reverseAGroup(ListNode* head, int k) {
ListNode* prev=nullptr;
ListNode* cur=head;
ListNode* next_node=nullptr;
for(int i=0; i<k; ++i) {
next_node=cur->next;
cur->next=prev;
prev=cur;
cur=next_node;
}
return prev;
}
};
// Time Complexity: O(N)
// Space Complexity: O(1) ○ 138. Copy List with Random Pointer Medium
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
class Solution {
public:
Node* copyRandomList(Node* head) {
if(!head){
return nullptr;
}
// old1, old2, ...
// old1, new1, old2, new2, ...
// copy next
Node* cur=head;
while(cur){
Node* newNode=new Node(cur->val);
newNode->next=cur->next;
cur->next=newNode;
cur=newNode->next;
}
// copy random
cur=head;
while(cur){
if(cur->random){
cur->next->random=cur->random->next;
}
cur=cur->next->next;
}
// separate the new list
Node dummy=Node(0);
Node* ccur=&dummy;
cur=head;
while(cur){
ccur->next=cur->next;
ccur=ccur->next;
cur->next=cur->next->next;
cur=cur->next;
}
return dummy.next;
}
};
// Time Complexity: O(N)
// Space Complexity: O(1), since we use interleaving nodes to avoid using extra space for a hash map. ○ 141. Linked List Cycle Easy
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if(!head) return false;
ListNode *fast=head;
ListNode *slow=head;
while(fast->next && fast->next->next){
slow=slow->next;
fast=fast->next->next;
if(slow==fast) return true;
}
return false;
}
};
// Time Complexity: O(N)
// Space Complexity: O(1) ○ 143. Reorder List Medium
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
void reorderList(ListNode* head) {
if(!head || !head->next){
return;
}
ListNode* slow=head;
ListNode* fast=head->next;
// find mid
// slow: 1 2
// fast: 2 4
while(fast && fast->next){
slow=slow->next;
fast=fast->next->next;
}
ListNode* pre=nullptr;
ListNode* cur=slow->next;
ListNode* nxt=cur->next;
slow->next=nullptr;
while(nxt){
cur->next=pre;
pre=cur;
cur=nxt;
nxt=nxt->next;
}
cur->next=pre;
ListNode* list1=head;
ListNode* list2=cur;
ListNode* tmp1;
ListNode* tmp2;
while(list2){
tmp1=list1->next;
tmp2=list2->next;
list1->next=list2;
list2->next=tmp1;
list1=tmp1;
list2=tmp2;
}
}
};
// Time Complexity: O(N)
// Space Complexity: O(1) ○ 146. LRU Cache Medium
struct Node {
int key;
int val;
Node* next;
Node* prev;
Node(int _key, int _val): key(_key), val(_val), next(nullptr), prev(nullptr){}
};
class LRUCache {
private:
unordered_map<int, Node*> umap;
Node* head;
Node* tail;
int cap;
void remove(Node *curNode){
curNode->prev->next=curNode->next;
curNode->next->prev=curNode->prev;
}
void add(Node *curNode){
Node* prev=tail->prev;
prev->next=curNode;
tail->prev=curNode;
curNode->prev=prev;
curNode->next=tail;
}
public:
LRUCache(int capacity) {
head=new Node(-1, -1);
tail=new Node(-1, -1);
head->next=tail;
tail->prev=head;
cap=capacity;
}
~LRUCache(){
Node* curNode=head;
while(curNode){
Node* next=curNode->next;
delete curNode;
curNode=next;
}
}
int get(int key) {
auto it=umap.find(key);
if(it!=umap.end()){
Node* curNode=it->second;
remove(curNode);
add(curNode);
return curNode->val;
}
return -1;
}
void put(int key, int value) {
Node* curNode;
auto it=umap.find(key);
if(it!=umap.end()){
curNode=it->second;
curNode->val=value;
remove(curNode);
}
else{
curNode=new Node(key, value);
umap[key]=curNode;
}
add(curNode);
if(umap.size()>cap){
Node* targetNode=head->next;
remove(targetNode);
umap.erase(targetNode->key);
delete targetNode;
}
}
};
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache* obj = new LRUCache(capacity);
* int param_1 = obj->get(key);
* obj->put(key,value);
*/
// Time Complexity: O(1) for get and put
// Space Complexity: O(N) for the cache, N is the capacity of the cache ○ 206. Reverse Linked List Easy
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
// Taking 3 nodes to store the nodes.
ListNode* cur = head;
ListNode* prev = NULL;
ListNode* next = NULL;
// reversing the linked list
// 1->2->3->4->5 to 5->4->4->3->2->1
while(cur){
next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
return prev;
}
};
// Time Complexity: O(N)
// Space Complexity: O(1) ○ 287. Find the Duplicate Number Medium
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int slow = nums[0], fast = nums[0];
do {
slow = nums[slow];
fast = nums[nums[fast]];
} while (slow != fast);
slow = nums[0];
while (slow != fast) {
slow = nums[slow];
fast = nums[fast];
}
return slow;
}
}; Trees (18)
○ 20. Diameter of Binary Tree Easy
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
std::pair<int, int> dfs(TreeNode* root) { // return the depth and the diameter of the tree
if(!root)
return {0, 0};
auto [leftDepth, leftDiameter] = dfs(root->left);
auto [rightDepth, rightDiameter] = dfs(root->right);
int diameterThroughRoot=leftDepth+rightDepth;
int currentDiameter=std::max({leftDiameter, rightDiameter, diameterThroughRoot});
int currentDepth=std::max(leftDepth, rightDepth)+1;
return {currentDepth, currentDiameter};
}
int diameterOfBinaryTree(TreeNode* root) {
return dfs(root).second;
}
};
// Time Complexity: O(N)
// Space Complexity: O(H) where H is the height of the tree, since we are using recursion (the call stack will take up space).
// In the worst case (skewed tree), H = N. In the best case (balanced tree), H = log(N). ○ 98. Validate Binary Search Tree Medium
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool dfs(TreeNode* root, TreeNode* low, TreeNode* high){
if(!root){
return true;
}
if((high && root->val>=high->val) || (low && root->val<=low->val)){
return false;
}
return dfs(root->left, low, root) && dfs(root->right, root, high);
}
bool isValidBST(TreeNode* root) {
return dfs(root, nullptr, nullptr);
}
};
// Time Complexity: O(N)
// Space Complexity: O(H) where H is the height of the tree, since we are using recursion (the call stack will take up space).
// In the worst case (skewed tree), H = N. In the best case (balanced tree), H = log(N). ○ 100. Same Tree Easy
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(!p){
return !q;
}
else if(!q){
return !p;
}
else{
return (p->val==q->val) && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
}
};
// Time Complexity: O(N)
// Space Complexity: O(H) where H is the height of the tree, since we are using recursion (the call stack will take up space).
// In the worst case (skewed tree), H = N. In the best case (balanced tree), H = log(N). ○ 102. Binary Tree Level Order Traversal Medium
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
if(!root){
return res;
}
queue<TreeNode*> q;
q.push(root);
vector<int> curLevel;
while(!q.empty()){
int levelSize=q.size();
curLevel.clear();
for(int i=0; i<levelSize; ++i){
TreeNode* curNode=q.front();
curLevel.push_back(curNode->val);
if(curNode->left){
q.push(curNode->left);
}
if(curNode->right){
q.push(curNode->right);
}
q.pop();
}
res.push_back(curLevel);
}
return res;
}
};
// Time Complexity: O(N)
// Space Complexity: O(W) for the queue, where W is the maximum width of the tree. ○ 104. Maximum Depth of Binary Tree Easy
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root) return 0;
return max(maxDepth(root->left), maxDepth(root->right))+1;
}
};
// Time Complexity: O(N)
// Space Complexity: O(H) where H is the height of the tree, since we are using recursion (the call stack will take up space).
// In the worst case (skewed tree), H = N. In the best case (balanced tree), H = log(N). ○ 105. Construct Binary Tree from Preorder and Inorder Traversal Medium
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
unordered_map<int, int> umap;
TreeNode* traversal(const vector<int>& preorder, const vector<int>& inorder, int l1, int r1, int l2, int r2) {
if(l1>r1){
return nullptr;
}
int val=preorder[l1];
TreeNode* root=new TreeNode(val);
int m=umap[val]; // idx in inorder
// left tree size: m-l2
int llen=m-l2;
root->left=traversal(preorder, inorder, l1+1, l1+llen, l2, m-1);
root->right=traversal(preorder, inorder, l1+llen+1, r1, m+1, r2);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int len=preorder.size();
for(int i=0; i<len; ++i){
umap[inorder[i]]=i;
}
return traversal(preorder, inorder, 0, len-1, 0, len-1);
}
};
// Time Complexity: O(N)
// Space Complexity: O(N) ○ 110. Balanced Binary Tree Easy
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int checkHeight(TreeNode* root){
if(!root){
return 0;
}
int l=checkHeight(root->left);
int r=checkHeight(root->right);
if(l==-1 || r==-1 || std::abs(l-r)>1){
return -1;
}
return std::max(l, r)+1;
}
bool isBalanced(TreeNode* root) {
if(!root){
return true;
}
return checkHeight(root)!=-1;
}
};
// Time Complexity: O(N)
// Space Complexity: O(H) where H is the height of the tree, since we are using recursion (the call stack will take up space).
// In the worst case (skewed tree), H = N. In the best case (balanced tree), H = log(N). ○ 111. Minimum Depth of Binary Tree Easy
#include <queue>
using namespace std;
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
int minDepth(TreeNode* root) {
if(!root){
return 0;
}
std::queue<pair<TreeNode*, int>> q;
q.push({root, 1});
while(!q.empty()){
auto [node, depth]=q.front();
q.pop();
if(!node->left && !node->right){
return depth;
}
if(node->left){
q.push({node->left, depth+1});
}
if(node->right){
q.push({node->right, depth+1});
}
}
return 0;
}
};
// Time Complexity: O(N)
// Space Complexity: O(H) where H is the height of the tree. In the worst case (skewed tree), it can be O(N). ○ 116. Populating Next Right Pointers in Each Node Medium
/*
// Definition for a Node.
class Node {
public:
int val;
Node* left;
Node* right;
Node* next;
Node() : val(0), left(NULL), right(NULL), next(NULL) {}
Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}
Node(int _val, Node* _left, Node* _right, Node* _next)
: val(_val), left(_left), right(_right), next(_next) {}
};
*/
class Solution {
public:
Node* connect(Node* root) {
if(!root)
return root;
Node* l=root->left;
Node* r=root->right;
Node* n=root->next;
if(l){
l->next=r;
if(n){
r->next=n->left;
}
connect(l);
connect(r);
}
return root;
}
};
// Time Complexity: O(N)
// Space Complexity: O(1) ○ 124. Binary Tree Maximum Path Sum Hard
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
std::pair<int, int> dfs(TreeNode* root){
if(!root){
return {-1001, -1001};
}
auto [l1, l2]=dfs(root->left);
auto [r1, r2]=dfs(root->right);
int v=root->val;
int ableToConnect=std::max(std::max(l1, r1)+v, v);
int notAbleToConnet=std::max(std::max(l2, r2), std::max(l1+r1+v, ableToConnect));
return {ableToConnect, notAbleToConnet};
}
int maxPathSum(TreeNode* root) {
auto [v1, v2]=dfs(root);
return std::max(v1, v2);
}
};
// Time Complexity: O(N)
// Space Complexity: O(H), where H is the height of the tree due to recursion stack. ○ 199. Binary Tree Right Side View Medium
#include <vector>
using namespace std;
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
void dfs(TreeNode* root, vector<int>& res, int level){
if(!root){
return;
}
if(level==res.size()){
res.push_back(root->val);
}
dfs(root->right, res, level+1);
dfs(root->left, res, level+1);
}
vector<int> rightSideView(TreeNode* root) {
vector<int> res;
dfs(root, res, 0);
return res;
}
};
// Time Complexity: O(N)
// Space Complexity: O(H), where H is the height of the binary tree, which is O(N) in the worst case (skewed tree) and O(log N) in the best case (balanced tree). ○ 226. Invert Binary Tree Easy
#include <iostream>
using namespace std;
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(!root){
return nullptr;
}
std::swap(root->left, root->right);
invertTree(root->left);
invertTree(root->right);
return root;
}
};
// Time: O(N), where N is the number of nodes in the tree, since we visit each node once.
// Space: O(H), where H is the height of the tree, due to the recursion stack.
○ 230. Kth Smallest Element in a BST Medium
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
void solve(TreeNode* root, int& k, int& res) {
if(!root){
return;
}
solve(root->left, k, res);
if(k==0){
return;
}
if(--k==0){
res=root->val;
return;
}
solve(root->right, k, res);
}
int kthSmallest(TreeNode* root, int k) {
int res=-1;
solve(root, k, res);
return res;
}
};
// Time: O(H+k), where H is the height of the tree, since we may need to traverse down to the leftmost node and then visit k nodes.
// Space: O(H), where H is the height of the tree, due to the recursionn stack. In the worst case of a skewed tree, this could be O(N). ○ 235. Lowest Common Ancestor of a Binary Search Tree Medium
#include <algorithm>
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
int minVal=std::min(p->val, q->val);
int maxVal=std::max(p->val, q->val);
while(root){
if(root->val<minVal){
root=root->right;
}
else if(root->val>maxVal){
root=root->left;
}
else{
return root;
}
}
return nullptr;
}
};
// Time: O(H), where H is the height of the tree, since in the worst case we might have to traverse from the root to a leaf node.
// Space: O(1), since we are using only a constant amount of extra space. ○ 297. Serialize and Deserialize Binary Tree Hard
class Codec {
public:
string serialize(TreeNode* root) {
string result;
function<void(TreeNode*)> dfs = [&](TreeNode* node) {
if (!node) {
result += "N ";
return;
}
result += to_string(node->val) + " ";
dfs(node->left);
dfs(node->right);
};
dfs(root);
return result;
}
TreeNode* deserialize(string data) {
istringstream in(data);
function<TreeNode*()> build = [&]() -> TreeNode* {
string token;
in >> token;
if (token == "N") return nullptr;
TreeNode* node = new TreeNode(stoi(token));
node->left = build();
node->right = build();
return node;
};
return build();
}
}; ○ 298. Binary Tree Longest Consecutive Sequence Medium
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void dfs(TreeNode* root, int pVal, int curLen, int& curMax){
if(!root){
return;
}
int rVal=root->val;
if(rVal==pVal+1){
curLen+=1;
}
else{
curLen=1;
}
curMax=std::max(curMax, curLen);
dfs(root->left, rVal, curLen, curMax);
dfs(root->right, rVal, curLen, curMax);
}
int longestConsecutive(TreeNode* root) {
int curMax=0;
dfs(root, root->val-1, 0, curMax);
return curMax;
}
};
// Time Complexity: O(N)
// Space Complexity: O(H) where H is the height of the tree ○ 572. Subtree of Another Tree Easy
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isIdentical(TreeNode* root, TreeNode* subRoot){
if(!root && !subRoot){
return true;
}
if(!root || !subRoot || root->val != subRoot->val){
return false;
}
return isIdentical(root->left, subRoot->left) && isIdentical(root->right, subRoot->right);
}
bool isSubtree(TreeNode* root, TreeNode* subRoot) {
return isIdentical(root, subRoot) || (root && (isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot)));
}
};
// Time Complexity: O(N*M)
// Space Complexity: O(H) where H is the height of the tree, since we are using recursion (the call stack will take up space).
// In the worst case (skewed tree), H = N. In the best case (balanced tree), H = log(N).
// We can use preorder traversal and serialize the tree to a string, then check if the subtree is a substring of the string, this will be O(N+M) time complexity. ○ 1448. Count Good Nodes in Binary Tree Medium
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
int goodNodes(TreeNode* root) {
return dfs(root, root->val);
}
int dfs(TreeNode* curNode, int maxValue){
int count=0;
if(!curNode)
return 0;
if(curNode->val>=maxValue){
maxValue=curNode->val;
count++;
}
count+=dfs(curNode->left, maxValue);
count+=dfs(curNode->right, maxValue);
return count;
}
};
// Time: O(n)
// Space: O(h) where h is the height of the tree, since we are using recursion (the call stack will take up space).
// In the worst case (skewed tree), h = n. In the best case (balanced tree), h = log(n). Tries (4)
○ 208. Implement Trie (Prefix Tree) Medium
#include <string>
using namespace std;
class TrieNode {
public:
bool isWord;
TrieNode *child[26];
TrieNode(){
isWord=false;
for(auto &a: child)
a=nullptr;
}
};
class Trie {
public:
Trie() {
root = new TrieNode();
}
void insert(string word) {
TrieNode* p=root;
for(auto &a: word){
int i=a-'a';
if(!p->child[i])
p->child[i]=new TrieNode();
p=p->child[i];
}
p->isWord=true;
}
bool search(string word) {
TrieNode* p=root;
for(auto &a: word){
int i=a-'a';
if(!p->child[i])
return false;
p=p->child[i];
}
return p->isWord;
}
bool startsWith(string prefix) {
TrieNode *p = root;
for (auto &a: prefix)
{
int i = a - 'a';
if(!p->child[i])
return false;
p=p->child[i];
}
return true;
}
private:
TrieNode* root;
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/
// Time Complexity: O(m) for insert, search, and startsWith, where m is the length of the input string (word or prefix).
// Space Complexity: O(m) for insert, since we may need to create up to m new TrieNodes in the worst case. The space complexity for search and startsWith is O(1) since they only use a constant amount of extra space. ○ 211. Design Add and Search Words Data Structure Medium
#include <string>
using namespace std;
class TrieNode {
public:
TrieNode* children[26];
bool isEnd;
TrieNode(){
for(auto& c: children){
c=nullptr;
}
isEnd=false;
}
};
class WordDictionary {
public:
WordDictionary() {
root=new TrieNode();
}
~WordDictionary(){
clear(root);
}
void addWord(string word) {
TrieNode* cur=root;
for(const char &c: word){
int i=c-'a';
if(!cur->children[i]){
cur->children[i]=new TrieNode();
}
cur=cur->children[i];
}
cur->isEnd=true;
}
bool search(string word) {
return dfs(root, word, 0);
}
private:
TrieNode* root;
bool dfs(TrieNode* cur, const string& word, int idx){
if(idx==word.size()){
return cur->isEnd;
}
char c=word[idx];
if(c=='.'){
for(int i=0; i<26; ++i){
if(cur->children[i] && dfs(cur->children[i], word, idx+1)){
return true;
}
}
return false;
}
int i=c-'a';
if(!cur->children[i]){
return false;
}
return dfs(cur->children[i], word, idx+1);
}
void clear(TrieNode* node){
if(!node){
return;
}
for(auto c: node->children){
if(c){
clear(c);
}
}
delete node;
}
};
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary* obj = new WordDictionary();
* obj->addWord(word);
* bool param_2 = obj->search(word);
*/
// Time Complexity: O(m) for addWord and search, where m is the length of the input word. In the worst case, search can take O(26^m) time if the word consists of '.' characters and matches all possible combinations of letters.
// Space Complexity: O(m) for addWord, since we may need to create up to m new TrieNodes in the worst case. The space complexity for search is O(m) due to the recursion stack in the worst case when the word consists of '.' characters. ○ 212. Word Search II Hard
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
struct TrieNode {
TrieNode* children[26]={nullptr};
// unique_ptr<TrieNode> children[26];
string* word=nullptr;
~TrieNode(){
for(int i=0; i<26; ++i){
if(children[i]){
delete children[i];
}
}
}
};
void insert(TrieNode* root, string& s){
TrieNode* cur=root;
for(char c: s){
if(cur->children[c-'a']==nullptr){
cur->children[c-'a']=new TrieNode();
}
cur=cur->children[c-'a'];
}
cur->word=&s;
}
void dfs(vector<vector<char>>& board, vector<string>& res, TrieNode* cur, int x, int y){
if(x<0 || x>=board.size() || y<0 || y>=board[0].size()){
return;
}
char c=board[x][y];
if(c=='#' || !cur->children[c-'a']){
return;
}
cur=cur->children[c-'a'];
if(cur->word){
res.push_back(*cur->word);
cur->word=nullptr;
}
board[x][y]='#';
int dx[4]={-1, 1, 0, 0};
int dy[4]={0, 0, -1, 1};
for(int i=0; i<4; ++i){
dfs(board, res, cur, x+dx[i], y+dy[i]);
}
board[x][y]=c;
}
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
vector<string> res;
TrieNode* root=new TrieNode();
for(string& word: words){
insert(root, word);
}
for(int x=0; x<board.size(); ++x){
for(int y=0; y<board[0].size(); ++y){
dfs(board, res, root, x, y);
}
}
delete root;
return res;
}
};
// Time Complexity: O(S + M*N*3^L) where S is the total number of letters in the words, M and N are the dimensions of the board, and L is the maximum length of a word.
// O(S) to build the Trie, and O(M*N*3^L) for the DFS search.
// Space Complexity: O(S) ○ 1233. Remove Sub-Folders from the Filesystem Medium
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<string> removeSubfolders(vector<string>& folder) {
sort(folder.begin(), folder.end());
vector<string> res;
res.push_back(folder[0]);
for(int i=1; i<folder.size(); ++i){
string s=folder[i];
string lastFolder=res.back();
lastFolder.push_back('/');
if(s.compare(0, lastFolder.size(), lastFolder)!=0){
res.push_back(s);
}
}
return res;
}
};
// Time Complexity: O(NlogN) for sorting the input vector, where N is the number of folders. The rest of the operations are O(N) for iterating through the sorted list.
// Space Complexity: O(N) for storing the result vector Heap / Priority Queue (8)
○ 215. Kth Largest Element in an Array Medium
#include <vector>
using namespace std;
class Solution {
public:
int quickSelect(vector<int>& nums, int l, int r) {
int randomIdx=std::rand()%(r-l+1)+l;
swap(nums[randomIdx], nums[r]);
int pivot=nums[r];
int i=l;
for(int j=l; j<r; ++j){
if(nums[j]>pivot){
swap(nums[i], nums[j]); // keep larger nums at the left
++i;
}
}
swap(nums[i], nums[r]);
return i;
}
int findKthLargest(vector<int>& nums, int k) {
srand(time(NULL));
int n=nums.size();
int target=k-1;
int l=0, r=n-1;
while(l<=r){
int pidx=quickSelect(nums, l, r);
if(pidx==target){
return nums[pidx];
}
else if(pidx<target){
l=pidx+1;
}
else{ // p>target
r=pidx-1;
}
}
return nums[l];
}
};
// Time Complexity: O(N) on average, O(N^2) in the worst case (when the smallest or largest element is always chosen as the pivot).
// Space Complexity: O(1) for the in-place partitioning. ○ 295. Find Median from Data Stream Hard
class MedianFinder {
priority_queue<int> lo; // max-heap, smaller half
priority_queue<int, vector<int>, greater<int>> hi; // min-heap, larger half
public:
MedianFinder() {}
void addNum(int num) {
lo.push(num);
hi.push(lo.top());
lo.pop();
if (hi.size() > lo.size()) {
lo.push(hi.top());
hi.pop();
}
}
double findMedian() {
if (lo.size() > hi.size()) return lo.top();
return (lo.top() + hi.top()) / 2.0;
}
}; ○ 355. Design Twitter Medium
class Twitter {
int timer = 0;
unordered_map<int, vector<pair<int,int>>> tweets; // user -> (time, tweetId)
unordered_map<int, unordered_set<int>> following; // user -> set of followees
public:
Twitter() {}
void postTweet(int userId, int tweetId) {
tweets[userId].push_back({timer++, tweetId});
}
vector<int> getNewsFeed(int userId) {
// max-heap entries: (time, tweetId, ownerId, index-in-owner-list)
priority_queue<array<int,4>> pq;
unordered_set<int> users = following[userId];
users.insert(userId);
for (int u : users) {
auto& tw = tweets[u];
if (!tw.empty()) {
int idx = tw.size() - 1;
pq.push({tw[idx].first, tw[idx].second, u, idx});
}
}
vector<int> res;
while (!pq.empty() && (int)res.size() < 10) {
auto top = pq.top(); pq.pop();
res.push_back(top[1]);
int u = top[2], idx = top[3];
if (idx > 0) {
auto& tw = tweets[u];
pq.push({tw[idx-1].first, tw[idx-1].second, u, idx-1});
}
}
return res;
}
void follow(int followerId, int followeeId) {
if (followerId != followeeId) following[followerId].insert(followeeId);
}
void unfollow(int followerId, int followeeId) {
following[followerId].erase(followeeId);
}
}; ○ 621. Task Scheduler Medium
class Solution {
public:
int leastInterval(vector<char>& tasks, int n) {
int len=tasks.size();
if(n==0){
return len;
}
int freq[26]={0};
for(const char& c: tasks){
++freq[c-'A'];
}
int max=INT_MIN;
int max_count=0;
for(int i=0; i<26; ++i){
int cur=freq[i];
if(cur>max){
max=cur;
max_count=1;
}
else if(cur==max){
++max_count;
}
}
return std::max(len, (max-1)*(n+1)+max_count);
}
};
// Time Complexity: O(N)
// Space Complexity: O(1) ○ 703. Kth Largest Element in a Stream Easy
class KthLargest {
priority_queue<int, vector<int>, greater<int>> minHeap;
int k;
public:
KthLargest(int k, vector<int>& nums) : k(k) {
for (int x : nums) add(x);
}
int add(int val) {
minHeap.push(val);
while ((int)minHeap.size() > k) minHeap.pop();
return minHeap.top();
}
}; ○ 973. K Closest Points to Origin Medium
class Solution {
public:
vector<vector<int>> kClosest(vector<vector<int>>& points, int k) {
priority_queue<pair<int, int>> maxHeap; // (dist, index)
for (int i = 0; i < (int)points.size(); ++i) {
int d = points[i][0] * points[i][0] + points[i][1] * points[i][1];
maxHeap.push({d, i});
if ((int)maxHeap.size() > k) maxHeap.pop();
}
vector<vector<int>> res;
while (!maxHeap.empty()) {
res.push_back(points[maxHeap.top().second]);
maxHeap.pop();
}
return res;
}
}; ○ 1046. Last Stone Weight Easy
class Solution {
public:
int lastStoneWeight(vector<int>& stones) {
std::priority_queue<int> max_heap(stones.begin(), stones.end());
int x=-1, y=-1;
while(max_heap.size()>1){
y=max_heap.top();
max_heap.pop();
x=max_heap.top();
max_heap.pop();
if(y>x){
max_heap.push(y-x);
}
}
if(max_heap.empty()){
return 0;
}
return max_heap.top();
}
};
// Time Complexity: O(NlogN)
// Space Complexity: O(N) ○ 1801. Number of Orders in the Backlog Medium
class Solution {
public:
int getNumberOfBacklogOrders(vector<vector<int>>& orders) {
std::priority_queue<pair<int, int>> max_buy_orders;
std::priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> min_sell_orders;
for(const auto& order: orders){
int price=order[0];
int amount=order[1];
int orderType=order[2];
if(orderType==0){ // buy
while(amount>0 && !min_sell_orders.empty()){
auto top_cell=min_sell_orders.top();
int sell_price=top_cell.first;
int sell_amount=top_cell.second;
if(sell_price>price){
break;
}
else{ // able to match
min_sell_orders.pop();
if(sell_amount>amount){
min_sell_orders.push({sell_price, sell_amount-amount});
amount=0;
}
else{
amount-=sell_amount;
}
}
}
if(amount>0){
max_buy_orders.push({price, amount});
}
}
else{ // sell
while(amount>0 && !max_buy_orders.empty()){
auto top_cell=max_buy_orders.top();
int buy_price=top_cell.first;
int buy_amount=top_cell.second;
if(buy_price<price){
break;
}
else{ // able to match
max_buy_orders.pop();
if(buy_amount>amount){
max_buy_orders.push({buy_price, buy_amount-amount});
amount=0;
}
else{
amount-=buy_amount;
}
}
}
if(amount>0){
min_sell_orders.push({price, amount});
}
}
}
const long long MOD=1e9+7;
long long res=0;
while(!max_buy_orders.empty()){
res=(res+max_buy_orders.top().second)%MOD;
max_buy_orders.pop();
}
while(!min_sell_orders.empty()){
res=(res+min_sell_orders.top().second)%MOD;
min_sell_orders.pop();
}
return (int)res;
}
};
// Time Complexity: O(NlogN)
// Space Complexity: O(N) Backtracking (9)
○ 17. Letter Combinations of a Phone Number Medium
class Solution {
public:
vector<string> digitsMap={"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
vector<string> letterCombinations(string digits) {
vector<string> result;
if(digits.length()==0)
return result;
string path="";
DFS(result, path, digits, 0);
return result;
}
void DFS(vector<string>& result, string& path, string& digits, int index) {
if(index==digits.length()){
result.push_back(path);
return;
}
string& letters=digitsMap[digits[index]-'2'];
for(char c: letters){
path.push_back(c);
DFS(result, path, digits, index+1);
path.pop_back();
}
}
};
// Time Complexity: O(4^N), but O(4^N * N) for copying the path to the result.
// Space Complexity: O(N), here we only consider the space of auxiliary space. When considering the space of the result, it is O(4^N * N). ○ 39. Combination Sum Medium
class Solution {
public:
void find(vector<vector<int>>& result, vector<int>& cur, vector<int>& candidates, int target, int idx){
if(target==0){
result.push_back(cur);
return;
}
if(target<0 || idx>=candidates.size() || candidates[idx]>target)
return;
cur.push_back(candidates[idx]);
find(result, cur, candidates, target-candidates[idx], idx);
cur.pop_back();
find(result, cur, candidates, target, idx+1);
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> result;
vector<int> cur;
std::sort(candidates.begin(), candidates.end());
find(result, cur, candidates, target, 0);
return result;
}
};
// 2 ...
// 2 2 ...
// 2 3 ...
// ...
// ======= (pop back)
// 3 ...
// ...
// Time Complexity: O(N^T/M) where N is the number of candidates, T is the target, M is the minimum candidate
// Space Complexity: O(T/M) ○ 40. Combination Sum II Medium
class Solution {
public:
void find(vector<vector<int>>& result, vector<int>& cur, vector<int>& candidates, int target, int idx){
if(target==0){
result.push_back(cur);
return;
}
if(target<0 || idx>=candidates.size() || candidates[idx]>target){
return;
}
cur.push_back(candidates[idx]);
find(result, cur, candidates, target-candidates[idx], idx+1);
cur.pop_back();
int next_idx=idx+1;
while(next_idx<candidates.size() && candidates[next_idx]==candidates[next_idx-1]){
++next_idx;
}
find(result, cur, candidates, target, next_idx);
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<vector<int>> result;
vector<int> cur;
std::sort(candidates.begin(), candidates.end());
find(result, cur, candidates, target, 0);
return result;
}
};
// Time Complexity: O(N^T/M) where N is the number of candidates, T is the target, M is the minimum candidate
// Space Complexity: O(T/M) ○ 46. Permutations Medium
class Solution {
public:
void dfs(vector<vector<int>>& res, vector<int>& cur, int n, int idx) {
if(idx==n-1) {
res.push_back(cur);
return;
}
for(int i=idx; i<n; ++i) {
swap(cur[idx], cur[i]);
dfs(res, cur, n, idx+1);
swap(cur[idx], cur[i]);
}
}
vector<vector<int>> permute(vector<int>& nums) {
int n=nums.size();
vector<vector<int>> res;
dfs(res, nums, n, 0);
return res;
}
};
// Time Complexity: O(N!)
// Space Complexity: O(N) ○ 51. N-Queens Hard
class Solution {
public:
void dfs(vector<string>& cur, int n, int curQNum){ // curQNum means current row
if(curQNum==n){
res.push_back(cur);
return;
}
for(int col=0; col<n; ++col){
if(!cols[col] && !diag1[curQNum+col] && !diag2[curQNum-col+n-1]){
cur[curQNum][col]='Q';
cols[col]=true;
diag1[curQNum+col]=true;
diag2[curQNum-col+n-1]=true;
dfs(cur, n, curQNum+1);
cols[col]=false;
cur[curQNum][col]='.';
diag1[curQNum+col]=false;
diag2[curQNum-col+n-1]=false;
}
}
}
vector<vector<string>> solveNQueens(int n) {
vector<string> cur(n, string(n, '.'));
cols.assign(n, false);
diag1.assign(2*n-1, false);
diag2.assign(2*n-1, false);
dfs(cur, n, 0);
return res;
}
vector<vector<string>> res;
vector<bool> cols;
vector<bool> diag1; // 0~2n-2
vector<bool> diag2; // -(n-1)~(n-1) --> 0~2n-2
};
// Time Complexity: O(N!)
// Space Complexity: O(N) ○ 78. Subsets Medium
class Solution {
public:
void getSubset(vector<vector<int>>& res, vector<int>& cur, vector<int>& nums, int idx){
if(idx==nums.size()){
res.push_back(cur);
return;
}
getSubset(res, cur, nums, idx+1);
cur.push_back(nums[idx]);
getSubset(res, cur, nums, idx+1);
cur.pop_back();
}
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> res;
vector<int> cur;
getSubset(res, cur, nums, 0);
return res;
}
};
// Time Complexity: O(2^N * N). Why N? Because we need to copy the current subset to the result.
// Space Complexity: O(2^N * N), and O(N) for the auxiliary space. ○ 79. Word Search Medium
class Solution {
public:
bool dfs(vector<vector<char>>& board, const string& word, int wordIdx, int x, int y){
if(wordIdx==word.length()){
return true;
}
if(x<0 || x>=board.size() || y<0 || y>=board[0].size() || board[x][y]!=word[wordIdx]){
return false;
}
char tmp=board[x][y];
board[x][y]='#';
int dx[]={-1, 1, 0, 0};
int dy[]={0, 0, 1, -1};
for(int i=0; i<4; ++i){
if(dfs(board, word, wordIdx+1, x+dx[i], y+dy[i])){
return true;
}
}
board[x][y]=tmp;
return false;
}
bool exist(vector<vector<char>>& board, string word) {
int m=board.size();
int n=board[0].size();
for(int i=0; i<m; ++i){
for(int j=0; j<n; ++j){
if(dfs(board, word, 0, i, j)){
return true;
}
}
}
return false;
}
};
// Time Complexity: O(M*N*4^L), where M is the number of rows, N is the number of columns, and L is the length of the word.
// Space Complexity: O(L), where L is the length of the word.
// The space complexity is due to the recursion stack. ○ 90. Subsets II Medium
class Solution {
public:
void dfs(vector<vector<int>>& res, const vector<int>& nums, vector<int>& cur, int idx) {
if(idx==nums.size()){
res.push_back(cur);
return;
}
cur.push_back(nums[idx]);
dfs(res, nums, cur, idx+1);
cur.pop_back();
int next=idx+1;
while(next<nums.size() && nums[next]==nums[idx]){
++next;
}
dfs(res, nums, cur, next);
}
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
vector<vector<int>> res;
vector<int> cur;
std::sort(nums.begin(), nums.end());
dfs(res, nums, cur, 0);
return res;
}
};
// Time Complexity: O(2^N * N).
// Space Complexity: O(2^N * N) for the result, O(N) for the auxiliary space. ○ 131. Palindrome Partitioning Medium
class Solution {
public:
vector<vector<bool>> pal;
void dfs(vector<vector<string>>& res, vector<string>& cur, string&s, int start){
if(start==s.length()){
res.push_back(cur);
return;
}
for(int end=start; end<s.length(); ++end){
if(pal[start][end]){
cur.push_back(s.substr(start, end-start+1));
dfs(res, cur, s, end+1);
cur.pop_back();
}
}
}
void expansion(const string& s, int i, int j){
if(i>=0 && j<s.length() && s[i]==s[j]){ // i <= j
pal[i][j]=true;
expansion(s, i-1, j+1);
}
}
vector<vector<string>> partition(string s) {
// preprocess: create a lookup table to check palindrome
int len=s.length();
pal.resize(len, vector<bool>(len, false)); // pal[i][j]: s[i...j] is pal or not
// use center expansion method
for(int i=0; i<len; ++i){
expansion(s, i, i);
expansion(s, i, i+1);
}
// dfs to get the result
vector<vector<string>> res;
vector<string> cur;
dfs(res, cur, s, 0);
return res;
}
};
// Time Complexity: O(N * 2^N). 2^N for generating all partitions, O(N) for copying substring to current partition
// Space Complexity: O(N^2) for palindrome lookup table + O(N) for current partition recursion stack Graphs (15)
○ 127. Word Ladder Hard
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
int len=wordList.size();
unordered_set<string> notVisited(wordList.begin(), wordList.end());
if(!notVisited.count(endWord)){
return 0;
}
queue<string> q;
q.push(beginWord);
int dist=0;
while(!q.empty()){
++dist;
int qlen=q.size();
for(int i=0; i<qlen; ++i){
string cur=q.front();
q.pop();
if(cur==endWord){
return dist;
}
for(int i=0; i<cur.length(); ++i){
char originalChar=cur[i];
for(int j=0; j<26; ++j){
cur[i]='a'+j;
if(notVisited.count(cur)){
q.push(cur);
notVisited.erase(cur);
}
}
cur[i]=originalChar;
}
}
}
return 0;
}
};
// Time Complexity: O(N * M * 26), N is the number of words in wordList, M is the length of each word
// Space Complexity: O(N) ○ 130. Surrounded Regions Medium
class Solution {
public:
void solve(vector<vector<char>>& board) {
const int m=board.size();
const int n=board[0].size();
queue<pair<int, int>> q;
for(int j=0; j<n; ++j){
if(board[0][j]=='O'){
q.push({0, j});
board[0][j]='#';
}
if(board[m-1][j]=='O'){
q.push({m-1, j});
board[m-1][j]='#';
}
}
for(int i=1; i<m-1; ++i){
if(board[i][0]=='O'){
q.push({i, 0});
board[i][0]='#';
}
if(board[i][n-1]=='O'){
q.push({i, n-1});
board[i][n-1]='#';
}
}
const int dirs[4][2]={{-1,0}, {1,0}, {0,-1}, {0,1}};
while(!q.empty()){
auto [x, y]=q.front();
q.pop();
for(auto& d: dirs){
int nx=x+d[0];
int ny=y+d[1];
if(nx>0 && nx<m-1 && ny>0 && ny<n-1 && board[nx][ny]=='O'){
board[nx][ny]='#';
q.push({nx, ny});
}
}
}
for(auto& row: board){
for(char& c: row){
if(c=='#'){
c='O';
}
else if(c=='O'){
c='X';
}
}
}
}
};
// Time Complexity: O(M*N)
// Space Complexity: O(M*N)
○ 133. Clone Graph Medium
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> neighbors;
Node() {
val = 0;
neighbors = vector<Node*>();
}
Node(int _val) {
val = _val;
neighbors = vector<Node*>();
}
Node(int _val, vector<Node*> _neighbors) {
val = _val;
neighbors = _neighbors;
}
};
*/
class Solution {
public:
unordered_map<Node*, Node*> umap; // original node -> cloned node
Node* cloneGraph(Node* node) {
if(!node){
return nullptr;
}
auto it=umap.find(node);
if(it!=umap.end()){
return it->second;
}
Node* root=new Node(node->val);
umap[node]=root;
for(auto& n: node->neighbors){
root->neighbors.push_back(cloneGraph(n));
}
return root;
}
};
// Time Complexity: O(V + E), V is the number of nodes, E is the number of edges
// Space Complexity: O(V) for the hashmap and recursion stack ○ 200. Number of Islands Medium
#include <vector>
using namespace std;
class Solution {
public:
const int dx[4]={-1, 1, 0, 0};
const int dy[4]={0, 0, -1, 1};
void dfs(vector<vector<char>>& grid, int x, int y){
int m=grid.size();
int n=grid[0].size();
grid[x][y]='0';
for(int k=0; k<4; ++k){
int nx=x+dx[k];
int ny=y+dy[k];
if(nx>=0 && nx<m && ny>=0 && ny<n && grid[nx][ny]=='1'){
dfs(grid, nx, ny);
}
}
}
int numIslands(vector<vector<char>>& grid) {
// BFS: O(MN), O(min(M, N))
// DFS: O(MN), O(MN)
// Union Find: O(MN.alpha(MN)), O(MN)
int m=grid.size();
int n=grid[0].size();
int count=0;
for(int i=0; i<m; ++i){
for(int j=0; j<n; ++j){
if(grid[i][j]=='1'){
++count;
dfs(grid, i, j);
}
}
}
return count;
}
};
// Time Complexity: O(MN), since we visit each cell at most once.
// Space Complexity: O(MN) in the worst case (when the grid is filled with land), due to the recursion stack in DFS.
// For BFS, the space complexity would be O(min(M, N)) in the worst case ○ 207. Course Schedule Medium
#include <vector>
#include <queue>
using namespace std;
class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
// topological sort
// 1. create adj list
// 2. start from indegree=0, check if I can go through all the courses
vector<vector<int>> adj(numCourses);
vector<int> inDegree(numCourses, 0);
for(const auto& p: prerequisites){
// [course, its prereq]
adj[p[1]].push_back(p[0]); // take i first, so that we can consider adj[i]
++inDegree[p[0]];
}
queue<int> q; // record those courses with inDegree=0
for(int i=0; i<numCourses; ++i){
if(inDegree[i]==0){
q.push(i);
}
}
int count=0;
while(!q.empty()){
int qlen=q.size();
count+=qlen;
for(int i=0; i<qlen; ++i){
int cur=q.front();
q.pop();
for(const int v: adj[cur]){ // vertex in adj[cur]
--inDegree[v];
if(inDegree[v]==0){
q.push(v);
}
}
}
}
return count==numCourses;
}
};
// Time: O(V+E) where V is the number of courses and E is the number of prerequisites
// Space: O(V+E) for the adjacency list and inDegree array ○ 210. Course Schedule II Medium
#include <vector>
#include <queue>
using namespace std;
class Solution {
public:
vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
// topological sort
// 1. create adj list
// 2. start from those inDegree=0, do bfs
vector<vector<int>> adj(numCourses);
vector<int> inDegree(numCourses, 0);
vector<int> res;
for(const auto& p: prerequisites){
adj[p[1]].push_back(p[0]); // pre: [nexts]
++inDegree[p[0]];
}
queue<int> q; // record all inDegree=0
for(int i=0; i<numCourses; ++i){
if(inDegree[i]==0){
q.push(i);
}
}
while(!q.empty()){
int qlen=q.size();
for(int i=0; i<qlen; ++i){
int cur=q.front();
q.pop();
res.push_back(cur);
for(const int v: adj[cur]){
--inDegree[v];
if(inDegree[v]==0){
q.push(v);
}
}
}
}
return res.size()==numCourses?res:vector<int>{};
}
};
// Time: O(V+E) where V is the number of courses and E is the number of prerequisites
// Space: O(V+E) for the adjacency list and inDegree array ○ 261. Graph Valid Tree Medium
class Solution {
vector<int> parent;
int find(int x) {
while (parent[x] != x) {
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}
public:
bool validTree(int n, vector<vector<int>>& edges) {
if ((int)edges.size() != n - 1) return false;
parent.resize(n);
for (int i = 0; i < n; ++i) parent[i] = i;
for (auto& e : edges) {
int a = find(e[0]), b = find(e[1]);
if (a == b) return false; // cycle
parent[a] = b;
}
return true;
}
}; ○ 286. Walls and Gates Medium
class Solution {
public:
void wallsAndGates(vector<vector<int>>& rooms) {
const int INF = 2147483647;
int m = rooms.size();
if (m == 0) return;
int n = rooms[0].size();
queue<pair<int,int>> q;
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
if (rooms[i][j] == 0) q.push({i, j});
int dirs[5] = {-1, 0, 1, 0, -1};
while (!q.empty()) {
auto [r, c] = q.front(); q.pop();
for (int d = 0; d < 4; ++d) {
int nr = r + dirs[d], nc = c + dirs[d+1];
if (nr < 0 || nc < 0 || nr >= m || nc >= n) continue;
if (rooms[nr][nc] != INF) continue;
rooms[nr][nc] = rooms[r][c] + 1;
q.push({nr, nc});
}
}
}
}; ○ 323. Number of Connected Components in an Undirected Graph Medium
class Solution {
vector<int> parent, rnk;
int find(int x) {
while (parent[x] != x) {
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}
public:
int countComponents(int n, vector<vector<int>>& edges) {
parent.resize(n);
rnk.assign(n, 0);
for (int i = 0; i < n; ++i) parent[i] = i;
int count = n;
for (auto& e : edges) {
int a = find(e[0]), b = find(e[1]);
if (a == b) continue;
if (rnk[a] < rnk[b]) swap(a, b);
parent[b] = a;
if (rnk[a] == rnk[b]) rnk[a]++;
count--;
}
return count;
}
}; ○ 399. Evaluate Division Medium
#include <unordered_map>
#include <unordered_set>
#include <queue>
using namespace std;
class Solution {
public:
vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) {
unordered_map<string, unordered_map<string, double>> g;
// build the graph
int n=equations.size();
for(int i=0; i<n; ++i){
string a=equations[i][0];
string b=equations[i][1];
double val=values[i];
g[a][b]=val;
g[b][a]=1/val;
}
// do bfs
vector<double> res;
for(const auto& query: queries){
string a=query[0];
string b=query[1];
if(!g.count(a) || !g.count(b)){
res.push_back(-1.0);
continue;
}
// find a path from a to b
unordered_set<string> visited;
queue<pair<string, double>> q;
q.push({a, 1.0});
visited.insert(a);
bool found=false;
double ans=-1.0;
while(!q.empty()){
auto [u, prod]=q.front();
q.pop();
if(u==b){
found=true;
ans=prod;
}
for(const auto& [node, weight]: g[u]){
if(!visited.count(node)){
q.push({node, weight*prod});
visited.insert(u);
}
}
}
res.push_back(ans);
}
return res;
}
};
// Time Complexity: O(Q*(V+E)), where Q is the number of queries, V is the number of variables, and E is the number of equations.
// Space Complexity: O(V+E) for the graph, O(V) for the visited set, and O(Q) for the result vector. ○ 417. Pacific Atlantic Water Flow Medium
#include <vector>
using namespace std;
class Solution {
public:
int m, n;
int dx[4]={-1, 1, 0, 0};
int dy[4]={0, 0, -1, 1};
void dfs(int x, int y, int prev_h, const vector<vector<int>>& h, vector<vector<bool>>& visited){
if(x<0 || x>=m || y<0 || y>=n || visited[x][y] || h[x][y]<prev_h){
return;
}
visited[x][y]=true;
for(int i=0; i<4; ++i){
dfs(x+dx[i], y+dy[i], h[x][y], h, visited);
}
}
vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {
m=heights.size();
n=heights[0].size();
vector<vector<bool>> pac(m, vector<bool>(n, false));
vector<vector<bool>> atl(m, vector<bool>(n, false));
for(int i=0; i<m; ++i){
dfs(i, 0, 0, heights, pac);
dfs(i, n-1, 0, heights, atl);
}
for(int j=0; j<n; ++j){
dfs(0, j, 0, heights, pac);
dfs(m-1, j, 0, heights, atl);
}
vector<vector<int>> res;
for(int i=0; i<m; ++i){
for(int j=0; j<n; ++j){
if(pac[i][j] && atl[i][j]){
res.push_back({i, j});
}
}
}
return res;
}
};
// Time: O(M*N)
// Space: O(M*N) ○ 684. Redundant Connection Medium
class Solution {
public:
int find(vector<int>& parents, int idx){
if(parents[idx]==idx){
return idx;
}
return parents[idx]=find(parents, parents[idx]);
}
vector<int> findRedundantConnection(vector<vector<int>>& edges) {
int n=edges.size();
vector<int> parents(n+1);
vector<int> ranks(n+1, 1);
for(int i=1; i<=n; ++i){
parents[i]=i;
}
for(const auto& e: edges){
// find parents
int a=e[0];
int b=e[1];
int pa=find(parents, a);
int pb=find(parents, b);
// if same: return this edge
if(pa==pb){
return e;
}
// if not same: join
if(ranks[pa]>ranks[pb]){
parents[pb]=pa;
}
else if(ranks[pb]>ranks[pa]){
parents[pa]=pb;
}
else{ // rank: pa==pb
parents[pb]=pa;
++ranks[pa];
}
}
return {};
}
};
// Time Complexity: O(N * α(N)), where α is the Inverse Ackermann function, can be considered nearly constant.
// Space Complexity: O(N) ○ 695. Max Area of Island Medium
#include <vector>
#include <queue>
using namespace std;
class Solution {
public:
// void dfs(vector<vector<int>>& grid, int& curArea, int x, int y){
// if(x<0 || x>=grid.size() || y<0 || y>=grid[0].size() || grid[x][y]==0){
// return;
// }
// ++curArea;
// grid[x][y]=0;
// for(int i=0; i<4; ++i){
// dfs(grid, curArea, x+dx[i], y+dy[i]);
// }
// }
int maxAreaOfIsland(vector<vector<int>>& grid) {
int m=grid.size();
int n=grid[0].size();
int maxArea=0;
queue<pair<int, int>> q;
const int dx[4]={-1, 1, 0, 0};
const int dy[4]={0, 0, -1, 1};
for(int i=0; i<m; ++i){
for(int j=0; j<n; ++j){
if(grid[i][j]==1){
int curArea=0;
// bfs
q.push({i, j});
grid[i][j]=0;
while(!q.empty()){
// int curLen=q.size();
// for(int i=0; i<curLen; ++i){
auto [x, y]=q.front();
q.pop();
++curArea;
for(int k=0; k<4; ++k){
int nx=x+dx[k];
int ny=y+dy[k];
if(nx<0 || nx>=m || ny<0 || ny>=n || grid[nx][ny]==0){
continue;
}
q.push({nx, ny});
grid[nx][ny]=0;
}
// }
}
maxArea=max(maxArea, curArea);
}
}
}
return maxArea;
}
}; ○ 994. Rotting Oranges Medium
class Solution {
public:
int orangesRotting(vector<vector<int>>& grid) {
// use bfs to solve the problem
queue<pair<int, int>> q; // store rotten oranges
int freshCount=0;
int time=0;
for(int i=0; i<grid.size(); ++i){
for(int j=0; j<grid[0].size(); ++j){
if(grid[i][j]==0)
continue;
else if(grid[i][j]==1)
++freshCount;
else // grid[i][j]==2
q.push({i, j});
}
}
if(freshCount==0)
return 0;
vector<pair<int,int>> directions={{0,1}, {0,-1}, {1,0}, {-1,0}};
while(!q.empty()){
int curNum=q.size();
for(int i=0; i<curNum; ++i){
auto cur=q.front();
q.pop();
int row=cur.first;
int col=cur.second;
for(auto& dir: directions){
int x=row+dir.first;
int y=col+dir.second;
if(x>=0 && y>=0 && x<grid.size() && y<grid[0].size() && grid[x][y]==1){
grid[x][y]=2;
q.push({x,y});
--freshCount;
}
}
}
if(!q.empty())
++time;
}
if(freshCount!=0)
return -1;
return time;
}
};
// Time: O(M*N)
// Space: O(M*N), for the queue to store the rotten oranges ○ 1462. Course Schedule IV Medium
#include <vector>
using namespace std;
class Solution {
public:
// int dfs(vector<vector<int>>& adj, vector<vector<int>>& memo, int s, int t){ // s: source, t: destination
bool dfs(vector<vector<int>>& adj, vector<bool>& visited, int s, int t){ // s: source, t: destination
if(s==t){
return true;
}
// if(memo[s][t]!=-1){
// return memo[s][t];
// }
// for(const int next: adj[s]){
// if(dfs(adj, memo, next, t)==1){
// memo[next][t]=1;
// return 1;
// }
// }
// memo[s][t]=0;
// return 0;
visited[s]=true;
for(const int next: adj[s]){
if(!visited[next]){
if(dfs(adj, visited, next, t)){
return true;
}
}
}
return false;
}
vector<bool> checkIfPrerequisite(int numCourses, vector<vector<int>>& prerequisites, vector<vector<int>>& queries) {
vector<vector<int>> adj(numCourses);
for(const auto& p: prerequisites){
adj[p[0]].push_back(p[1]);
}
vector<bool> res;
// vector<vector<int>> memo(numCourses, vector<int>(numCourses, -1)); // -1: not visited yet, 0: not reachable, 1: reachable
vector<bool> visited(numCourses, false);
for(const auto& q: queries){
// res.push_back(dfs(adj, memo, q[0], q[1])==1);
vector<bool> visited(numCourses, false);
res.push_back(dfs(adj, visited, q[0], q[1]));
}
return res;
}
/*
vector<bool> checkIfPrerequisite(int numCourses, vector<vector<int>>& prerequisites, vector<vector<int>>& queries) {
// topological sort (Q is large)
// 1. create adj list, inDegree
// 2. for each inDegree, do bfs, update table
// time: O(E*V)
// space: O(V*V)
vector<vector<int>> adj(numCourses);
vector<int> inDegree(numCourses, 0);
for(const auto& p: prerequisites){
adj[p[0]].push_back(p[1]);
++inDegree[p[1]];
}
queue<int> q;
vector<bool> res;
vector<vector<int>> table(numCourses, vector<int>(numCourses, false));
for(int i=0; i<numCourses; ++i){
if(inDegree[i]==0){
q.push(i);
}
}
while(!q.empty()){
int qlen=q.size();
for(int i=0; i<qlen; ++i){
int cur=q.front();
q.pop();
for(const int v: adj[cur]){
table[cur][v]=true;
// update table
for(int j=0; j<numCourses; ++j){
if(table[j][cur]){
table[j][v]=true;
}
}
--inDegree[v];
if(inDegree[v]==0){
q.push(v);
}
}
}
}
for(const auto& q: queries){
res.push_back(table[q[0]][q[1]]);
}
return res;
}
*/
};
// for DFS
// Time: O((V+E)*Q) where Q is the number of queries, V is the number of courses, and E is the number of prerequisites
// Space: O(V+E) for the adjacency list and O(V^2) for the memoization table
// for DFS with memoization
// Time: O(V*E+Q)
// Space: O(V*V) for the memoization table
// for topological sort
// Time: O(V*E+Q)
// Space: O(V*V) for the table and O(V+E) for the adjacency list and inDegree array Advanced Graphs (8)
○ 269. Alien Dictionary Hard
#include <string>
#include <vector>
#include <unordered_set>
#include <unordered_map>
#include <queue>
using namespace std;
class Solution {
public:
string alienOrder(vector<string>& words) {
if(words.empty()){
return "";
}
std::unordered_set<char> all_chars;
for(const string& w: words){
for(const char& c: w){
all_chars.insert(c);
}
}
// build inDegree
std::unordered_map<char, int> inDegree;
for(const char c: all_chars){
inDegree[c]=0;
}
// build adj list
std::unordered_map<char, std::unordered_set<char>> adj;
for(int i=0; i<words.size()-1; ++i){
const string& s1=words[i];
const string& s2=words[i+1];
int len1=s1.length();
int len2=s2.length();
bool foundDiff=false;
for(int j=0; j<std::min(len1, len2); ++j){
if(s1[j]!=s2[j]){
if(!adj[s1[j]].count(s2[j])){
adj[s1[j]].insert(s2[j]);
++inDegree[s2[j]];
}
foundDiff=true;
break;
}
}
if(!foundDiff && len1>len2){
return "";
}
}
// bfs
string res="";
queue<char> q;
for(const auto& [ch, degree]: inDegree){
if(degree==0){
q.push(ch);
}
}
while(!q.empty()){
char u=q.front();
q.pop();
res+=u;
for(char v: adj[u]){
--inDegree[v];
if(inDegree[v]==0){
q.push(v);
}
}
}
if(res.length()!=all_chars.size()){
return "";
}
return res;
}
};
// Time Complexity: O(C) where C is the total number of characters in all words. We need to iterate through all characters to build the graph and perform BFS.
// Space Complexity: O(U+E) where U is the number of unique characters and E is the number of edges in the graph. We need space to store the graph and the in-degree of each character.
// But it's bound by 26^2, so we can consider it O(1) in terms of space complexity. ○ 305. Number of Islands II Hard
#include <vector>
using namespace std;
class Solution {
public:
// int find(vector<int>& parent, int idx){
// if(parent[idx]==idx){
// return idx;
// }
// return parent[idx]=find(parent, parent[idx]);
// }
// vector<int> numIslands2(int m, int n, vector<vector<int>>& positions) {
// vector<int> parent(m*n, -1);
// vector<int> rank(m*n, 0);
// vector<int> res;
// int count=0;
// int dx[4]={-1, 1, 0, 0};
// int dy[4]={0, 0, -1, 1};
// for(const auto& p: positions){
// int x=p[0];
// int y=p[1];
// int idx=x*n+y;
// if(parent[idx]!=-1){
// res.push_back(count);
// continue;
// }
// parent[idx]=idx;
// ++count;
// ++rank[idx];
// for(int i=0; i<4; ++i){
// int nx=x+dx[i];
// int ny=y+dy[i];
// int nidx=nx*n+ny;
// if(nx>=0 && nx<m && ny>=0 && ny<n && parent[nidx]!=-1){
// int r1=find(parent, idx);
// int r2=find(parent, nidx);
// if(r1==r2){
// continue;
// }
// if(rank[r1]<rank[r2]){
// parent[r1]=r2;
// }
// else if(rank[r1]>rank[r2]){
// parent[r2]=r1;
// }
// else{
// parent[r1]=r2;
// ++rank[r2];
// }
// --count;
// }
// }
// if(count<0){
// count=0;
// }
// res.push_back(count);
// }
// return res;
// }
struct DSU {
vector<int> parent;
vector<int> rank;
int count;
DSU(int n): parent(n, -1), rank(n, 0), count(0){}
bool addLand(int idx){
if(parent[idx]!=-1){
return false;
}
parent[idx]=idx;
++count;
// ++rank[idx];
return true;
}
int find(int idx){
if(idx!=parent[idx]){
parent[idx]=find(parent[idx]);
}
return parent[idx];
}
void unite(int i, int j){
int r1=find(i);
int r2=find(j);
if(r1!=r2){
if(rank[r1]>rank[r2]){
parent[r2]=r1;
}
else if(rank[r2]>rank[r1]){
parent[r1]=r2;
}
else{
parent[r2]=r1;
++rank[r1];
}
--count;
}
}
};
vector<int> numIslands2(int m, int n, vector<vector<int>>& positions) {
DSU dsu(m*n);
vector<int> res;
int dx[4]={-1, 1, 0, 0};
int dy[4]={0, 0, -1, 1};
for(const auto& p: positions){
int x=p[0];
int y=p[1];
int idx=x*n+y;
if(!dsu.addLand(idx)){
res.push_back(dsu.count);
continue;
}
for(int i=0; i<4; ++i){
int nx=x+dx[i];
int ny=y+dy[i];
int nidx=nx*n+ny;
if(nx>=0 && nx<m && ny>=0 && ny<n && dsu.parent[nidx]!=-1){
dsu.unite(idx, nidx);
}
}
res.push_back(dsu.count);
}
return res;
}
};
// By using path compression and union by rank, the DSU operations (find and unite) run in nearly O(1) time
// Time Complexity: O(m*n + k*alpha(m*n)) where k is the number of positions, m and n are the dimensions of the grid, and alpha is the inverse Ackermann function which is very slow growing and can be considered almost constant in practice.
// Space Complexity: O(m*n) for the DSU data structure to store the parent and rank arrays. ○ 307. Range Sum Query - Mutable Medium
class NumArray {
public:
NumArray(vector<int>& nums) {
N=nums.size();
tree.resize(N*4, 0);
buildTree(nums, 1, 0, N-1);
}
void update(int index, int val) {
updateTree(1, 0, N-1, index, val);
}
int sumRange(int left, int right) {
return getSum(1, 0, N-1, left, right);
}
private:
vector<int> tree; // the index of root node is 1
int N; // N is the size of the nums
void buildTree(vector<int>& nums, int treeIdx, int start, int end) {
if(start==end) {
tree[treeIdx]=nums[start];
return;
}
int mid=(start+end)/2;
buildTree(nums, treeIdx*2, start, mid);
buildTree(nums, treeIdx*2+1, mid+1, end);
tree[treeIdx]=tree[treeIdx*2]+tree[treeIdx*2+1];
}
int getSum(int treeIdx, int curLeft, int curRight, int targetLeft, int targetRight) {
if (curLeft>=targetLeft && curRight<= targetRight)
return tree[treeIdx];
else if (curRight<targetLeft || curLeft>targetRight)
return 0;
else {
int mid=(curLeft+curRight)/2;
return getSum(treeIdx*2, curLeft, mid, targetLeft, targetRight)+getSum(treeIdx*2+1, mid+1, curRight, targetLeft, targetRight);
}
}
void updateTree(int treeIdx, int start, int end, int targetIdx, int val) {
if (start==end) {
tree[treeIdx]=val;
return;
}
int mid=(start+end)/2;
if (targetIdx<=mid) {
updateTree(treeIdx*2, start, mid, targetIdx, val);
}
else {
updateTree(treeIdx*2+1, mid+1, end, targetIdx, val);
}
tree[treeIdx]=tree[treeIdx*2]+tree[treeIdx*2+1];
};
};
// Time: O(log N) for update and sumRange, O(N) for buildTree
// Space: O(4N) for the tree ○ 332. Reconstruct Itinerary Hard
class Solution {
public:
vector<string> findItinerary(vector<vector<string>>& tickets) {
unordered_map<string, multiset<string>> adj;
for (auto& t : tickets) adj[t[0]].insert(t[1]);
vector<string> route;
stack<string> st;
st.push("JFK");
while (!st.empty()) {
string u = st.top();
auto& dests = adj[u];
if (dests.empty()) {
route.push_back(u);
st.pop();
} else {
string v = *dests.begin();
dests.erase(dests.begin());
st.push(v);
}
}
reverse(route.begin(), route.end());
return route;
}
}; ○ 743. Network Delay Time Medium
#include <vector>
#include <queue>
// #include <climits>
using namespace std;
class Solution {
public:
int networkDelayTime(vector<vector<int>>& times, int n, int k) {
// Dijkstra: single source
// keep adding the min time edge to our graph
// to achieve this, we need to maintain a pq
// time: O(ElogV)
// space: O(V+E)
// init adj list
vector<vector<pair<int, int>>> adj(n+1);
for(const auto& t: times){
adj[t[0]].push_back({t[1], t[2]}); // key is the source node
}
// init dist
vector<int> dist(n+1, INT_MAX);
dist[k]=0;
// init pq, it stores {w, u}
std::priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq; // min_heap
pq.push({0, k});
// do Dijkstra's Algo
while(!pq.empty()){
const auto [d, u]=pq.top();
pq.pop();
if(d>dist[u]){
continue;
}
for(const auto& edge: adj[u]){
int v=edge.first;
int w=edge.second;
if(dist[v]>dist[u]+w){
dist[v]=dist[u]+w;
pq.push({dist[v], v});
}
}
}
int maxDist=INT_MIN;
for(int i=1; i<=n; ++i){
if(dist[i]==INT_MAX){
return -1;
}
maxDist=std::max(maxDist, dist[i]);
}
return maxDist;
}
};
// Time: O(ElogV) or O(ElogE) since E can be at most V^2, O(ElogV^2) = O(2ElogV) = O(ElogV)
// Space: O(V+E) for the adjacency list and distance array ○ 778. Swim in Rising Water Hard
class Solution {
public:
int swimInWater(vector<vector<int>>& grid) {
int n = grid.size();
vector<vector<bool>> visited(n, vector<bool>(n, false));
priority_queue<array<int,3>, vector<array<int,3>>, greater<array<int,3>>> pq;
pq.push({grid[0][0], 0, 0}); // (time, row, col)
int dirs[5] = {-1, 0, 1, 0, -1};
while (!pq.empty()) {
auto [t, r, c] = pq.top(); pq.pop();
if (r == n - 1 && c == n - 1) return t;
if (visited[r][c]) continue;
visited[r][c] = true;
for (int d = 0; d < 4; ++d) {
int nr = r + dirs[d], nc = c + dirs[d+1];
if (nr < 0 || nc < 0 || nr >= n || nc >= n) continue;
if (visited[nr][nc]) continue;
pq.push({max(t, grid[nr][nc]), nr, nc});
}
}
return -1;
}
}; ○ 787. Cheapest Flights Within K Stops Medium
class Solution {
public:
int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int k) {
const int INF = 1e9;
vector<int> cost(n, INF);
cost[src] = 0;
for (int i = 0; i <= k; ++i) {
vector<int> tmp = cost;
for (auto& f : flights) {
int u = f[0], v = f[1], w = f[2];
if (cost[u] == INF) continue;
tmp[v] = min(tmp[v], cost[u] + w);
}
cost = tmp;
}
return cost[dst] == INF ? -1 : cost[dst];
}
}; ○ 1584. Min Cost to Connect All Points Medium
class Solution {
public:
int minCostConnectPoints(vector<vector<int>>& points) {
int cost=0;
int n=points.size();
vector<bool> visited(n, false);
vector<int> dist(n, INT_MAX);
// start from any point
dist[0]=0;
int count=0; // node count
while(count<n){
int u=-1;
int min_dist=INT_MAX;
for(int i=0; i<n; ++i){
if(!visited[i] && dist[i]<min_dist){
u=i;
min_dist=dist[i];
}
}
if(u==-1){
break;
}
visited[u]=true;
cost+=min_dist;
++count;
// update dist
for(int v=0; v<n; ++v){
if(!visited[v]){
int d=abs(points[v][0]-points[u][0])+abs(points[v][1]-points[u][1]);
dist[v]=min(dist[v], d);
}
}
}
return cost;
}
};
// Time Complexity: O(N^2)
// Space Complexity: O(N) 1-D Dynamic Programming (15)
○ 5. Longest Palindromic Substring Medium
#include <algorithm>
#include <string>
using namespace std;
class Solution {
public:
int expandAroundCenter(const string &s, int leftIdx, int rightIdx) {
int strLen = s.length();
while (leftIdx >= 0 && rightIdx < strLen && s[leftIdx] == s[rightIdx]) {
leftIdx--;
rightIdx++;
}
return rightIdx - leftIdx - 1;
}
string longestPalindrome(string s) {
// there are two types of palindrome, odd-length and even-length
int strLen = s.length();
int maxLen = 1;
int startOfMaxLen = 0;
for (int i = 0; i < strLen; i++) {
int len1 = expandAroundCenter(s, i, i);
int len2 = expandAroundCenter(s, i, i + 1);
int curLen = max(len1, len2);
if (curLen > maxLen) {
maxLen = curLen;
startOfMaxLen = i - (curLen - 1) / 2;
}
}
return s.substr(startOfMaxLen, maxLen);
}
};
// Time: O(n^2)
// Space: O(1) ○ 70. Climbing Stairs Easy
class Solution {
public:
int climbStairs(int n) {
if(n<2){
return n;
}
int prev1=2;
int prev2=1;
for(int i=3; i<=n; ++i){
int cur=prev1+prev2;
prev2=prev1;
prev1=cur;
}
return prev1;
}
};
// Time Complexity: O(N)
// Space Complexity: O(1) ○ 91. Decode Ways Medium
class Solution {
public:
int numDecodings(string s) {
int len=s.length();
if(len==0 || s[0]=='0'){
return 0;
}
int prev2=1;
int prev1=1;
for(int i=1; i<len; ++i){
int cur=0;
if(s[i]!='0'){
cur+=prev1;
}
int twoDigits=stoi(s.substr(i-1, 2));
if(twoDigits>=10 && twoDigits<=26){
cur+=prev2;
}
prev2=prev1;
prev1=cur;
if(prev1==0){
return 0;
}
}
return prev1;
}
};
// Time Complexity: O(N)
// Space Complexity: O(1) ○ 123. Best Time to Buy and Sell Stock III Hard
class Solution {
public:
/*
int maxProfit(vector<int>& prices) {
int n=prices.size(); // n is the total number of days
// dp[i][k][0/1] means day i, already k transactions, notHold/hold
vector<vector<vector<int>>> dp(n, vector<vector<int>>(3, vector<int>(2, -1e5)));
// initialization
dp[0][0][1]=-prices[0];
for(int i=1; i<n; i++){
dp[i][0][1]=max(dp[i-1][0][1], -prices[i]);
dp[i][1][0]=max(dp[i-1][1][0], dp[i-1][0][1]+prices[i]);
dp[i][1][1]=max(dp[i-1][1][1], dp[i-1][1][0]-prices[i]);
dp[i][2][0]=max(dp[i-1][2][0], dp[i-1][1][1]+prices[i]);
}
int result=max(dp[n-1][1][0], dp[n-1][2][0]);
return max(0, result);
}
*/
/*
int maxProfit(vector<int>& prices) {
int n=prices.size();
vector<vector<vector<int>>> dp(2, vector<vector<int>>(3, vector<int>(2, -1e5)));
dp[0][0][1]=-prices[0];
for(int i=1; i<n; i++){
dp[1][0][1]=max(dp[0][0][1], -prices[i]);
dp[1][1][0]=max(dp[0][1][0], dp[0][0][1]+prices[i]);
dp[1][1][1]=max(dp[0][1][1], dp[0][1][0]-prices[i]);
dp[1][2][0]=max(dp[0][2][0], dp[0][1][1]+prices[i]);
dp[0][0][1]=dp[1][0][1];
dp[0][1][0]=dp[1][1][0];
dp[0][1][1]=dp[1][1][1];
dp[0][2][0]=dp[1][2][0];
}
int result=max(dp[1][1][0], dp[1][2][0]);
return max(0, result);
}
*/
int maxProfit(vector<int>& prices) {
int n=prices.size();
vector<int> buy(3, -1e5); // buy[j] ending with the jth buy
vector<int> sell(3, 0); // sell[j] ending with the jth sell
for(int price: prices){
for(int j=1; j<=2; j++){
buy[j]=max(buy[j], sell[j-1]-price);
sell[j]=max(sell[j], buy[j]+price);
}
}
return sell[2];
}
};
// Time Complexity: O(n)
// Space Complexity: O(1) ○ 139. Word Break Medium
struct TrieNode {
TrieNode* children[26];
bool isEnd=false;
};
class Solution {
TrieNode* root=new TrieNode();
void insert(const string& word){
TrieNode* node=root;
for(char c: word){
if(!node->children[c-'a']){
node->children[c-'a']=new TrieNode();
}
node=node->children[c-'a'];
}
node->isEnd=true;
}
public:
bool wordBreak(string s, vector<string>& wordDict) {
// uset: store words
// dp[i]: dp[1...i] can be made up by words
// maxWordLen
// every time, we check dp[i-1]~dp[i-maxWordLen] exist in uset
// return dp[len]
// int len=s.length();
// int maxWordLen=INT_MIN;
// unordered_set<string_view> uset(wordDict.begin(), wordDict.end()); // n elements
// vector<bool> dp(len+1, false);
// for(const string& w: wordDict){
// maxWordLen=max(maxWordLen, (int)w.length());
// }
// dp[0]=true;
// string_view sv(s);
// for(int i=1; i<=len; ++i){
// for(int j=i-1; j>=0; --j){
// if(!dp[j] || i-j>maxWordLen){ // cur string len = i-j
// continue;
// }
// if(uset.count(sv.substr(j, i-j))){
// dp[i]=true;
// break;
// }
// }
// }
// return dp[len];
int len=s.length();
vector<bool> dp(len+1, false);
for(const string& w: wordDict){
insert(w);
}
dp[0]=true;
for(int i=0; i<len; ++i){
if(!dp[i]){
continue;
}
TrieNode* tmp=root;
for(int j=i; j<len; ++j){
int cur=s[j]-'a';
if(!tmp->children[cur]){
break;
}
tmp=tmp->children[cur];
if(tmp->isEnd){
dp[j+1]=true;
}
}
}
return dp[len];
}
};
// Time Complexity: O(len * maxWordLen)
// Space Complexity: O(N) for dp array and O(M) for unordered_set ○ 152. Maximum Product Subarray Medium
#include <vector>
using namespace std;
class Solution {
public:
int maxProduct(vector<int>& nums) {
int curMin=nums[0];
int curMax=nums[0];
int globalMax=nums[0];
for(int i=1; i<nums.size(); ++i){
int n=nums[i];
if(n>=0){
curMin=std::min(curMin*n, n);
curMax=std::max(curMax*n, n);
}
else{ // n<0
int tmpMin=curMin;
curMin=std::min(curMax*n, n);
curMax=std::max(tmpMin*n, n);
}
globalMax=std::max(globalMax, curMax);
}
return globalMax;
}
};
// Time Complexity: O(N)
// Space Complexity: O(1) ○ 198. House Robber Medium
#include <vector>
using namespace std;
class Solution {
public:
int rob(vector<int>& nums) {
int prev1=0;
int prev2=0;
for(const int n: nums){
int cur=std::max(prev1, n+prev2);
prev2=prev1;
prev1=cur;
}
return prev1;
}
};
// Time: O(N)
// Space: O(1) ○ 213. House Robber II Medium
#include <vector>
using namespace std;
class Solution {
public:
int rob(vector<int>& nums) {
// 1. include nums[0]: find max in nums[2, ..., n-2]
// 2. not include nums[0]: find max in nums[1, ..., n-1]
int n=nums.size();
int prev1=0;
int prev2=0;
for(int i=2; i<n-1; ++i){
int cur=std::max(prev1, prev2+nums[i]);
prev2=prev1;
prev1=cur;
}
int max1=prev1+nums[0]; // nums[0] is 0 or positive
prev1=0;
prev2=0;
for(int i=1; i<n; ++i){
int cur=std::max(prev1, prev2+nums[i]);
prev2=prev1;
prev1=cur;
}
int max2=prev1;
return std::max(max1, max2);
}
};
// Time: O(N)
// Space: O(1) ○ 300. Longest Increasing Subsequence Medium
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
vector<int> tails;
for (int x : nums) {
auto it = lower_bound(tails.begin(), tails.end(), x);
if (it == tails.end()) tails.push_back(x);
else *it = x;
}
return tails.size();
}
}; ○ 303. Range Sum Query - Immutable Easy
class NumArray {
public:
NumArray(vector<int>& nums) {
int N=nums.size();
accSum.resize(N+1, 0);
for(int i=0; i<N; ++i){
accSum[i+1]=accSum[i]+nums[i]; // accSum[1]=nums[0], accSum[2]=nums[0]+nums[1], ...
}
}
int sumRange(int left, int right) {
return accSum[right+1]-accSum[left];
}
vector<int> accSum; // accumulated sum
};
// Time Complexity: O(N) for constructor, O(1) for sumRange
// Space Complexity: O(N) for accSum ○ 332. Coin Challenge Medium
#include <vector>
#include <algorithm>
class Solution {
public:
int coinChange(std::vector<int>& coins, int amount) {
// build a vector, to record the fewest num of coins to make up the corresponding amount
std::vector<int> dp(amount+1, amount+1);
// base case
dp[0]=0;
/* not necessary
for(int deno: coins){
if(deno<=amount){
dp[deno]=1;
}
}
*/
for(int i=1; i<amount+1; i++){
for(int deno: coins){
if(i-deno>=0)
dp[i]=std::min(dp[i-deno]+1, dp[i]);
}
}
return (dp[amount]>amount)? -1 : dp[amount];
}
};
// Time Complexity: O(n*m) where n is the amount and m is the number of coins
// Space Complexity: O(n) ○ 416. Partition Equal Subset Sum Medium
class Solution {
public:
bool canPartition(vector<int>& nums) {
int total = 0;
for (int x : nums) total += x;
if (total % 2 != 0) return false;
int target = total / 2;
vector<bool> dp(target + 1, false);
dp[0] = true;
for (int num : nums) {
for (int s = target; s >= num; --s) {
if (dp[s - num]) dp[s] = true;
}
}
return dp[target];
}
}; ○ 647. Palindromic Substrings Medium
#include <string>
using namespace std;
class Solution {
public:
int expand(const string& s, int l, int r){
int count=0;
while(l>=0 && r<s.length() && s[l]==s[r]){
++count;
--l;
++r;
}
return count;
}
int countSubstrings(string s) {
int count=0;
int len=s.length();
for(int i=0; i<len; ++i){
count+=expand(s, i, i);
count+=expand(s, i, i+1);
}
return count;
}
};
// Time Complexity: O(N^2)
// Space Complexity: O(1) ○ 714. Best Time to Buy and Sell Stock with Transaction Fee Medium
class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
int numOfDays=prices.size();
vector<int> hold(numOfDays, 0);
vector<int> notHold(numOfDays, 0);
hold[0]=-prices[0];
notHold[0]=0;
for(int i=1; i<numOfDays; i++){
hold[i]=max(hold[i-1], notHold[i-1]-prices[i]);
notHold[i]=max(notHold[i-1], hold[i-1]+prices[i]-fee);
}
return notHold[numOfDays-1];
}
};
// Time Complexity: O(n)
// Space Complexity: O(n), could be optimized to O(1) ○ 746. Min Cost Climbing Stairs Easy
#include <vector>
using namespace std;
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
// 1. f(k)=min(f(k-1)+cost(k-1), f(k-2)+cost(k-2)), f(0)=f(1)=0, start from n, recursively, without paying the kth cost
// 2. f(0)=f(1)=0, same formula, but start from 2 to n
// to save the memory, we can use only two vars to memorize the previous two nums
int prev2=0, prev1=0;
for(int i=2; i<=cost.size(); ++i){
int cur=std::min(prev2+cost[i-2], prev1+cost[i-1]);
prev2=prev1;
prev1=cur;
}
return prev1;
}
};
// Time Complexity: O(N)
// Space Complexity: O(1) 2-D Dynamic Programming (13)
○ 10. Regular Expression Matching Hard
class Solution {
public:
bool isMatch(string s, string p) {
int slen=s.length();
int plen=p.length();
vector<vector<bool>> dp(slen+1, vector<bool>(plen+1, false)); // 1-based indice
// initialize
dp[0][0]=true;
for(int j=1; j<=plen; ++j){
if(p[j-1]=='*'){
dp[0][j]=dp[0][j-2];
}
}
for(int i=1; i<=slen; ++i){
for(int j=1; j<=plen; ++j){
if(p[j-1]!='*'){
if(p[j-1]=='.'||s[i-1]==p[j-1])
dp[i][j]=dp[i-1][j-1];
}
else{ // p[j]=='*'
// zero || one or more preceding element
dp[i][j]=dp[i][j-2];
if(s[i-1]==p[j-2]||p[j-2]=='.'){
dp[i][j]=dp[i][j]||dp[i-1][j];
}
}
}
}
return dp[slen][plen];
}
};
// Time: O(M*N), where M is the length of s and N is the length of p
// Space: O(M*N) ○ 62. Unique Paths Medium
class Solution {
public:
int uniquePaths(int m, int n) {
vector<int> res(n, 1);
for(int row=1; row<m; ++row){
for(int col=1; col<n; ++col){
res[col]+=res[col-1];
}
}
return res[n-1];
}
};
// Time Complexity: O(M*N)
// Space Complexity: O(N) ○ 72. Edit Distance Medium
class Solution {
public:
int minDistance(string word1, string word2) {
// - - h o r s e (len1)
// - 0 1 2 3 4 5
// r 1
// o 2
// s 3
// (len2)
int len1=word1.size();
int len2=word2.size();
vector<int> dp(len1+1, 0);
// init dp
for(int j=0; j<=len1; ++j){
dp[j]=j;
}
for(int i=1; i<=len2; ++i){
int prev_diag=dp[0]; // record prev[j-1]
int tmp=0;
dp[0]=i;
for(int j=1; j<=len1; ++j){
tmp=dp[j];
if(word1[j-1]==word2[i-1]){
dp[j]=prev_diag;
}
else{
dp[j]=std::min(dp[j-1], std::min(prev_diag, dp[j]))+1;
}
prev_diag=tmp;
}
}
return dp[len1];
}
};
// Time Complexity: O(M*N)
// Space Complexity: O(N) ○ 97. Interleaving String Medium
class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
// use dp, dp[i][j] means whether s3[0:i+j-1] is an interleaving of s1[0:i-1] and s2[0:j-1]
int len1=s1.length();
int len2=s2.length();
int len3=s3.length();
if(len1+len2!=len3){
return false;
}
if(len1>len2){
return isInterleave(s2, s1, s3);
}
vector<bool> dp(len1+1, false);
// init
dp[0]=true;
for(int i=1; i<=len1; ++i){
dp[i]=(dp[i-1] && s1[i-1]==s3[i-1]);
}
for(int j=1; j<=len2; ++j){
dp[0]=(dp[0] && s2[j-1]==s3[j-1]);
for(int i=1; i<=len1; ++i){
dp[i]=(dp[i-1] && s1[i-1]==s3[i+j-1])||(dp[i] && s2[j-1]==s3[i+j-1]);
}
}
return dp[len1];
}
};
// Time Complexity: O(M*N)
// Space Complexity: O(min(M, N)) ○ 115. Distinct Subsequences Hard
class Solution {
public:
int numDistinct(string s, string t) {
int len1=s.length();
int len2=t.length();
if(len1<len2){
return 0;
}
vector<int> dp(len1, 0); // dp[i] means the num of subsequence ending with s[i]
vector<long long> prefixSum(len1, 0); // prefixSum means the accumulated num ending with s[i]
// init
if(s[0]==t[0]){
prefixSum[0]=1;
}
for(int i=1; i<len1; ++i){
if(s[i]==t[0]){
prefixSum[i]+=1;
}
prefixSum[i]+=prefixSum[i-1];
}
for(int j=1; j<len2; ++j){
for(int i=j; i<len1; ++i){
if(s[i]==t[j]){
dp[i]=prefixSum[i-1];
}
else{
dp[i]=0;
}
}
prefixSum[j-1]=0;
for(int i=j; i<len1; ++i){
prefixSum[i]=dp[i]+prefixSum[i-1];
}
}
return prefixSum[len1-1];
}
};
// Time Complexity: O(M*N)
// Space Complexity: O(M), M is the length of s. ○ 188. Best Time to Buy and Sell Stock IV Hard
class Solution {
public:
/*
int maxProfit(int k, vector<int>& prices) {
int n=prices.size();
vector<vector<vector<int>>> dp(2, vector<vector<int>>(k+1, vector<int>(2, -1e5)));
dp[0][0][1]=-prices[0];
for(int i=1; i<n; i++){
dp[1][0][1]=max(dp[0][0][1], -prices[i]);
for(int j=1; j<k; j++){
dp[1][j][0]=max(dp[0][j][0], dp[0][j-1][1]+prices[i]);
dp[1][j][1]=max(dp[0][j][1], dp[0][j][0]-prices[i]);
}
dp[1][k][0]=max(dp[0][k][0], dp[0][k-1][1]+prices[i]);
dp[0][0][1]=dp[1][0][1];
for(int j=1; j<k; j++){
dp[0][j][0]=dp[1][j][0];
dp[0][j][1]=dp[1][j][1];
}
dp[0][k][0]=dp[1][k][0];
}
int result=0;
for(int i=1; i<=k; i++)
result=max(result, dp[1][i][0]);
return result;
}
*/
int maxProfit(int k, vector<int>& prices) {
int n=prices.size();
vector<int> buy(k+1, -1e5); // ending with buy j times
vector<int> sell(k+1, 0); // ending with buy and sell j times
for(int price: prices){
for(int j=1; j<=k; j++){
buy[j]=max(buy[j], sell[j-1]-price);
sell[j]=max(sell[j], buy[j]+price);
}
}
return sell[k];
}
};
// Time Complexity: O(n)
// Space Complexity: O(1) ○ 221. Maximal Square Medium
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
int m=matrix.size();
int n=matrix[0].size();
int maxEdge=0;
vector<vector<int>> dp(m+1, vector<int>(n+1, 0));
for(int i=1; i<m+1; ++i){
for(int j=1; j<n+1; ++j){
if(matrix[i-1][j-1]=='1'){
dp[i][j]=min({dp[i-1][j-1], dp[i-1][j], dp[i][j-1]})+1;
maxEdge=max(maxEdge, dp[i][j]);
}
}
}
return maxEdge*maxEdge;
}
};
// Time Complexity: O(M*N), where M is the number of rows and N is the number of columns in the matrix.
// Space Complexity: O(M*N) for the dp array.
// The space can be optimized to O(N) by using only two rows, but here we use O(M*N) for clarity.
// The result is the area of the largest square found, which is maxEdge squared. ○ 309. Best Time to Buy and Sell Stock with Cooldown Medium
class Solution {
public:
/*
int maxProfit(vector<int>& prices) {
int numOfDays=prices.size();
if(numOfDays<2)
return 0;
vector<vector<int>> dp(numOfDays, vector<int>(2, 0)); // max profit (end with hold, end with notHold)
// initialization
dp[0][0]=-prices[0];
dp[0][1]=0;
dp[1][0]=max(-prices[0], -prices[1]);
dp[1][1]=max(0, dp[0][0]+prices[1]);
for(int i=2; i<numOfDays; i++){
dp[i][0]=max(dp[i-1][0], dp[i-2][1]-prices[i]);
dp[i][1]=max(dp[i-1][1], dp[i-1][0]+prices[i]);
}
return dp[numOfDays-1][1];
}
*/
// dp with O(1) space
int maxProfit(vector<int>& prices) {
int numOfDays=prices.size();
if(numOfDays<2)
return 0;
int prevHold, hold, prevNotHold, notHold;
prevHold=-prices[0];
hold=max(prevHold, -prices[1]);
prevNotHold=0;
notHold=max(prevNotHold, prevHold+prices[1]);
for(int i=2; i<numOfDays; i++){
prevHold=hold;
hold=max(hold, prevNotHold-prices[i]);
prevNotHold=notHold;
notHold=max(notHold, prevHold+prices[i]);
}
return notHold;
}
};
// Time Complexity: O(n)
// Space Complexity: O(1) ○ 312. Burst Balloons Hard
class Solution {
public:
int maxCoins(vector<int>& nums) {
int n = nums.size();
vector<int> vals(n + 2);
vals[0] = vals[n + 1] = 1;
for (int i = 0; i < n; ++i) vals[i + 1] = nums[i];
vector<vector<int>> dp(n + 2, vector<int>(n + 2, 0));
for (int len = 1; len <= n; ++len) {
for (int left = 1; left + len - 1 <= n; ++left) {
int right = left + len - 1;
for (int k = left; k <= right; ++k) {
int coins = vals[left - 1] * vals[k] * vals[right + 1];
coins += dp[left][k - 1] + dp[k + 1][right];
dp[left][right] = max(dp[left][right], coins);
}
}
}
return dp[1][n];
}
}; ○ 329. Longest Increasing Path in a Matrix Hard
class Solution {
public:
int longestIncreasingPath(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size();
vector<vector<int>> memo(m, vector<int>(n, 0));
int best = 0;
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
best = max(best, dfs(matrix, memo, i, j));
return best;
}
private:
int dfs(vector<vector<int>>& matrix, vector<vector<int>>& memo, int i, int j) {
if (memo[i][j] != 0) return memo[i][j];
int m = matrix.size(), n = matrix[0].size();
int dirs[5] = {0, 1, 0, -1, 0};
int best = 1;
for (int d = 0; d < 4; ++d) {
int ni = i + dirs[d], nj = j + dirs[d + 1];
if (ni >= 0 && ni < m && nj >= 0 && nj < n && matrix[ni][nj] > matrix[i][j]) {
best = max(best, 1 + dfs(matrix, memo, ni, nj));
}
}
memo[i][j] = best;
return best;
}
}; ○ 494. Target Sum Medium
class Solution {
public:
int findTargetSumWays(vector<int>& nums, int target) {
int total = 0;
for (int x : nums) total += x;
long shifted = (long)total + target;
if (shifted < 0 || shifted % 2 != 0) return 0;
int need = (int)(shifted / 2);
vector<int> dp(need + 1, 0);
dp[0] = 1;
for (int num : nums) {
for (int s = need; s >= num; --s) {
dp[s] += dp[s - num];
}
}
return dp[need];
}
}; ○ 518. Coin Change II Medium
#include <vector>
using namespace std;
class Solution {
public:
int change(int amount, vector<int>& coins) {
// use dynamic programmming to update the number of combinations
vector<int> dp(amount+1, 0);
// initialize
dp[0]=1;
for(int coin: coins){ // 1, 2, 5
for(int i=1; i<amount+1; i++){ // i: 1 to 5
if(i-coin>=0){
dp[i]+=dp[i-coin];
}
}
}
return dp[amount];
}
};
// Time Complexity: O(n*m) where n is the amount and m is the number of coins
// Space Complexity: O(n) ○ 1143. Longest Common Subsequence Medium
class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
int len1=text1.length();
int len2=text2.length();
vector<int> dp(len2+1, 0);
// update dp row by row
for(int i=1; i<=len1; ++i){
int prev_diag=0;
for(int j=1; j<=len2; ++j){
int tmp=dp[j];
if(text1[i-1]==text2[j-1]){ // text1 and text2 are 0-indexed
dp[j]=prev_diag+1;
}
else{
dp[j]=std::max(dp[j], dp[j-1]);
}
prev_diag=tmp;
}
}
return dp[len2];
}
};
// Time Complexity: O(M*N)
// Space Complexity: O(N) Greedy (10)
○ 45. Jump Game II Medium
class Solution {
public:
int jump(vector<int>& nums) {
// use greedy algorithm
// iterate from 0 to n-1, each time we keep "the max_pos we can jump to" and "the min number of jumps"
int max_pos=0;
int end=0;
int jumps=0;
int n=nums.size();
if(n==1)
return 0;
for(int i=0; i<n-1; ++i){
max_pos=std::max(max_pos, i+nums[i]);
if(i==end){
++jumps;
end=max_pos;
if(end>=n-1)
return jumps;
}
}
return jumps;
}
};
// Time Complexity: O(N)
// Space Complexity: O(1) ○ 53. Maximum Subarray Medium
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int curMax=nums[0];
int globalMax=nums[0];
for(int i=1; i<nums.size(); ++i){
// curMax is the max ending with i
curMax=std::max(curMax+nums[i], nums[i]);
globalMax=std::max(curMax, globalMax);
}
return globalMax;
}
};
// Time Complexity: O(N)
// Space Complexity: O(1) ○ 55. Jump Game Medium
class Solution {
public:
bool canJump(vector<int>& nums) {
int curFarthest=0;
int len=nums.size();
for(int i=0; i<len; ++i){
if(curFarthest>=len-1){
return true;
}
if(curFarthest<i){
return false;
}
curFarthest=std::max(curFarthest, i+nums[i]);
}
return false;
}
};
// Time Complexity: O(N)
// Space Complexity: O(1) ○ 122. Best Time to Buy and Sell Stock II Medium
class Solution {
public:
int maxProfit(vector<int>& prices) {
int profit=0;
int numOfDays=prices.size();
if(numOfDays<2)
return 0;
int i=0;
while(i<numOfDays){
bool isBuyPoint=false;
if(i==0)
isBuyPoint=prices[i]<prices[i+1];
else if(i==numOfDays-1)
isBuyPoint=false; // we don't buy at the last time
else
isBuyPoint = prices[i]<prices[i+1] && prices[i]<=prices[i-1];
if(isBuyPoint){
// find next local Max to sell
int j=i+1; // j is sellPoint
while(j<numOfDays-1){
if(prices[j]>prices[j+1])
break;
j++;
}
profit+=prices[j]-prices[i];
i=j+1;
}
else
i++;
}
return profit;
}
};
// Time Complexity: O(n)
// Space Complexity: O(1) ○ 134. Gas Station Medium
#include <vector>
#include <climits>
using namespace std;
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int len=gas.size();
gas[0]-=cost[0];
for(int i=1; i<len; ++i){
gas[i]-=cost[i];
gas[i]+=gas[i-1];
}
if(gas[len-1]<0){
return -1;
}
int minDiff=INT_MAX;
int minIdx=-1;
for(int i=0; i<len; ++i){
if(minDiff>gas[i]){
minDiff=gas[i];
minIdx=i;
}
}
return (minIdx+1)%len;
}
};
// Time Complexity: O(N)
// Space Complexity: O(1) ○ 678. Valid Parenthesis String Medium
#include <string>
using namespace std;
class Solution {
public:
bool checkValidString(string s) {
int lmin=0;
int lmax=0;
for(const char c: s){
if(c=='('){
++lmin;
++lmax;
}
else if(c==')'){
--lmin;
--lmax;
}
else{ // c=='*'
--lmin;
++lmax;
}
if(lmax<0){
return false;
}
if(lmin<0){
lmin=0;
}
}
return lmin==0;
}
};
// Time Complexity: O(n)
// Space Complexity: O(1) ○ 763. Partition Labels Medium
class Solution {
public:
vector<int> partitionLabels(string s) {
vector<int> last(26, 0);
for (int i = 0; i < (int)s.size(); ++i) last[s[i] - 'a'] = i;
vector<int> result;
int start = 0, end = 0;
for (int i = 0; i < (int)s.size(); ++i) {
end = max(end, last[s[i] - 'a']);
if (i == end) {
result.push_back(end - start + 1);
start = i + 1;
}
}
return result;
}
}; ○ 846. Hand of Straights Medium
class Solution {
public:
bool isNStraightHand(vector<int>& hand, int groupSize) {
if (hand.size() % groupSize != 0) return false;
map<int,int> count;
for (int c : hand) count[c]++;
while (!count.empty()) {
int start = count.begin()->first;
for (int v = start; v < start + groupSize; ++v) {
auto it = count.find(v);
if (it == count.end()) return false;
if (--(it->second) == 0) count.erase(it);
}
}
return true;
}
}; ○ 1353. Maximum Number of Events That Can Be Attended Medium
class Solution {
public:
int maxEvents(vector<vector<int>>& events) {
int len=events.size();
std::sort(events.begin(), events.end(), [](const auto& a, const auto& b){return a[0]<b[0];});
std::priority_queue<int, std::vector<int>, greater<int>> pq;
int idx=0; // event idx
int res=0;
// find max day
int maxDay=0;
for(int i=0; i<len; ++i){
maxDay=std::max(maxDay, events[i][1]);
}
for(int i=1; i<=maxDay; ++i){
while(idx<len && events[idx][0]==i){
pq.push(events[idx][1]);
++idx;
}
if(!pq.empty()){
pq.pop();
++res;
}
while(!pq.empty() && pq.top()<=i){
pq.pop();
}
}
return res;
}
};
// [2,5],[2,3],[3,4]
// idx: 0~2
// maxDay
// for 0~maxDay
// add events start with the current day to the min_heap (store end day)
// check expire from the top
○ 1899. Merge Triplets to Form Target Triplet Medium
class Solution {
public:
bool mergeTriplets(vector<vector<int>>& triplets, vector<int>& target) {
bool m0 = false, m1 = false, m2 = false;
for (auto& t : triplets) {
if (t[0] > target[0] || t[1] > target[1] || t[2] > target[2]) continue;
if (t[0] == target[0]) m0 = true;
if (t[1] == target[1]) m1 = true;
if (t[2] == target[2]) m2 = true;
}
return m0 && m1 && m2;
}
}; Intervals (7)
○ 56. Merge Intervals Medium
class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end());
vector<vector<int>> result;
for (auto& iv : intervals) {
if (!result.empty() && iv[0] <= result.back()[1]) {
result.back()[1] = max(result.back()[1], iv[1]);
} else {
result.push_back(iv);
}
}
return result;
}
}; ○ 57. Insert Interval Medium
class Solution {
public:
vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
vector<vector<int>> res;
int n=intervals.size();
int i=0;
while(i<n && intervals[i][1]<newInterval[0]){
res.push_back(intervals[i]);
++i;
}
while(i<n && intervals[i][0]<=newInterval[1]){
newInterval[0]=std::min(newInterval[0], intervals[i][0]);
newInterval[1]=std::max(newInterval[1], intervals[i][1]);
++i;
}
res.push_back(newInterval);
while(i<n){
res.push_back(intervals[i]);
++i;
}
return res;
}
};
// Time Complexity: O(n)
// Space Complexity: O(n) ○ 252. Meeting Rooms Easy
#include <vector>
using namespace std;
class Solution {
public:
bool canAttendMeetings(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end());
for(int i=1; i<intervals.size(); ++i){
if(intervals[i][0]<intervals[i-1][1]){
return false;
}
}
return true;
}
};
// Time: O(nlogn)
// Space: O(1) ○ 253. Meeting Rooms II Medium
#include <vector>
#include <queue>
using namespace std;
class Solution {
public:
int minMeetingRooms(vector<vector<int>>& intervals) {
int count=0;
int n=intervals.size();
std::priority_queue<int, vector<int>, greater<int>> pq;
pq.push(0);
sort(intervals.begin(), intervals.end());
for(const auto& i: intervals){
int curMin=pq.top();
if(curMin<=i[0]){
pq.pop();
pq.push(i[1]);
}
else{
pq.push(i[1]);
}
}
return pq.size();
}
};
// Time: O(nlogn)
// Space: O(n) in the worst case when all meetings overlap, otherwise O(k) where k is the maximum number of overlapping meetings. ○ 435. Non-overlapping Intervals Medium
class Solution {
public:
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end(), [](const vector<int>& a, const vector<int>& b) {
return a[1] < b[1];
});
int removed = 0;
long prevEnd = LONG_MIN;
for (auto& iv : intervals) {
if (iv[0] >= prevEnd) {
prevEnd = iv[1];
} else {
++removed;
}
}
return removed;
}
}; ○ 986. Interval List Intersections Medium
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> intervalIntersection(vector<vector<int>>& firstList, vector<vector<int>>& secondList) {
int i=0, j=0;
vector<vector<int>> res;
while(i<firstList.size()&&j<secondList.size()){
// check overlap
int maxLeft=std::max(firstList[i][0], secondList[j][0]);
int minRight=std::min(firstList[i][1], secondList[j][1]);
if(maxLeft<=minRight){
res.push_back({maxLeft, minRight});
}
if(firstList[i][1]<secondList[j][1]){
++i;
}
else{
++j;
}
}
return res;
}
};
// [[0,2],[5,10],[13,23],[24,25]] i=3
// [[1,5],[8,12],[15,24],[25,26]] j=3
// [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]
// Time Complexity: O(M+N), where M and N are the lengths of firstList and secondList, respectively.
// Space Complexity: O(M+N) for the result vector in the worst case when all intervals overlap. ○ 1851. Minimum Interval to Include Each Query Hard
class Solution {
public:
vector<int> minInterval(vector<vector<int>>& intervals, vector<int>& queries) {
sort(intervals.begin(), intervals.end());
int q = queries.size();
vector<int> order(q);
for (int i = 0; i < q; ++i) order[i] = i;
sort(order.begin(), order.end(), [&](int a, int b) {
return queries[a] < queries[b];
});
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> heap;
vector<int> answer(q, -1);
int idx = 0, n = intervals.size();
for (int qi : order) {
int value = queries[qi];
while (idx < n && intervals[idx][0] <= value) {
int size = intervals[idx][1] - intervals[idx][0] + 1;
heap.push({size, intervals[idx][1]});
++idx;
}
while (!heap.empty() && heap.top().second < value) heap.pop();
if (!heap.empty()) answer[qi] = heap.top().first;
}
return answer;
}
}; Math & Geometry (12)
○ 43. Multiply Strings Medium
class Solution {
public:
string multiply(string num1, string num2) {
if(num1=="0" || num2=="0")
return "0";
int n1=num1.size();
int n2=num2.size();
vector<int> res(n1+n2, 0);
for(int i=n1-1; i>=0; i--){
for(int j=n2-1; j>=0; j--){
res[i+j+1]+=(num1[i]-'0')*(num2[j]-'0');
if(res[i+j+1]>=10){
res[i+j]+=(res[i+j+1]/10);
res[i+j+1]%=10;
}
}
}
int start=0;
while(start<res.size() && res[start]==0)
++start;
string str;
for(int i=start; i<n1+n2; i++)
str.push_back(res[i]+'0');
return str;
}
};
// Time Complexity: O(M*N)
// Space Complexity: O(M+N) ○ 48. Rotate Image Medium
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int n=matrix.size();
for(int i=0; i<n; ++i){
for(int j=i; j<n; ++j){
std::swap(matrix[i][j], matrix[j][i]);
}
}
for(int i=0; i<n; ++i){
std::reverse(matrix[i].begin(), matrix[i].end());
}
}
};
// Time Complexity: O(N^2)
// Space Complexity: O(1) ○ 50. Pow(x, n) Medium
class Solution {
public:
double myPow(double x, int n) {
if(x==1 || n==0)
return 1.0;
if(x==-1)
return (n%2)?-1.0:1.0;
double res=1;
long N=n;
if(N<0){
x=1.0/x;
N=-N;
}
// 2^10 = 4^5 = 4^4 * 4 = 16^2 * 4 = 256*4
while(N>1){
if(N&1){
res*=x;
}
x*=x;
N>>=1;
}
res*=x;
return res;
}
};
// Time Complexity: O(log n)
// Space Complexity: O(1) ○ 54. Spiral Matrix Medium
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
int m=matrix.size(); // 3
int n=matrix[0].size(); // 4
// loop 0: (0, 0) -> (0, n-1) -> (m-1, n-1) -> (m-1, 0) -> (1, 0)
// loop 1: (1, 1) -> (1, n-2) -> (m-2, n-2) -> (m-2, 1) -> (2, 1)
// loop 2: (2, 2) -> ...
int totLoop=std::min(m, n)/2;
int curLoop=0;
while(curLoop<totLoop){
// first row
for(int j=curLoop; j<=n-1-curLoop; ++j){
res.push_back(matrix[curLoop][j]);
}
// last col
for(int i=curLoop+1; i<=m-1-curLoop; ++i){
res.push_back(matrix[i][n-1-curLoop]);
}
// last row
for(int j=n-2-curLoop; j>=curLoop; --j){
res.push_back(matrix[m-1-curLoop][j]);
}
// first col
for(int i=m-2-curLoop; i>curLoop; --i){
res.push_back(matrix[i][curLoop]);
}
++curLoop;
}
if(std::min(m, n)%2==1){
if(m<=n){
for(int j=curLoop; j<=n-1-curLoop; ++j){
res.push_back(matrix[curLoop][j]);
}
}
else{
for(int i=curLoop; i<=m-1-curLoop; ++i){
res.push_back(matrix[i][curLoop]);
}
}
}
return res;
}
};
// Time Complexity: O(M*N)
// Space Complexity: O(1) ○ 66. Plus One Easy
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
for(int i=digits.size()-1; i>=0; --i){
++digits[i];
if(digits[i]<10){
return digits;
}
digits[i]=0;
}
digits.insert(digits.begin(), 1);
return digits;
}
};
// Time Complexity: O(N)
// Space Complexity: O(1) ○ 73. Set Matrix Zeroes Medium
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int m=matrix.size();
int n=matrix[0].size();
vector<bool> row(m, false);
vector<bool> col(n, false);
for(int i=0; i<m; ++i){ // O(mn)
for(int j=0; j<n; ++j){
if(matrix[i][j]==0){
row[i]=true;
col[j]=true;
}
}
}
for(int i=0; i<m; ++i){ // O(mn)
if(row[i]){
for(int j=0; j<n; ++j){
matrix[i][j]=0;
}
}
}
for(int j=0; j<n; ++j){ // O(mn)
if(col[j]){
for(int i=0; i<m; ++i){
matrix[i][j]=0;
}
}
}
}
};
// Time Complexity: O(mn)
// Space Complexity: O(m+n), can be optimized to O(1) by using the first row and first column to store the information. ○ 202. Happy Number Easy
class Solution {
public:
bool isHappy(int n) {
// loop this:
// 1. extract each digits
// 2. get the sum
// 3. check if the sum==1
// 2^31 -> 1000^3 -> 1e9 (approx)
// use 10 digit to be upper bound
// max: 9^2 * 10 = 810 -> max loop number
// the other methods are to use hash set or two pointer
for(int i=0; i<810; ++i){
int sum=0;
while(n!=0){
int digit=n%10;
n/=10;
sum+=(digit*digit);
}
if(sum==1){
return true;
}
n=sum;
}
return false;
}
};
// Time: O(1)
// Space: O(1) ○ 311. Sparse Matrix Multiplication Medium
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> multiply(vector<vector<int>>& mat1, vector<vector<int>>& mat2) {
int m=mat1.size();
int k=mat1[0].size();
int n=mat2[0].size();
vector<vector<int>> res(m, vector<int>(n, 0));
for(int i=0; i<m; ++i){
for(int j=0; j<k; ++j){
if(mat1[i][j]==0){
continue;
}
for(int l=0; l<n; ++l){
if(mat2[j][l]==0){
continue;
}
res[i][l]+=mat1[i][j]*mat2[j][l];
}
}
}
return res;
}
};
// m*k, k*n
// for each element, we do k multiplication
// m*n elements, so m*n*k multiplication
// Time Complexity: O(m*n*k), where m, n, and k are the dimensions of the input matrices.
// Space Complexity: O(m*n) for the result matrix. ○ 384. Shuffle an Array Medium
class Solution {
private:
mt19937 gen{random_device{}()};
vector<int> original;
int n;
public:
Solution(vector<int>& nums): original(nums), n(nums.size()) {}
vector<int> reset() {
return original;
}
vector<int> shuffle() {
vector<int> res=original;
for(int i=0; i<n; ++i){
uniform_int_distribution<int> dist(i, n-1);
swap(res[i], res[dist(gen)]);
}
return res;
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(nums);
* vector<int> param_1 = obj->reset();
* vector<int> param_2 = obj->shuffle();
*/ ○ 1114. Print in Order Easy
#include <functional>
#include <mutex>
#include <condition_variable>
using namespace std;
class Foo {
private:
int count=1;
std::mutex mtx;
std::condition_variable cv;
public:
Foo() {
}
void first(function<void()> printFirst) {
std::unique_lock<std::mutex> lock(mtx);
// printFirst() outputs "first". Do not change or remove this line.
printFirst();
count=2;
cv.notify_all();
}
void second(function<void()> printSecond) {
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, [this]{return count==2;});
// printSecond() outputs "second". Do not change or remove this line.
printSecond();
count=3;
cv.notify_all();
}
void third(function<void()> printThird) {
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, [this]{return count==3;});
// printThird() outputs "third". Do not change or remove this line.
printThird();
}
}; ○ 1226. The Dining Philosophers Medium
#include <mutex>
#include <semaphore>
#include <functional>
class DiningPhilosophers {
private:
std::mutex forks[5];
std::counting_semaphore<4> limit{4};
public:
DiningPhilosophers() {
}
void wantsToEat(int philosopher,
function<void()> pickLeftFork,
function<void()> pickRightFork,
function<void()> eat,
function<void()> putLeftFork,
function<void()> putRightFork) {
int left=philosopher;
int right=(philosopher+1)%5;
limit.acquire();
forks[left].lock();
forks[right].lock();
pickLeftFork();
pickRightFork();
eat();
putLeftFork();
putRightFork();
forks[left].unlock();
forks[right].unlock();
limit.release();
}
}; ○ 2013. Detect Squares Medium
class DetectSquares {
public:
vector<vector<int>> cnts;
unordered_map<int, vector<int>> x_to_y;
DetectSquares():cnts(1001, vector<int>(1001, 0)) {}
void add(vector<int> point) {
if(cnts[point[0]][point[1]]++ ==0){
x_to_y[point[0]].push_back(point[1]);
}
}
int count(vector<int> point) {
int x=point[0];
int y=point[1];
int res=0;
auto it=x_to_y.find(x);
if(it==x_to_y.end()){
return 0;
}
for(const int& y2: it->second){
if(y2==y){
continue;
}
int d=std::abs(y2-y);
if(x-d>=0){
res+=cnts[x][y2]*cnts[x-d][y]*cnts[x-d][y2];
}
if(x+d<=1000){
res+=cnts[x][y2]*cnts[x+d][y]*cnts[x+d][y2];
}
}
return res;
}
};
// Time Complexity: O(1) for add, O(N) for count
// Space Complexity: O(N) for cnts, O(N) for x_to_y Bit Manipulation (10)
○ 7. Reverse Integer Medium
#include <climits>
class Solution {
public:
int reverse(int x) {
int result=0;
while(x!=0){
int digit=x%10;
if(result>INT_MAX/10 || (result==INT_MAX/10 && digit>7))
return 0;
if(result<INT_MIN/10 || (result==INT_MIN/10 && digit<-8))
return 0;
result=result*10+digit;
x/=10;
}
return result;
}
};
// Time Complexity: O(log(x)) where x is the input integer
// Space Complexity: O(1) ○ 29. Divide Two Integers Medium
class Solution {
public:
int divide(int dividend, int divisor) {
if(dividend==INT_MIN && divisor==-1){
return INT_MAX;
}
bool isNegative=(dividend>0)^(divisor>0);
long long a=abs((long long)dividend);
long long b=abs((long long)divisor);
long long quotient=0;
while(a>=b){
long long tmp=b;
int shift=0;
while((tmp<<1)<a){
tmp<<=1;
++shift;
}
a-=tmp;
quotient+=(1<<shift);
}
return isNegative? -quotient: quotient;
}
};
// Time Complexity: O(log(dividend/divisor))
// Space Complexity: O(1) ○ 136. Single Number Easy
class Solution {
public:
int singleNumber(vector<int>& nums) {
// A^A=0
int ans=0;
for(const int& n: nums){
ans^=n;
}
return ans;
}
};
// Time Complexity: O(N)
// Space Complexity: O(1) ○ 190. Reverse Bits Easy
class Solution {
public:
int reverseBits(int n) {
int res=0;
for(int i=0; i<32; ++i){
if(n==0){
break;
}
if(n&1){
res+=(1<<(31-i));
}
n>>=1;
}
return res;
}
};
// Time Complexity: O(1)
// Space Complexity: O(1) ○ 191. Number of 1 Bits Easy
class Solution {
public:
int hammingWeight(int n) {
int count=0;
while(n>0){
if(n&1>0){
++count;
}
n>>=1;
}
return count;
}
};
// Time Complexity: O(1), since the number of 1 bits is at most 32.
// Space Complexity: O(1) ○ 201. Bitwise AND of Numbers Range Medium
class Solution {
public:
int rangeBitwiseAnd(int left, int right) {
// 101 (left)
// 111 (right)
// 100 (find the common prefix)
unsigned short shift=0;
while(left<right){
left>>=1;
right>>=1;
++shift;
}
return left<<shift;
}
}; ○ 231. Power of Two Easy
class Solution {
public:
bool isPowerOfTwo(int n) {
// if n is 2^k, then only 1 bit is 1
return n>0 && (n&(n-1))==0;
}
};
// Time Complexity: O(1)
// Space Complexity: O(1) ○ 268. Missing Number Easy
class Solution {
public:
int missingNumber(vector<int>& nums) {
int result = nums.size();
for (int i = 0; i < (int)nums.size(); ++i) {
result ^= i ^ nums[i];
}
return result;
}
}; ○ 338. Counting Bits Easy
class Solution {
public:
vector<int> countBits(int n) {
vector<int> ans(n+1);
// use bottom-up dynamic programming
ans[0]=0;
for(int i=1; i<=n; ++i){
ans[i]=ans[i>>1]+(i&1);
}
return ans;
}
};
// Time Complexity: O(N)
// Space Complexity: O(N) ○ 371. Sum of Two Integers Medium
class Solution {
public:
int getSum(int a, int b) {
while (b != 0) {
unsigned int carry = (unsigned int)(a & b) << 1;
a = a ^ b;
b = (int)carry;
}
return a;
}
}; 📚 Notes
🧩 System Design (2)
○ A framework for the interview Beginner
A repeatable, time-boxed structure for a 45-minute system-design round.
○ Building blocks Beginner
The reusable components that show up in almost every design, and when to reach for each.
💬 Behavioral (2)
○ The STAR method Beginner
Structure any behavioral answer as Situation, Task, Action, Result — with the emphasis in the right place.
○ Common questions Beginner
The recurring behavioral prompts, what each is really probing, and how to prep a story for it.
📚 Learning (14)
○ What is Durable Execution? Beginner
The core idea behind Temporal — code that you can crash and resume without losing state.
○ Workflows & Activities Beginner
The two core building blocks — the deterministic orchestrator and the side-effecting units it calls.
○ Workers & Task Queues Intermediate
Where your code actually executes, and how the Temporal service hands work to it.
○ Retries & Timeouts Intermediate
How Temporal makes flaky work reliable — retry policies, the four activity timeouts, and idempotency.
○ Why OTA Updates Are Hard (and A/B Updates) Beginner
The failure modes of updating remote embedded devices, and how dual-rootfs updates make them atomic.
○ Mender Artifacts Beginner
The .mender update package — what's inside, device-type compatibility, and full-image vs application updates.
○ Deployments & Device Groups Intermediate
Rolling an Artifact out to a fleet — grouping, phased rollouts, monitoring, and rollback in practice.
○ State Scripts & Delta Updates Advanced
Hooking custom logic into the update lifecycle, and shipping only what changed.
○ Cloud Run — Serverless Containers Beginner
Deploy a container and get a scaling HTTPS endpoint, scale-to-zero, and pay-per-use.
○ GKE — Managed Kubernetes Intermediate
When to choose Kubernetes over Cloud Run, and Autopilot vs Standard clusters.
○ Pub/Sub — Asynchronous Messaging Beginner
Decouple producers from consumers with topics, subscriptions, delivery guarantees, and dead-letter queues.
○ Cloud Storage — Object Storage Beginner
Buckets, objects, storage classes, signed URLs, and lifecycle rules.
○ IAM — Who Can Do What Intermediate
Principals, roles, and bindings on the resource hierarchy — plus service accounts and least privilege.
○ BigQuery — Serverless Data Warehouse Beginner
Petabyte-scale SQL with no servers — datasets, tables, pricing models, and partitioning.