├── 01-matrix ├── 01-matrix.cpp └── README.md ├── 2037. Minimum Number of Moves to Seat Everyone ├── 2038. Remove Colored Pieces if Both Neighbors are the Same Color ├── 2042. Check if Numbers Are Ascending in a Sentence ├── 2043. Simple Bank System ├── 2044. Count Number of Maximum Bitwise-OR Subsets ├── 3sum-closest ├── 3sum-closest.cpp └── README.md ├── 3sum ├── 3sum.cpp └── README.md ├── CONTRIBUTING.md ├── Design-twitter └── Design-Twitter.cpp ├── Find First and Last Position of Element in Sorted Array ├── Find First and Last Position of Element in Sorted Array.cpp ├── FirstAndLastPosition.cpp └── Readme.md ├── Min-Cost └── MinCost.cpp ├── README.md ├── Search in Rotated Sorted Array.cpp ├── WildcardMatching.cpp ├── add-MatrixZero └── addMatrixzero.cpp ├── add-strings ├── README.md └── add-strings.cpp ├── allocate-mailboxes ├── README.md └── allocate-mailboxes.cpp ├── arithmetic-slices-ii-subsequence ├── README.md └── arithmetic-slices-ii-subsequence.cpp ├── arithmetic-slices ├── README.md └── arithmetic-slices.cpp ├── array-nesting ├── README.md └── array-nesting.cpp ├── backspace-string-compare ├── README.md └── backspace-string-compare.cpp ├── beautiful-arrangement └── Beautiful Arrangement.cpp ├── beautiful-array ├── README.md └── beautiful-array.cpp ├── best-sightseeing-pair ├── README.md └── best-sightseeing-pair.cpp ├── best-time-to-buy-and-sell-stock-ii ├── README.md └── best-time-to-buy-and-sell-stock-ii.cpp ├── best-time-to-buy-and-sell-stock-with-cooldown ├── README.md └── best-time-to-buy-and-sell-stock-with-cooldown.cpp ├── best-time-to-buy-and-sell-stock-with-transaction-fee ├── README.md └── best-time-to-buy-and-sell-stock-with-transaction-fee.cpp ├── best-time-to-buy-and-sell-stock ├── README.md └── best-time-to-buy-and-sell-stock.cpp ├── binary-search ├── README.md └── binary-search.cpp ├── binary-tree-inorder-traversal ├── README.md └── binary-tree-inorder-traversal.cpp ├── binary-tree-level-order-traversal ├── README.md └── binary-tree-level-order-traversal.cpp ├── binary-tree-maximum-path-sum ├── README.md └── binary-tree-maximum-path-sum.cpp ├── binary-tree-postorder-traversal └── postorder.cpp ├── binary-tree-preorder-traversal ├── README.md └── binary-tree-preorder-traversal.cpp ├── binary-tree-pruning ├── README.md └── binary-tree-pruning.cpp ├── binary-tree-right-side-view ├── README.md └── binary-tree-right-side-view.cpp ├── breadth-first-search └── breadth-first-search.cpp ├── burst-ballons └── burst-balloons.cpp ├── cheapest-flights-within-K-stops └── Cheapest Flights Within K Stops.cpp ├── cherry-pickup-ii ├── README.md └── cherry-pickup-ii.cpp ├── cherry-pickup ├── README.md └── cherry-pickup.cpp ├── climbing-stairs ├── README.md └── climbing-stairs.cpp ├── coin-change-2 ├── README.md └── coin_change2.cpp ├── coin-change ├── README.md └── coin-change.cpp ├── combination-sum-iv ├── README.md └── combination-sum-iv.cpp ├── combination-sum ├── README.md └── combination-sum.cpp ├── combinations ├── README.md └── combinations.cpp ├── complex-number-multiplication ├── README.md └── complex-number-multiplication.cpp ├── construct-binary-tree-from-preorder-and-inorder-traversal ├── README.md └── construct-binary-tree-from-preorder-and-inorder-traversal.cpp ├── container-with-most-water ├── README.md └── container-with-most-water.cpp ├── convert-sorted-array-to-binary-search-tree ├── README.md └── convert-sorted-array-to-binary-search-tree.cpp ├── copy-list-with-random-pointer ├── README.md └── copy-list-with-random-pointer.cpp ├── count-good-nodes-in-binary-tree ├── README.md └── count-good-nodes-in-binary-tree.cpp ├── countAndSay.cpp ├── counting-bits ├── README.md └── counting-bits.cpp ├── course-schedule ├── README.md └── course-schedule.cpp ├── daily-temperatures ├── README.md └── daily-temperatures.cpp ├── decode-string ├── README.md └── decode-string.cpp ├── decode-ways ├── README.md ├── decode-ways.cpp └── decodeWays.cpp ├── delete-and-earn ├── README.md └── delete-and-earn.cpp ├── diameter-of-binary-tree ├── README.md └── diameter-of-binary-tree.cpp ├── dungeon-game ├── README.md └── dungeon-game.cpp ├── edit-distance ├── README.md └── edit-distance.cpp ├── fibonacci-number ├── README.md └── fibonacci-number.cpp ├── find-all-anagrams-in-a-string ├── README.md └── find-all-anagrams-in-a-string.cpp ├── find-all-duplicates-in-an-array ├── README.md └── find-all-duplicates-in-an-array.cpp ├── find-all-numbers-disappeared-in-an-array ├── README.md └── find-all-numbers-disappeared-in-an-array.cpp ├── find-first-and-last-position-of-element-in-sorted-array ├── README.md └── solution.cpp ├── find-minimum-in-rotated-sorted-array ├── README.md └── find-minimum-in-rotated-sorted-array.cpp ├── find-peak-element ├── README.md └── find-peak-element.cpp ├── findMedianSortedArrays.cpp ├── first-bad-version ├── README.md └── first-bad-version.cpp ├── first-missing-positive ├── README.md └── first-missing-positive.cpp ├── flatten-binary-tree-to-linked-list ├── README.md └── flatten-binary-tree-to-linked-list.cpp ├── flip-binary-tree └── flipbinarytree.cpp ├── flood-fill ├── README.md └── flood-fill.cpp ├── gas-station ├── README.md └── gas-station.cpp ├── generate-parentheses ├── README.md └── generate-parentheses.cpp ├── group-anagrams ├── README.md └── group-anagrams.cpp ├── heaters ├── README.md └── heaters.cpp ├── house-robber-ii ├── README.md └── house-robber-ii.cpp ├── house-robber-iii ├── README.md └── house-robber-iii.cpp ├── house-robber ├── House Robber.cpp ├── README.md └── house-robber.cpp ├── insert-delete-getrandom-o1 ├── README.md └── insert-delete-getrandom-o1.cpp ├── insert-interval ├── README.md └── insert-interval.cpp ├── integer-break ├── README.md └── integer-break.cpp ├── interval-list-intersections ├── Interval-list-intersection.cpp └── README.md ├── invert-binary-tree ├── README.md └── invert-binary-tree.cpp ├── is-graph-bipartite ├── README.md └── is-graph-bipartite.cpp ├── is-subsequence ├── README.md └── is_subsequence.cpp ├── island-perimeter ├── README.md └── island-perimeter.cpp ├── jump-game-ii ├── README.md └── jump-game-ii.cpp ├── jump-game ├── README.md └── jump-game.cpp ├── koko-eating-bananas ├── readme.md └── solution.cpp ├── kth-smallest-element-in-a-bst ├── README.md └── kth-smallest-element-in-a-bst.cpp ├── largest-rectangle-in-histogram ├── README.md └── largest-rectangle-in-histogram.cpp ├── letter-case-permutation ├── README.md └── letter-case-permutation.cpp ├── linked-list-cycle ├── README.md └── linked-list-cycle.cpp ├── longest-common-subsequence ├── README.md └── longest-common-subsequence.cpp ├── longest-increasing-path-in-a-matrix └── Longest-Increasing-Path-in a-Matrix.cpp ├── longest-increasing-subsequence ├── README.md └── lis.cpp ├── longest-palindromic-subsequence ├── README.md └── longest-palindromic-subsequence.cpp ├── longest-palindromic-substring ├── README.md └── longest-palindromic-substring.cpp ├── longest-substring-without-repeating-characters ├── README.md └── solution.cpp ├── lru-cache ├── README.md └── lru-cache.cpp ├── majority-element ├── README.md ├── majority-element.cpp └── majority_element_another_approach.cpp ├── making-a-large-island ├── README.md └── making-a-large-island.cpp ├── map-sum-pairs ├── README.md └── map-sum-pairs.cpp ├── matrix-block-sum ├── README.md └── matrix-block-sum.cpp ├── max-area-of-island ├── README.md └── max-area-of-island.cpp ├── max-subarray-sum └── kadane-algorithm.cpp ├── maximal-square ├── README.md └── maximal-square.cpp ├── maximum-length-of-subarray-with-positive-product ├── README.md └── maximum-length-of-subarray-with-positive-product.cpp ├── maximum-product-of-splitted-binary-tree ├── README.md └── maximum-product-of-splitted-binary-tree.cpp ├── maximum-product-subarray ├── README.md └── maximum-product-subarray.cpp ├── maximum-profit-in-job-scheduling ├── README.md └── maximum-profit-in-job-scheduling.cpp ├── maximum-subarray ├── README.md └── solution.cpp ├── maximum-sum-circular-subarray ├── README.md └── maximum-sum-circular-subarray.cpp ├── merge-k-sorted-lists ├── README.md └── merge-k-sorted-lists.cpp ├── merge-two-binary-trees ├── README.md └── merge-two-binary-trees.cpp ├── merge-two-sorted-lists ├── README.md └── merge-two-sorted-lists.cpp ├── middle-of-the-linked-list ├── README.md └── middle-of-the-linked-list.cpp ├── min-cost-climbing-stairs ├── README.md └── solution.cpp ├── min-stack ├── README.md └── min-stack.cpp ├── minimum-falling-path-sum ├── README.md └── minimum-falling-path-sum.cpp ├── minimum-path-sum ├── README.md └── minimum-path-sum.cpp ├── minimum-window-substring ├── README.md └── minimum-window-substring.cpp ├── move-zeroes ├── README.md └── move-zeroes.cpp ├── n-ary-tree-level-order-traversal ├── README.md └── n-ary-tree-level-order-traversal.cpp ├── n-th-tribonacci-number ├── README.md └── n-th-tribonacci-number.cpp ├── next-permutation ├── README.md └── next-permutation.cpp ├── non-negative-integers-without-consecutive-ones ├── README.md └── non-negative-integers-without-consecutive-ones.cpp ├── number-of-1-bits ├── README.md └── number-of-1-bits.cpp ├── number-of-islands ├── README.md └── number-of-islands.cpp ├── number-of-provinces ├── README.md └── number-of-provinces.cpp ├── palindrome-linked-list ├── README.md └── pallindrome-linked list.cpp ├── palindromic-substrings ├── README.md └── palindromic-substrings.cpp ├── partition-labels ├── README.md └── partition-labels.cpp ├── pascals-triangle-ii ├── README.md └── pascals triangle2.cpp ├── pascals-triangle ├── README.md └── pascals-triangle.cpp ├── patching-array ├── README.md └── patching-array.cpp ├── path-sum-ii ├── README.md └── path-sum-ii.cpp ├── perfect-squares ├── README.md └── perfect-squares.cpp ├── permutation-in-string ├── README.md └── permutation-in-string.cpp ├── permutations ├── README.md └── permutations.cpp ├── populating-next-right-pointers-in-each-node ├── README.md └── populating-next-right-pointers-in-each-node.cpp ├── postorder.cpp ├── power-of-two ├── README.md └── power_of_two.cpp ├── product-of-array-except-self ├── README.md └── product-of-array-except-self.cpp ├── push-dominoes ├── README.md └── push-dominoes.cpp ├── range-sum-query-2d-immutable └── README.md ├── range-sum-query-immutable ├── README.md └── range-sum-query-immutable.cpp ├── regular-expression-matching ├── README.md └── regular-expression-matching.cpp ├── remove-boxes ├── README.md └── remove-boxes.cpp ├── remove-duplicates-from-sorted-list-ii ├── README.md └── remove-duplicates-from-sorted-list-ii.cpp ├── remove-nth-node-from-end-of-list ├── README.md └── remove-nth-node-from-end-of-list.cpp ├── reverse-bits ├── README.md └── reverse-bits.cpp ├── reverse-linked-list ├── README.md └── reverse-linked-list.cpp ├── reverse-nodes-in-k-group ├── README.md └── reverse-nodes-in-k-group.cpp ├── reverse-string ├── README.md └── reverse-string.cpp ├── reverse-words-in-a-string-iii ├── README.md └── solution.cpp ├── rotate-array ├── README.md └── rotate-array.cpp ├── rotate-image ├── README.md └── rotate-image.cpp ├── rotting-oranges ├── README.md └── rotting-oranges.cpp ├── search-a-2d-matrix ├── README.md └── search-a-2d-matrix.cpp ├── search-in-rotated-sorted-array ├── README.md └── search-in-rotated-sorted-array.cpp ├── search-insert-position ├── README.md └── search-insert-position.cpp ├── serialize-and-deserialize-binary-tree ├── README.md └── serialize-and-deserialize-binary-tree.cpp ├── single-number ├── README.md └── single-number.cpp ├── sliding-window-maximum ├── README.md └── sliding-window-maximum.cpp ├── sort-colors ├── README.md └── sort-colors.cpp ├── spiral-matrix ├── README.md └── spiral-matrix.cpp ├── squares-of-a-sorted-array ├── README.md └── squares-of-a-sorted-array.cpp ├── subsets-ii ├── README.md └── subsets-ii.cpp ├── subsets ├── README.md └── subsets.cpp ├── sudoku-solver ├── README.md └── sudoku-solver.cpp ├── surrounded-regions ├── README.md └── surrounded-regions.cpp ├── symmetric-tree ├── README.md └── symmetric-tree.cpp ├── task-scheduler ├── README.md └── task-scheduler.cpp ├── top-k-frequent-elements ├── README.md └── top-k-frequent-elements.cpp ├── trapping-rain-water ├── README.md └── trapping-rain-water.cpp ├── triangle ├── README.md └── triangle.cpp ├── two-sum-ii-input-array-is-sorted ├── README.md └── two-sum-ii-input-array-is-sorted.cpp ├── two-sum-iv-input-is-a-bst ├── README.md └── two-sum-iv-input-is-a-bst.cpp ├── two-sum ├── README.md └── two-sum.cpp ├── ugly-number-ii ├── README.md └── ugly-number-ii.cpp ├── unique-binary-search-trees ├── README.md └── unique-binary-search-trees.cpp ├── unique-paths-ii ├── README.md └── solution.cpp ├── unique-paths ├── README.md └── unique-paths.cpp ├── valid-parentheses ├── README.md └── valid-parentheses.cpp ├── valid-sudoku ├── README.md └── valid-sudoku.cpp ├── verify-preorder-serialization-of-a-binary-tree ├── README.md └── verify-preorder-serialization-of-a-binary-tree.cpp ├── water-and-jug-problem ├── README.md └── water-and-jug-problem.cpp ├── wiggle-subsequence ├── README.md └── wiggle-subsequence.cpp ├── wildcard-matching ├── README.md └── wildcard-matching.cpp ├── word-break ├── README.md └── word-break.cpp ├── word-ladder-ii ├── README.md └── word-ladder-ii.cpp ├── word-ladder ├── README.md └── word-ladder.cpp ├── word-search ├── README.md └── word-search.cpp └── zigzag-conversion └── ZigZag Conversion.cpp /2037. Minimum Number of Moves to Seat Everyone: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minMovesToSeat(vector& seats, vector& students) { 4 | sort(seats.begin(),seats.end()); 5 | sort(students.begin(),students.end()); 6 | int res = 0; 7 | for(int i = 0;icntb) return true; 18 | return false; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /2042. Check if Numbers Are Ascending in a Sentence: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isNumber(const string& str) 4 | { 5 | for (char const &c : str) { 6 | if (std::isdigit(c) == 0) return false; 7 | } 8 | return true; 9 | } 10 | int getnum(string &s){ 11 | return stoi(s); 12 | } 13 | bool areNumbersAscending(string s) { 14 | istringstream ss(s); 15 | string word; 16 | int prev = -100; 17 | while(ss>>word){ 18 | if(isNumber(word)){ 19 | int num = getnum(word); 20 | if(num<=prev) return false; 21 | prev = num; 22 | } 23 | } 24 | return true; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /2043. Simple Bank System: -------------------------------------------------------------------------------- 1 | class Bank { 2 | public: 3 | mapmp; 4 | int size; 5 | Bank(vector& balance) { 6 | int i = 1; 7 | for(auto x:balance) mp[i++] = x; 8 | size = i-1; 9 | } 10 | 11 | 12 | bool transfer(int account1, int account2, long long money) { 13 | if(account1>size || account2>size) return false; 14 | if(mp[account1]>=money){ 15 | mp[account2]+=money; 16 | mp[account1]-=money; 17 | return true; 18 | } 19 | return false; 20 | } 21 | 22 | bool deposit(int account, long long money) { 23 | if(account>size) return false; 24 | mp[account]+=money; 25 | return true; 26 | } 27 | 28 | bool withdraw(int account, long long money) { 29 | if(account>size) return false; 30 | if(mp[account]>=money){ 31 | mp[account]-=money; 32 | return true; 33 | } 34 | return false; 35 | } 36 | }; 37 | 38 | /** 39 | * Your Bank object will be instantiated and called as such: 40 | * Bank* obj = new Bank(balance); 41 | * bool param_1 = obj->transfer(account1,account2,money); 42 | * bool param_2 = obj->deposit(account,money); 43 | * bool param_3 = obj->withdraw(account,money); 44 | */ 45 | -------------------------------------------------------------------------------- /2044. Count Number of Maximum Bitwise-OR Subsets: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int res; 4 | int mx; 5 | 6 | void generate(vector&nums,int n,int maxPossible){ 7 | if(n==0){ 8 | if(maxPossible==res){ 9 | mx++; 10 | } 11 | else if(res< maxPossible){ 12 | mx = 1; 13 | res = maxPossible; 14 | } 15 | return; 16 | } 17 | 18 | generate(nums,n-1,maxPossible|nums[n-1]); 19 | generate(nums,n-1,maxPossible); 20 | } 21 | 22 | int countMaxOrSubsets(vector& nums) { 23 | mx = 0; 24 | res =0; 25 | generate(nums,nums.size(),0); 26 | return mx; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /3sum-closest/3sum-closest.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int threeSumClosest(vector& nums, int target) { 4 | int diff = INT_MAX; 5 | int size = nums.size(); 6 | 7 | sort(nums.begin(),nums.end()); 8 | 9 | for(int i=0; i16. 3Sum Closest

Medium


Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
Input: nums = [-1,2,1,-4], target = 1
 7 | Output: 2
 8 | Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
 9 | 
10 | 11 |

 

12 |

Constraints:

13 | 14 |
    15 |
  • 3 <= nums.length <= 10^3
  • 16 |
  • -10^3 <= nums[i] <= 10^3
  • 17 |
  • -10^4 <= target <= 10^4
  • 18 |
19 |
-------------------------------------------------------------------------------- /3sum/3sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> threeSum(vector& nums) { 4 | sort(nums.begin(),nums.end()); 5 | 6 | vector> res; 7 | 8 | for(int i=0; i<(int)nums.size()-2; i++){ 9 | if(i==0 || (i>0 && nums[i] != nums[i-1])){ 10 | int low = i+1; 11 | int high = nums.size()-1; 12 | int sum = 0-nums[i]; 13 | 14 | while(low temp; 17 | temp.push_back(nums[i]); 18 | temp.push_back(nums[low]); 19 | temp.push_back(nums[high]); 20 | res.push_back(temp); 21 | 22 | while(low sum) high--; 28 | else low++; 29 | } 30 | } 31 | } 32 | return res; 33 | } 34 | }; -------------------------------------------------------------------------------- /3sum/README.md: -------------------------------------------------------------------------------- 1 |

15. 3Sum

Medium


Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

2 | 3 |

Notice that the solution set must not contain duplicate triplets.

4 | 5 |

 

6 |

Example 1:

7 |
Input: nums = [-1,0,1,2,-1,-4]
 8 | Output: [[-1,-1,2],[-1,0,1]]
 9 | 

Example 2:

10 |
Input: nums = []
11 | Output: []
12 | 

Example 3:

13 |
Input: nums = [0]
14 | Output: []
15 | 
16 |

 

17 |

Constraints:

18 | 19 |
    20 |
  • 0 <= nums.length <= 3000
  • 21 |
  • -105 <= nums[i] <= 105
  • 22 |
23 |
-------------------------------------------------------------------------------- /Design-twitter/Design-Twitter.cpp: -------------------------------------------------------------------------------- 1 | class Twitter { 2 | public: 3 | 4 | map> following; 5 | list> tweets; 6 | Twitter() { 7 | 8 | } 9 | 10 | void postTweet(int userId, int tweetId) { 11 | tweets.push_front({userId, tweetId}); 12 | } 13 | 14 | vector getNewsFeed(int userId) { 15 | int count = 10; 16 | vector feed; 17 | for (auto x: tweets){ 18 | if (((x.first == userId)||(following[userId].find(x.first) != following[userId].end())) && count > 0){ 19 | feed.push_back(x.second); 20 | count -= 1; 21 | } 22 | } 23 | return feed; 24 | } 25 | 26 | void follow(int followerId, int followeeId) { 27 | if (following[followerId].find(followeeId) == following[followerId].end()){ 28 | following[followerId].insert(followeeId); 29 | } 30 | } 31 | 32 | void unfollow(int followerId, int followeeId) { 33 | if (following[followerId].find(followeeId) != following[followerId].end()){ 34 | following[followerId].erase(followeeId); 35 | } 36 | } 37 | }; -------------------------------------------------------------------------------- /Find First and Last Position of Element in Sorted Array/Find First and Last Position of Element in Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector searchRange(vector& nums, int target) { 4 | vectorans; 5 | 6 | int low = lower_bound(nums.begin(),nums.end(),target) - nums.begin(); 7 | int high = upper_bound(nums.begin(),nums.end(),target) - nums.begin() -1; 8 | 9 | if(low!=nums.size() && high!=nums.size() && nums[low] == target && nums[high] == target){ 10 | ans.push_back(low); 11 | ans.push_back(high); 12 | } 13 | else{ 14 | ans.push_back(-1); 15 | ans.push_back(-1); 16 | } 17 | 18 | return ans; 19 | 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Find First and Last Position of Element in Sorted Array/FirstAndLastPosition.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector searchRange(vector& nums, int target) { 4 | int left = get_first_element_position(nums, target); 5 | int right = get_last_element_position(nums, target); 6 | return left <= right ? vector{left, right} : vector(2, -1); 7 | } 8 | private: 9 | int get_first_element_position(vector& nums, int target){ 10 | int left = 0, right = nums.size() - 1, mid; 11 | while ( left <= right ) 12 | { 13 | mid = (right + left) / 2; 14 | if ( nums[mid] < target) left = mid + 1; 15 | else right = mid - 1; 16 | } 17 | return left; 18 | } 19 | int get_last_element_position(vector& nums, int target){ 20 | int left = 0, right = nums.size() - 1, mid; 21 | while ( left <= right ) 22 | { 23 | mid = (right + left) / 2; 24 | if ( nums[mid] <= target ) left = mid + 1; 25 | else right = mid - 1; 26 | } 27 | return right; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /Min-Cost/MinCost.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minCostClimbingStairs(vector& cost) { 4 | if(cost.size() == 1) 5 | return cost[0]; 6 | int dp[cost.size()+1]; 7 | memset(dp,0,sizeof(dp)); 8 | dp[0] = 0; 9 | dp[1] = 0; 10 | for(int i = 2; i <= cost.size(); i++){ 11 | dp[i] = min(dp[i-1]+cost[i-1],dp[i-2]+cost[i-2]); 12 | } 13 | 14 | return dp[cost.size()]; 15 | } 16 | }; -------------------------------------------------------------------------------- /Search in Rotated Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int search(vector& a, int x) { 4 | int lo = 0, hi = a.size() - 1; 5 | while (lo <= hi) { 6 | int mid = lo + (hi - lo) / 2; 7 | if (a[mid] == x) { 8 | return mid; 9 | } else if (a[mid] >= a.front()) { 10 | auto it = lower_bound(a.begin(), a.begin() + mid + 1, x); 11 | if (it != a.end() and *it == x) 12 | return it - a.begin(); 13 | else 14 | lo = mid + 1; 15 | } else { 16 | auto it = lower_bound(a.begin() + mid, a.end(), x); 17 | if (it != a.end() and *it == x) 18 | return it - a.begin(); 19 | else 20 | hi = mid - 1; 21 | } 22 | } 23 | return -1; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /WildcardMatching.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isMatch(string str, string pattern) { 4 | int n1 = str.size(), n2 = pattern.size(); 5 | vector> dp(n1 + 1, vector (n2 + 1, false)); 6 | dp[0][0] = true; 7 | for (int j = 0; j < n2 and pattern[j] == '*'; ++j) { 8 | // if (pattern[j] == '*') 9 | dp[0][j + 1] = true; 10 | } 11 | for (int i = 1; i <= n1; ++i) { 12 | for (int j = 1; j <= n2; ++j) { 13 | if (pattern[j - 1] == '*') 14 | dp[i][j] = dp[i - 1][j] or dp[i][j - 1]; 15 | else 16 | dp[i][j] = dp[i - 1][j - 1] and 17 | (str[i - 1] == pattern[j - 1] or pattern[j - 1] == '?'); 18 | } 19 | } 20 | // for (int i = 0; i <= n1; ++i) { 21 | // for (int j = 0; j <= n2; ++j) 22 | // cout << dp[i][j] << ' '; 23 | // cout << '\n'; 24 | // } 25 | return dp[n1][n2]; 26 | } 27 | }; 28 | /* 29 | 1 0 0 0 0 0 30 | 0 1 1 0 0 0 31 | 0 0 1 1 1 0 32 | 0 0 0 0 1 1 33 | */ 34 | -------------------------------------------------------------------------------- /add-MatrixZero/addMatrixzero.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void setZeroes(vector>& a) { 4 | int n = a.size(), m = a[0].size(); 5 | bool row0 = false, col0 = false; 6 | if (find(a[0].begin(), a[0].end(), 0) != a[0].end()) 7 | row0 = true; 8 | for (int i = 0; i < n; ++i) { 9 | if (a[i][0] == 0) 10 | col0 = true; 11 | } 12 | for (int i = 1; i < n; ++i) { 13 | for (int j = 1; j < m; ++j) { 14 | if (a[i][j] == 0) 15 | a[0][j] = a[i][0] = 0; 16 | } 17 | } 18 | for (int i = 1; i < n; ++i) { 19 | if (a[i][0] == 0) 20 | a[i].assign(m, 0); 21 | } 22 | for (int j = 1; j < m; ++j) { 23 | if (a[0][j] == 0) { 24 | for (int i = 1; i < n; ++i) 25 | a[i][j] = 0; 26 | } 27 | } 28 | if (row0 == true) 29 | a[0].assign(m, 0); 30 | if (col0 == true) { 31 | for (int i = 0; i < n; ++i) 32 | a[i][0] = 0; 33 | } 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /add-strings/README.md: -------------------------------------------------------------------------------- 1 |

415. Add Strings

Easy


Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.

2 | 3 |

You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
Input: num1 = "11", num2 = "123"
 9 | Output: "134"
10 | 
11 | 12 |

Example 2:

13 | 14 |
Input: num1 = "456", num2 = "77"
15 | Output: "533"
16 | 
17 | 18 |

Example 3:

19 | 20 |
Input: num1 = "0", num2 = "0"
21 | Output: "0"
22 | 
23 | 24 |

 

25 |

Constraints:

26 | 27 |
    28 |
  • 1 <= num1.length, num2.length <= 104
  • 29 |
  • num1 and num2 consist of only digits.
  • 30 |
  • num1 and num2 don't have any leading zeros except for the zero itself.
  • 31 |
32 |
-------------------------------------------------------------------------------- /add-strings/add-strings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string addStrings(string num1, string num2) { 4 | int i = num1.size() - 1; 5 | int j = num2.size() - 1; 6 | int carry = 0; 7 | string res = ""; 8 | while(i>=0 || j>=0 || carry){ 9 | long sum = 0; 10 | if(i >= 0){sum += (num1[i] - '0');i--;} 11 | if(j >= 0){sum += (num2[j] - '0');j--;} 12 | sum += carry; 13 | carry = sum / 10; 14 | sum = sum % 10; 15 | res = res + to_string(sum); 16 | } 17 | reverse(res.begin(), res.end()); 18 | return res; 19 | } 20 | }; -------------------------------------------------------------------------------- /allocate-mailboxes/allocate-mailboxes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minDistance(vector& houses, int k) { 4 | sort(begin(houses), end(houses)); 5 | vector prefix(houses.size() + 1); 6 | for (int i = 0; i < houses.size(); ++i) { 7 | prefix[i + 1] = prefix[i] + houses[i]; 8 | } 9 | vector dp(houses.size()); 10 | for (int j = 0; j < houses.size(); ++j) { 11 | dp[j] = cost(prefix, 0, j); 12 | } 13 | for (int m = 1; m < k; ++m) { 14 | for (int j = houses.size() - 1; j >= 0; --j) { 15 | for (int i = m; i <= j; ++i) { 16 | dp[j] = min(dp[j], dp[i - 1] + cost(prefix, i, j)); 17 | } 18 | } 19 | } 20 | return dp.back(); 21 | } 22 | 23 | private: 24 | int cost(const vector& prefix, int i, int j) { 25 | return (prefix[j + 1] - prefix[(i + j + 1) / 2]) - 26 | (prefix[(i + j) / 2 + 1] - prefix[i]); 27 | } 28 | }; -------------------------------------------------------------------------------- /arithmetic-slices-ii-subsequence/arithmetic-slices-ii-subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numberOfArithmeticSlices(vector& nums) { 4 | int n = nums.size(); 5 | 6 | long long ans = 0; 7 | 8 | vector> cnt(n); 9 | 10 | for(int i=1; i413. Arithmetic Slices

Medium


An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.

2 | 3 |
    4 |
  • For example, [1,3,5,7,9], [7,7,7,7], and [3,-1,-5,-9] are arithmetic sequences.
  • 5 |
6 | 7 |

Given an integer array nums, return the number of arithmetic subarrays of nums.

8 | 9 |

A subarray is a contiguous subsequence of the array.

10 | 11 |

 

12 |

Example 1:

13 | 14 |
Input: nums = [1,2,3,4]
15 | Output: 3
16 | Explanation: We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself.
17 | 
18 | 19 |

Example 2:

20 | 21 |
Input: nums = [1]
22 | Output: 0
23 | 
24 | 25 |

 

26 |

Constraints:

27 | 28 |
    29 |
  • 1 <= nums.length <= 5000
  • 30 |
  • -1000 <= nums[i] <= 1000
  • 31 |
32 |
-------------------------------------------------------------------------------- /arithmetic-slices/arithmetic-slices.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numberOfArithmeticSlices(vector& A) { 4 | 5 | int n = A.size(); 6 | if (n < 3) return 0; 7 | vector dp(n, 0); 8 | if (A[2]-A[1] == A[1]-A[0]) dp[2] = 1; 9 | int result = dp[2]; 10 | for (int i = 3; i < n; ++i) { 11 | if (A[i]-A[i-1] == A[i-1]-A[i-2]) 12 | dp[i] = dp[i-1] + 1; 13 | result += dp[i]; 14 | } 15 | return result; 16 | 17 | 18 | } 19 | }; -------------------------------------------------------------------------------- /array-nesting/array-nesting.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int arrayNesting(vector& nums) { 4 | 5 | int ans = 0, n = nums.size(); 6 | 7 | 8 | for(int i=0; i= 0 && (back > 0 || S[i] == '#')) { 8 | back += S[i] == '#' ? 1 : -1; 9 | i--; 10 | } 11 | back = 0; 12 | while (j >= 0 && (back > 0 || T[j] == '#')) { 13 | back += T[j] == '#' ? 1 : -1; 14 | j--; 15 | } 16 | if (i >= 0 && j >= 0 && S[i] == T[j]) { 17 | i--; 18 | j--; 19 | } else { 20 | break; 21 | } 22 | } 23 | return i == -1 && j == -1; 24 | } -------------------------------------------------------------------------------- /beautiful-arrangement/Beautiful Arrangement.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int solve(vector&nums, vector&vis, int index, int n){ 4 | if(index==n+1){ 5 | return 1; 6 | } 7 | int res=0; 8 | for(int i=0;inums, vis(n+1,0); 19 | for(int i=1;i<=n;i++){ 20 | nums.push_back(i); 21 | } 22 | 23 | int ans=solve(nums,vis,1,n); 24 | return ans; 25 | 26 | } 27 | }; -------------------------------------------------------------------------------- /beautiful-array/README.md: -------------------------------------------------------------------------------- 1 |

932. Beautiful Array

Medium


For some fixed n, an array nums is beautiful if it is a permutation of the integers 1, 2, ..., n, such that:

2 | 3 |

For every i < j, there is no k with i < k < j such that nums[k] * 2 = nums[i] + nums[j].

4 | 5 |

Given n, return any beautiful array nums.  (It is guaranteed that one exists.)

6 | 7 |

 

8 | 9 |

Example 1:

10 | 11 |
Input: n = 4
12 | Output: [2,1,4,3]
13 | 
14 | 15 |
16 |

Example 2:

17 | 18 |
Input: n = 5
19 | Output: [3,1,2,5,4]
20 | 21 |

 

22 |
23 | 24 |

Note:

25 | 26 |
    27 |
  • 1 <= n <= 1000
  • 28 |
29 | 30 |
31 |
 
32 |
33 |
-------------------------------------------------------------------------------- /beautiful-array/beautiful-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int partition(vector &v, int start, int end, int mask) 4 | { 5 | int j = start; 6 | for(int i = start; i <= end; i++) 7 | { 8 | if((v[i] & mask) != 0) 9 | { 10 | swap(v[i], v[j]); 11 | j++; 12 | } 13 | } 14 | return j; 15 | } 16 | 17 | void sort(vector & v, int start, int end, int mask) 18 | { 19 | if(start >= end) return; 20 | int mid = partition(v, start, end, mask); 21 | sort(v, start, mid - 1, mask << 1); 22 | sort(v, mid, end, mask << 1); 23 | } 24 | 25 | vector beautifulArray(int N) { 26 | vector ans; 27 | for(int i = 0; i < N; i++) ans.push_back(i + 1); 28 | sort(ans, 0, N - 1, 1); 29 | return ans; 30 | } 31 | }; -------------------------------------------------------------------------------- /best-sightseeing-pair/README.md: -------------------------------------------------------------------------------- 1 |

1014. Best Sightseeing Pair

Medium


You are given an integer array values where values[i] represents the value of the ith sightseeing spot. Two sightseeing spots i and j have a distance j - i between them.

2 | 3 |

The score of a pair (i < j) of sightseeing spots is values[i] + values[j] + i - j: the sum of the values of the sightseeing spots, minus the distance between them.

4 | 5 |

Return the maximum score of a pair of sightseeing spots.

6 | 7 |

 

8 |

Example 1:

9 | 10 |
Input: values = [8,1,5,2,6]
11 | Output: 11
12 | Explanation: i = 0, j = 2, values[i] + values[j] + i - j = 8 + 5 + 0 - 2 = 11
13 | 
14 | 15 |

Example 2:

16 | 17 |
Input: values = [1,2]
18 | Output: 2
19 | 
20 | 21 |

 

22 |

Constraints:

23 | 24 |
    25 |
  • 2 <= values.length <= 5 * 104
  • 26 |
  • 1 <= values[i] <= 1000
  • 27 |
28 |
-------------------------------------------------------------------------------- /best-sightseeing-pair/best-sightseeing-pair.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxScoreSightseeingPair(vector& values) { 4 | int res = 0, cur = 0; 5 | 6 | for(int val: values){ 7 | 8 | res = max(res, cur+val); 9 | cur = max(cur,val)-1; 10 | 11 | } 12 | return res; 13 | } 14 | }; -------------------------------------------------------------------------------- /best-time-to-buy-and-sell-stock-ii/best-time-to-buy-and-sell-stock-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices) { 4 | int maxprofit = 0; 5 | for (int i = 1; i < prices.size(); i++) { 6 | if (prices[i] > prices[i - 1]) 7 | maxprofit += prices[i] - prices[i - 1]; 8 | } 9 | return maxprofit; 10 | } 11 | }; -------------------------------------------------------------------------------- /best-time-to-buy-and-sell-stock-with-cooldown/best-time-to-buy-and-sell-stock-with-cooldown.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices){ 4 | if (prices.size() <= 1) return 0; 5 | vector s0(prices.size(), 0); 6 | vector s1(prices.size(), 0); 7 | vector s2(prices.size(), 0); 8 | s1[0] = -prices[0]; 9 | s0[0] = 0; 10 | s2[0] = INT_MIN; 11 | for (int i = 1; i < prices.size(); i++) { 12 | s0[i] = max(s0[i - 1], s2[i - 1]); 13 | s1[i] = max(s1[i - 1], s0[i - 1] - prices[i]); 14 | s2[i] = s1[i - 1] + prices[i]; 15 | } 16 | return max(s0[prices.size() - 1], s2[prices.size() - 1]); 17 | } 18 | }; -------------------------------------------------------------------------------- /best-time-to-buy-and-sell-stock-with-transaction-fee/best-time-to-buy-and-sell-stock-with-transaction-fee.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices, int fee) { 4 | int cash = 0, hold = -prices[0]; 5 | for (int i = 1; i < prices.size(); i++) { 6 | cash = max(cash, hold + prices[i] - fee); 7 | hold = max(hold, cash - prices[i]); 8 | } 9 | return cash; 10 | } 11 | }; -------------------------------------------------------------------------------- /best-time-to-buy-and-sell-stock/best-time-to-buy-and-sell-stock.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices) { 4 | int n = prices.size(); 5 | int minprice = INT_MAX; 6 | int maxprofit = 0; 7 | 8 | for(int i=0; i maxprofit){ 13 | maxprofit = prices[i] - minprice; 14 | } 15 | } 16 | return maxprofit; 17 | } 18 | }; -------------------------------------------------------------------------------- /binary-search/README.md: -------------------------------------------------------------------------------- 1 |

704. Binary Search

Easy


Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.

2 | 3 |

You must write an algorithm with O(log n) runtime complexity.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
Input: nums = [-1,0,3,5,9,12], target = 9
 9 | Output: 4
10 | Explanation: 9 exists in nums and its index is 4
11 | 
12 | 13 |

Example 2:

14 | 15 |
Input: nums = [-1,0,3,5,9,12], target = 2
16 | Output: -1
17 | Explanation: 2 does not exist in nums so return -1
18 | 
19 | 20 |

 

21 |

Constraints:

22 | 23 |
    24 |
  • 1 <= nums.length <= 104
  • 25 |
  • -104 < nums[i], target < 104
  • 26 |
  • All the integers in nums are unique.
  • 27 |
  • nums is sorted in ascending order.
  • 28 |
29 |
-------------------------------------------------------------------------------- /binary-search/binary-search.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int search(vector& nums, int target) { 4 | int mid, left = 0, right = nums.size() - 1; 5 | while (left <= right) { 6 | mid = left + (right - left) / 2; 7 | if (nums[mid] == target) return mid; 8 | if (target < nums[mid]) right = mid - 1; 9 | else left = mid + 1; 10 | } 11 | return -1; 12 | } 13 | }; -------------------------------------------------------------------------------- /binary-tree-inorder-traversal/binary-tree-inorder-traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | 15 | vector res; 16 | 17 | void helper(TreeNode* root){ 18 | if(!root) return; 19 | 20 | helper(root->left); 21 | res.push_back(root->val); 22 | helper(root->right); 23 | 24 | } 25 | 26 | vector inorderTraversal(TreeNode* root) { 27 | helper(root); 28 | return res; 29 | } 30 | }; -------------------------------------------------------------------------------- /binary-tree-level-order-traversal/README.md: -------------------------------------------------------------------------------- 1 |

102. Binary Tree Level Order Traversal

Medium


Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).

2 | 3 |

 

4 |

Example 1:

5 | 6 |
Input: root = [3,9,20,null,null,15,7]
 7 | Output: [[3],[9,20],[15,7]]
 8 | 
9 | 10 |

Example 2:

11 | 12 |
Input: root = [1]
13 | Output: [[1]]
14 | 
15 | 16 |

Example 3:

17 | 18 |
Input: root = []
19 | Output: []
20 | 
21 | 22 |

 

23 |

Constraints:

24 | 25 |
    26 |
  • The number of nodes in the tree is in the range [0, 2000].
  • 27 |
  • -1000 <= Node.val <= 1000
  • 28 |
29 |
-------------------------------------------------------------------------------- /binary-tree-level-order-traversal/binary-tree-level-order-traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | vector> levelOrder(TreeNode* root) { 15 | vector> ans; 16 | if(root == NULL) return ans; 17 | queue q; 18 | q.push(root); 19 | while(!q.empty()) { 20 | int size = q.size(); 21 | vector level; 22 | for(int i = 0;ileft != NULL) q.push(node->left); 26 | if(node->right != NULL) q.push(node->right); 27 | level.push_back(node->val); 28 | } 29 | ans.push_back(level); 30 | } 31 | return ans; 32 | } 33 | 34 | }; -------------------------------------------------------------------------------- /binary-tree-maximum-path-sum/binary-tree-maximum-path-sum.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | 15 | int maxPathSum_util(TreeNode *root,int &result) 16 | { 17 | if(!root) 18 | return 0; 19 | 20 | int left = maxPathSum_util(root->left,result); 21 | int right = maxPathSum_util(root->right,result); 22 | 23 | int max_straight = max(max(left,right)+root->val, root->val); 24 | int max_caseVal = max(max_straight,left+right+root->val); 25 | result = max(max_caseVal,result); 26 | 27 | return max_straight; 28 | } 29 | 30 | int maxPathSum(TreeNode* root) { 31 | int result = INT_MIN; 32 | maxPathSum_util(root,result); 33 | return result; 34 | } 35 | }; -------------------------------------------------------------------------------- /binary-tree-postorder-traversal/postorder.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | 13 | class Solution { 14 | public: 15 | vector preorderTraversal(TreeNode* root) { 16 | vector ans; 17 | postorderHelper(root,ans); 18 | return ans; 19 | } 20 | 21 | void postorderHelper(TreeNode* root,vector &ans) 22 | { 23 | if (node == NULL) 24 | return; 25 | 26 | postorderHelper(node->left); 27 | postorderHelper(node->right); 28 | printf("%d ", node->data); 29 | } 30 | 31 | }; -------------------------------------------------------------------------------- /binary-tree-preorder-traversal/binary-tree-preorder-traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | 13 | class Solution { 14 | public: 15 | vector preorderTraversal(TreeNode* root) { 16 | vector ans; 17 | preorderHelper(root,ans); 18 | return ans; 19 | } 20 | 21 | void preorderHelper(TreeNode* root,vector &ans) 22 | { 23 | if(root) 24 | { 25 | ans.push_back((root->val)); 26 | preorderHelper(root->left,ans); 27 | preorderHelper(root->right,ans); 28 | } 29 | } 30 | 31 | }; -------------------------------------------------------------------------------- /binary-tree-pruning/binary-tree-pruning.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | TreeNode* pruneTree(TreeNode* root) { 15 | if(!root) return root; 16 | 17 | root->left = pruneTree(root->left); 18 | root->right = pruneTree(root->right); 19 | 20 | if(root->val == 0 && !root->left && !root->right){ 21 | root = NULL; 22 | } 23 | 24 | return root; 25 | 26 | } 27 | }; -------------------------------------------------------------------------------- /binary-tree-right-side-view/README.md: -------------------------------------------------------------------------------- 1 |

199. Binary Tree Right Side View

Medium


Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
Input: root = [1,2,3,null,5,null,4]
 7 | Output: [1,3,4]
 8 | 
9 | 10 |

Example 2:

11 | 12 |
Input: root = [1,null,3]
13 | Output: [1,3]
14 | 
15 | 16 |

Example 3:

17 | 18 |
Input: root = []
19 | Output: []
20 | 
21 | 22 |

 

23 |

Constraints:

24 | 25 |
    26 |
  • The number of nodes in the tree is in the range [0, 100].
  • 27 |
  • -100 <= Node.val <= 100
  • 28 |
29 |
-------------------------------------------------------------------------------- /burst-ballons/burst-balloons.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxCoins(vector& a) { 4 | a.insert(a.begin(), 1); 5 | a.push_back(1); 6 | int n = a.size(); 7 | int dp[n][n]; 8 | for (int i = 1; i < n; ++i) 9 | dp[i][i] = 0; 10 | for (int l = 2; l < n; ++l) { 11 | for (int i = 1; i + l - 1 < n; ++i) { 12 | int j = i + l - 1; 13 | dp[i][j] = -1e9; 14 | for (int k = i; k <= j - 1; ++k) 15 | dp[i][j] = max(dp[i][j], dp[i][k] + dp[k + 1][j] + 16 | a[i - 1] * a[k] * a[j]); 17 | } 18 | } 19 | // for (int i = 1; i < n; ++i) { 20 | // for (int j = 1; j < n; ++j) 21 | // cout << dp[i][j] << ' '; 22 | // cout << endl; 23 | // } 24 | return dp[1][n - 1]; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /cheapest-flights-within-K-stops/Cheapest Flights Within K Stops.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int intmax = 1e5; 4 | typedef pair pii; 5 | int findCheapestPrice(int n, vector>& edges, int src, int dest, int K) { 6 | vector adj[n]; 7 | for (auto it : edges) { 8 | adj[it[0]].push_back({it[1], it[2]}); 9 | } 10 | vector dist(n, intmax); 11 | dist[src] = 0; 12 | queue q; 13 | q.push({0, src}); 14 | int ans = 1e8; 15 | while (!q.empty() and K-- >= 0) { 16 | int sz = q.size(); 17 | for (int i = 0; i < sz; ++i) { 18 | auto [dist_node, node] = q.front(); 19 | q.pop(); 20 | for (auto [nbr, d] : adj[node]) { 21 | if (dist[nbr] > d + dist_node) { 22 | dist[nbr] = d + dist_node; 23 | q.push({dist[nbr], nbr}); 24 | } 25 | if (nbr == dest) 26 | ans = min(ans, dist[nbr]); 27 | } 28 | } 29 | } 30 | return ans == 1e8 ? -1 : ans; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /cherry-pickup-ii/cherry-pickup-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int dp[80][80][80]; 5 | 6 | int helper(vector>& grid, int c1, int c2, int r){ 7 | 8 | int n = grid.size(); 9 | int m = grid[0].size(); 10 | 11 | if(r==n) return 0; 12 | if(dp[c1][c2][r] != -1) return dp[c1][c2][r]; 13 | 14 | int ans = 0; 15 | for(int i=c1-1; i<=c1+1; i++){ 16 | for(int j=c2-1; j<=c2+1; j++){ 17 | if(i>=0 && i=0 && j>& grid) { 28 | memset(dp,-1,sizeof(dp)); 29 | int n = grid.size(); 30 | int m = grid[0].size(); 31 | return helper(grid,0,m-1,0); 32 | } 33 | }; -------------------------------------------------------------------------------- /cherry-pickup/cherry-pickup.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int dp[51][51][51]; 5 | 6 | int helper(vector>& grid, int r1, int c1, int c2){ 7 | int r2 = r1+c1-c2; 8 | int n = grid.size(); 9 | if(n == r1 || n == r2 || n == c1 || n == c2 || grid[r1][c1] == -1 || grid[r2][c2] == -1){ 10 | return INT_MIN; 11 | } 12 | else if(r1 == n-1 && c1 == n-1){ 13 | return grid[r1][c1]; 14 | } 15 | else if(dp[r1][c1][c2] != INT_MIN){ 16 | return dp[r1][c1][c2]; 17 | } 18 | else{ 19 | int ans = grid[r1][c1]; 20 | if(c1!=c2) ans+=grid[r2][c2]; 21 | 22 | ans += max(max(helper(grid,r1+1,c1,c2),helper(grid,r1,c1+1,c2+1)),max(helper(grid,r1+1,c1,c2+1),helper(grid,r1,c1+1,c2))); 23 | dp[r1][c1][c2] = ans; 24 | return ans; 25 | } 26 | 27 | } 28 | 29 | int cherryPickup(vector>& grid) { 30 | int n = grid.size(); 31 | for(int i=0; i<51; i++) 32 | for(int j=0; j<51; j++) 33 | for(int k=0; k<51; k++) 34 | dp[i][j][k] = INT_MIN; 35 | return max(0,helper(grid,0,0,0)); 36 | } 37 | }; -------------------------------------------------------------------------------- /climbing-stairs/README.md: -------------------------------------------------------------------------------- 1 |

70. Climbing Stairs

Easy


You are climbing a staircase. It takes n steps to reach the top.

2 | 3 |

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

4 | 5 |

 

6 |

Example 1:

7 | 8 |
Input: n = 2
 9 | Output: 2
10 | Explanation: There are two ways to climb to the top.
11 | 1. 1 step + 1 step
12 | 2. 2 steps
13 | 
14 | 15 |

Example 2:

16 | 17 |
Input: n = 3
18 | Output: 3
19 | Explanation: There are three ways to climb to the top.
20 | 1. 1 step + 1 step + 1 step
21 | 2. 1 step + 2 steps
22 | 3. 2 steps + 1 step
23 | 
24 | 25 |

 

26 |

Constraints:

27 | 28 |
    29 |
  • 1 <= n <= 45
  • 30 |
31 |
-------------------------------------------------------------------------------- /climbing-stairs/climbing-stairs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int climbStairs(int n) { 4 | int arr[n+1]; 5 | 6 | arr[0] = 1; 7 | arr[1] = 1; 8 | 9 | for(int i = 2; i<=n; i++){ 10 | arr[i] = arr[i-1] + arr[i-2]; 11 | } 12 | 13 | return arr[n]; 14 | 15 | } 16 | }; -------------------------------------------------------------------------------- /coin-change-2/coin_change2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int change(int amount, vector& coins) { 4 | 5 | int n=coins.size(); 6 | 7 | int dp[n+1][amount+1]; 8 | 9 | 10 | 11 | for(int i=0;i<=n;i++){ 12 | 13 | dp[i][0]=1; 14 | } 15 | 16 | for(int j=1;j<=amount;j++){ 17 | dp[0][j]=0; 18 | } 19 | 20 | for(int i=1;i<=n;i++){ 21 | 22 | 23 | for(int j=1;j<=amount;j++){ 24 | 25 | if(coins[i-1]<=j){ 26 | 27 | dp[i][j]=dp[i-1][j]+dp[i][j-coins[i-1]]; 28 | } 29 | else{ 30 | dp[i][j]=dp[i-1][j]; 31 | } 32 | 33 | } 34 | } 35 | return dp[n][amount]; 36 | 37 | 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /coin-change/coin-change.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int coinChange(vector& coins, int amount) { 4 | 5 | vector dp(amount+1, INT_MAX); 6 | 7 | dp[0] = 0; 8 | 9 | sort(coins.begin(), coins.end()); 10 | 11 | for(int i=1; i<=amount; i++){ 12 | 13 | for(int coin : coins){ 14 | if(i& nums, int target) { 5 | 6 | vector dp(target + 1); 7 | dp[0] = 1; 8 | sort (nums.begin(), nums.end()); 9 | for (int i = 1; i <= target; i++) { 10 | for (auto num : nums) { 11 | if (i < num) break; 12 | dp[i] += dp[i - num]; 13 | } 14 | } 15 | return dp.back(); 16 | 17 | } 18 | }; -------------------------------------------------------------------------------- /combination-sum/combination-sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | vector> res; 5 | 6 | vector> combinationSum(vector& candidates, int target) { 7 | sort(candidates.begin(), candidates.end()); 8 | 9 | vector temp; 10 | 11 | helper(candidates, temp, target, 0); 12 | return res; 13 | } 14 | 15 | void helper(vector& candidates, vector& temp, int target, int i){ 16 | 17 | if(target == 0){ 18 | res.push_back(temp); 19 | return; 20 | } 21 | 22 | if(i>= candidates.size() || target < 0) return; 23 | 24 | temp.push_back(candidates[i]); 25 | helper(candidates, temp, target-candidates[i], i); 26 | temp.pop_back(); 27 | helper(candidates, temp, target, i+1); 28 | 29 | } 30 | 31 | }; -------------------------------------------------------------------------------- /combinations/README.md: -------------------------------------------------------------------------------- 1 |

77. Combinations

Medium


Given two integers n and k, return all possible combinations of k numbers out of the range [1, n].

2 | 3 |

You may return the answer in any order.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
Input: n = 4, k = 2
 9 | Output:
10 | [
11 |   [2,4],
12 |   [3,4],
13 |   [2,3],
14 |   [1,2],
15 |   [1,3],
16 |   [1,4],
17 | ]
18 | 
19 | 20 |

Example 2:

21 | 22 |
Input: n = 1, k = 1
23 | Output: [[1]]
24 | 
25 | 26 |

 

27 |

Constraints:

28 | 29 |
    30 |
  • 1 <= n <= 20
  • 31 |
  • 1 <= k <= n
  • 32 |
33 |
-------------------------------------------------------------------------------- /combinations/combinations.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | vector> ans; 5 | vector temp; 6 | 7 | void helper(int n, int k, int i){ 8 | 9 | if(k == 0){ 10 | ans.push_back(temp); 11 | return; 12 | } 13 | 14 | if(i > n || k<0){ 15 | return; 16 | } 17 | 18 | temp.push_back(i); 19 | helper(n,k-1,i+1); 20 | temp.pop_back(); 21 | helper(n,k,i+1); 22 | } 23 | 24 | vector> combine(int n, int k) { 25 | 26 | helper(n,k,1); 27 | return ans; 28 | } 29 | }; -------------------------------------------------------------------------------- /complex-number-multiplication/complex-number-multiplication.cpp: -------------------------------------------------------------------------------- 1 | //Leetcode 537 2 | class Solution { 3 | public: 4 | int realpart(string str){ 5 | int i = 0 ; 6 | string realpart = "" ; 7 | 8 | while(str[i]!='+'){ 9 | realpart += str[i] ; 10 | i++ ; 11 | } 12 | return stoi(realpart) ; 13 | } 14 | 15 | int complex(string str){ 16 | int i = 0 ; 17 | string complex = "" ; 18 | 19 | while(str[i]!='+'){ 20 | i++ ; 21 | } 22 | 23 | i++ ; 24 | 25 | while(str[i]!='i'){ 26 | complex += str[i] ; 27 | i++ ; 28 | } 29 | 30 | return stoi(complex) ; 31 | } 32 | 33 | string complexNumberMultiply(string a, string b) { 34 | string result = "" ; 35 | int a1 = realpart(a) ; 36 | int a2 = realpart(b) ; 37 | int b1 = complex(a) ; 38 | int b2 = complex(b) ; 39 | 40 | result = result + to_string(a1*a2-b1*b2)+'+'+to_string(a1*b2+a2*b1)+'i' ; 41 | 42 | return result ; 43 | } 44 | }; -------------------------------------------------------------------------------- /container-with-most-water/container-with-most-water.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxArea(vector& height) { 4 | int ans = 0; 5 | int left = 0, right = height.size() - 1; 6 | while (left < right) { 7 | int h = min(height[left], height[right]); 8 | ans = max(ans, (right - left) * h); 9 | while (height[left] <= h && left < right) left++; 10 | while (height[right] <= h && left < right) right--; 11 | } 12 | return ans; 13 | } 14 | }; -------------------------------------------------------------------------------- /convert-sorted-array-to-binary-search-tree/convert-sorted-array-to-binary-search-tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | TreeNode* helper(vector nums, int i, int j){ 15 | 16 | 17 | if(i>=j) return NULL; 18 | 19 | int mid = (i+j)/2; 20 | 21 | TreeNode* root = new TreeNode(nums[mid]); 22 | root->left = helper(nums, i, mid); 23 | root->right = helper(nums, mid+1, j); 24 | 25 | return root; 26 | 27 | } 28 | 29 | TreeNode* sortedArrayToBST(vector& nums) { 30 | 31 | int n = nums.size(); 32 | return helper(nums, 0, n); 33 | 34 | } 35 | }; -------------------------------------------------------------------------------- /count-good-nodes-in-binary-tree/count-good-nodes-in-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int goodNodesHelper(TreeNode* root, int msf){ 15 | 16 | if(!root){ 17 | return 0; 18 | } 19 | 20 | int temp = 0; 21 | 22 | int leftGoodNodes = goodNodesHelper(root->left, max(msf,root->val)); 23 | int rightGoodNodes = goodNodesHelper(root->right, max(msf,root->val)); 24 | 25 | if(root->val >= msf) temp++; 26 | 27 | return temp + leftGoodNodes + rightGoodNodes; 28 | 29 | } 30 | 31 | int goodNodes(TreeNode* root) { 32 | return goodNodesHelper(root, INT_MIN); 33 | } 34 | }; -------------------------------------------------------------------------------- /countAndSay.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string fun(int n,vector &dp) 4 | { 5 | if(n==1) 6 | return "1"; 7 | if(dp[n]!="-1") 8 | return dp[n]; 9 | string prev=fun(n-1,dp); 10 | //time for string compression 11 | string ans; 12 | int cnt=1; 13 | char ele=prev[0]; 14 | //scan elements 15 | for(int i=1;i dp(31,"-1"); 32 | return fun(n,dp); 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /counting-bits/counting-bits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector countBits(int n) { 4 | vector res(n); 5 | res.push_back(0); 6 | if(n==0) return res; 7 | 8 | for(int i=1;i<=n;i++){ 9 | if(i%2==0){ 10 | res[i]=res[i/2]; 11 | } else { 12 | res[i]=res[i-1]+1; 13 | } 14 | } 15 | return res; 16 | } 17 | }; -------------------------------------------------------------------------------- /course-schedule/course-schedule.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | bool canFinish(int n, vector>& prerequisites) { 5 | vector> G(n); 6 | vector degree(n, 0), bfs; 7 | for (auto& e : prerequisites) 8 | G[e[1]].push_back(e[0]), degree[e[0]]++; 9 | for (int i = 0; i < n; ++i) if (!degree[i]) bfs.push_back(i); 10 | for (int i = 0; i < bfs.size(); ++i) 11 | for (int j: G[bfs[i]]) 12 | if (--degree[j] == 0) bfs.push_back(j); 13 | return bfs.size() == n; 14 | } 15 | }; -------------------------------------------------------------------------------- /daily-temperatures/README.md: -------------------------------------------------------------------------------- 1 |

739. Daily Temperatures

Medium


Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.

2 | 3 |

 

4 |

Example 1:

5 |
Input: temperatures = [73,74,75,71,69,72,76,73]
 6 | Output: [1,1,4,2,1,1,0,0]
 7 | 

Example 2:

8 |
Input: temperatures = [30,40,50,60]
 9 | Output: [1,1,1,0]
10 | 

Example 3:

11 |
Input: temperatures = [30,60,90]
12 | Output: [1,1,0]
13 | 
14 |

 

15 |

Constraints:

16 | 17 |
    18 |
  • 1 <= temperatures.length <= 105
  • 19 |
  • 30 <= temperatures[i] <= 100
  • 20 |
21 |
-------------------------------------------------------------------------------- /daily-temperatures/daily-temperatures.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector dailyTemperatures(vector& temperatures) { 4 | 5 | stack s; 6 | vector ans(temperatures.size(),0); 7 | 8 | for(int i=0; i temperatures[s.top()]){ 11 | int idx = s.top(); 12 | s.pop(); 13 | ans[idx] = i-idx; 14 | } 15 | s.push(i); 16 | } 17 | return ans; 18 | } 19 | }; -------------------------------------------------------------------------------- /decode-string/decode-string.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | bool isDigit(char c) { 5 | return c - '0' >= 0 && c - '0' <= 9; 6 | } 7 | int i=0; 8 | string decodeString(string s) { 9 | string res = "", num = "";; 10 | 11 | while(i=s.size())return 1; 6 | if(dp[i]!=-1)return dp[i]; 7 | int ans=0; 8 | int x1=s[i]-48,x2=0; 9 | if(i0)ans+=solve(i+1,s,dp); 14 | if(x1>0 and x2>0 and x2<=26)ans+=solve(i+2,s,dp); 15 | return dp[i]=ans; 16 | } 17 | int numDecodings(string s) { 18 | int dp[101]; 19 | memset(dp,-1,sizeof(dp)); 20 | return solve(0,s,dp); 21 | 22 | } 23 | }; -------------------------------------------------------------------------------- /decode-ways/decodeWays.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numDecodings(string s) { 4 | 5 | int sz=s.size()-1; 6 | if(s[0]=='0') return 0; 7 | if(sz==0) return 1; 8 | int n=sz+1; 9 | vector dp(n+1,0); 10 | dp[1]=1; 11 | dp[0]=1; 12 | if(s[0]=='0') return 0; 13 | for(int i=2;i<=n;i++){ 14 | int x=s[i-1]-'0'; 15 | if(x>0) dp[i]=dp[i-1]; 16 | int y=s[i-2]-'0'; 17 | if(y==1||(y==2&&x<7)) dp[i]+=dp[i-2]; 18 | } 19 | return dp[n]; 20 | } 21 | }; -------------------------------------------------------------------------------- /delete-and-earn/delete-and-earn.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int deleteAndEarn(vector& nums) { 4 | int sums[10005]; 5 | memset(sums,0,sizeof(sums)); 6 | for(int i=0;i543. Diameter of Binary Tree

Easy


Given the root of a binary tree, return the length of the diameter of the tree.

2 | 3 |

The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

4 | 5 |

The length of a path between two nodes is represented by the number of edges between them.

6 | 7 |

 

8 |

Example 1:

9 | 10 |
Input: root = [1,2,3,4,5]
11 | Output: 3
12 | Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].
13 | 
14 | 15 |

Example 2:

16 | 17 |
Input: root = [1,2]
18 | Output: 1
19 | 
20 | 21 |

 

22 |

Constraints:

23 | 24 |
    25 |
  • The number of nodes in the tree is in the range [1, 104].
  • 26 |
  • -100 <= Node.val <= 100
  • 27 |
28 |
-------------------------------------------------------------------------------- /diameter-of-binary-tree/diameter-of-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | 15 | int ans=0; 16 | 17 | int height(TreeNode* root) 18 | { 19 | if(!root) return 0; 20 | 21 | int lHeight = height(root->left); 22 | int rHeight = height(root->right); 23 | 24 | ans= max(ans, 1 + lHeight + rHeight); 25 | return 1+ max( lHeight , rHeight); 26 | 27 | } 28 | 29 | int diameterOfBinaryTree(TreeNode* root) { 30 | if(!root) return 0; 31 | height(root); 32 | return ans-1; 33 | } 34 | }; -------------------------------------------------------------------------------- /dungeon-game/dungeon-game.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int m, n; 4 | int calculateMinimumHP(vector>& grid) { 5 | m = grid.size(); n = grid[0].size(); 6 | int left = 1, right = 1000 * (m+n) + 1, ans = right; 7 | while (left <= right) { 8 | int mid = left + (right - left) / 2; 9 | if (isGood(grid, mid)) { 10 | ans = mid; 11 | right = mid - 1; 12 | } else left = mid + 1; 13 | } 14 | return ans; 15 | } 16 | bool isGood(vector>& grid, int initHealth) { 17 | vector> dp(m, vector(n, 0)); 18 | dp[0][0] = initHealth + grid[0][0]; 19 | for (int r = 0; r < m; ++r) { 20 | for (int c = 0; c < n; ++c) { 21 | if (r > 0 && dp[r-1][c] > 0) 22 | dp[r][c] = max(dp[r][c], dp[r-1][c] + grid[r][c]); 23 | if (c > 0 && dp[r][c-1] > 0) 24 | dp[r][c] = max(dp[r][c], dp[r][c-1] + grid[r][c]); 25 | } 26 | } 27 | return dp[m-1][n-1] > 0; 28 | } 29 | }; -------------------------------------------------------------------------------- /fibonacci-number/README.md: -------------------------------------------------------------------------------- 1 |

509. Fibonacci Number

Easy


The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,

2 | 3 |
F(0) = 0, F(1) = 1
 4 | F(n) = F(n - 1) + F(n - 2), for n > 1.
 5 | 
6 | 7 |

Given n, calculate F(n).

8 | 9 |

 

10 |

Example 1:

11 | 12 |
Input: n = 2
13 | Output: 1
14 | Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
15 | 
16 | 17 |

Example 2:

18 | 19 |
Input: n = 3
20 | Output: 2
21 | Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.
22 | 
23 | 24 |

Example 3:

25 | 26 |
Input: n = 4
27 | Output: 3
28 | Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.
29 | 
30 | 31 |

 

32 |

Constraints:

33 | 34 |
    35 |
  • 0 <= n <= 30
  • 36 |
37 |
-------------------------------------------------------------------------------- /fibonacci-number/fibonacci-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int fib(int n) { 4 | int first = 0, second = 1; 5 | if(n < 2) return n; 6 | int third = 0; 7 | for(int i = 2; i <= n; i++){ 8 | third = first + second; 9 | first = second; 10 | second = third; 11 | } 12 | return third; 13 | } 14 | }; -------------------------------------------------------------------------------- /find-all-anagrams-in-a-string/find-all-anagrams-in-a-string.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findAnagrams(string s, string p) { 4 | 5 | vector pv(26,0), sv(26,0), res; 6 | if(s.size() < p.size()) 7 | return res; 8 | 9 | for(int i = 0; i < p.size(); ++i) 10 | { 11 | ++pv[p[i]-'a']; 12 | ++sv[s[i]-'a']; 13 | } 14 | 15 | if(pv == sv) 16 | res.push_back(0); 17 | 18 | for(int i = p.size(); i < s.size(); ++i) 19 | { 20 | ++sv[s[i]-'a']; 21 | 22 | --sv[s[i-p.size()]-'a']; 23 | 24 | if(pv == sv) 25 | res.push_back(i-p.size()+1); 26 | } 27 | return res; 28 | } 29 | }; -------------------------------------------------------------------------------- /find-all-duplicates-in-an-array/README.md: -------------------------------------------------------------------------------- 1 |

442. Find All Duplicates in an Array

Medium


Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice.

2 | 3 |

You must write an algorithm that runs in O(n) time and uses only constant extra space.

4 | 5 |

 

6 |

Example 1:

7 |
Input: nums = [4,3,2,7,8,2,3,1]
 8 | Output: [2,3]
 9 | 

Example 2:

10 |
Input: nums = [1,1,2]
11 | Output: [1]
12 | 

Example 3:

13 |
Input: nums = [1]
14 | Output: []
15 | 
16 |

 

17 |

Constraints:

18 | 19 |
    20 |
  • n == nums.length
  • 21 |
  • 1 <= n <= 105
  • 22 |
  • 1 <= nums[i] <= n
  • 23 |
  • Each element in nums appears once or twice.
  • 24 |
25 |
-------------------------------------------------------------------------------- /find-all-duplicates-in-an-array/find-all-duplicates-in-an-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findDuplicates(vector& nums) { 4 | vector res; 5 | int n = nums.size(); 6 | for(int i=0; i 0) 9 | res.push_back(abs(nums[i])); 10 | } 11 | return res; 12 | } 13 | }; -------------------------------------------------------------------------------- /find-all-numbers-disappeared-in-an-array/README.md: -------------------------------------------------------------------------------- 1 |

448. Find All Numbers Disappeared in an Array

Easy


Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums.

2 | 3 |

 

4 |

Example 1:

5 |
Input: nums = [4,3,2,7,8,2,3,1]
 6 | Output: [5,6]
 7 | 

Example 2:

8 |
Input: nums = [1,1]
 9 | Output: [2]
10 | 
11 |

 

12 |

Constraints:

13 | 14 |
    15 |
  • n == nums.length
  • 16 |
  • 1 <= n <= 105
  • 17 |
  • 1 <= nums[i] <= n
  • 18 |
19 | 20 |

 

21 |

Follow up: Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

22 |
-------------------------------------------------------------------------------- /find-all-numbers-disappeared-in-an-array/find-all-numbers-disappeared-in-an-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findDisappearedNumbers(vector& nums) { 4 | int len = nums.size(); 5 | for(int i=0; i0 ? -nums[m] : nums[m]; 8 | } 9 | vector res; 10 | for(int i = 0; i 0) res.push_back(i+1); 12 | } 13 | return res; 14 | } 15 | }; -------------------------------------------------------------------------------- /find-first-and-last-position-of-element-in-sorted-array/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector searchRange(vector &nums, int target) 5 | { 6 | int x = bs(nums, target); 7 | int y = bs(nums, target + 1) - 1; 8 | if (x < nums.size() && nums[x] == target) 9 | return {x, y}; 10 | else 11 | return {-1, -1}; 12 | } 13 | 14 | int bs(vector nums, int target) 15 | { 16 | int lo = 0, hi = nums.size() - 1; 17 | 18 | while (lo <= hi) 19 | { 20 | int mid = (lo + hi) / 2; 21 | if (nums[mid] < target) 22 | { 23 | lo = mid + 1; 24 | } 25 | else 26 | hi = mid - 1; 27 | } 28 | return lo; 29 | } 30 | }; -------------------------------------------------------------------------------- /find-minimum-in-rotated-sorted-array/find-minimum-in-rotated-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMin(vector& nums) { 4 | int lo = 0; 5 | int hi = nums.size()-1; 6 | 7 | if (nums.size() == 1) { 8 | return nums[0]; 9 | } 10 | 11 | if(nums[hi] > nums[0]) return nums[0]; 12 | 13 | while(lo<=hi){ 14 | int mid = (lo+hi)/2; 15 | 16 | if(nums[mid]>nums[mid+1]) return nums[mid+1]; 17 | 18 | if(nums[mid-1]>nums[mid]){ 19 | return nums[mid]; 20 | } 21 | 22 | if(nums[mid] > nums[0]) lo = mid+1; 23 | else hi = mid-1; 24 | }return -1; 25 | } 26 | 27 | }; -------------------------------------------------------------------------------- /find-peak-element/find-peak-element.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findPeakElement(vector& nums) { 4 | int l = 0; 5 | int r = nums.size()-1; 6 | 7 | while(l nums[mid+1]) r = mid; 10 | else l = mid + 1; 11 | } 12 | return l; 13 | } 14 | }; -------------------------------------------------------------------------------- /findMedianSortedArrays.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double findMedianSortedArrays(vector& a, vector& b) { 4 | if (a.size() > b.size()) 5 | return findMedianSortedArrays(b, a); 6 | int m = a.size(), n = b.size(), req = (m + n + 1) / 2; 7 | int lo = 0, hi = m; 8 | while (lo <= hi) { 9 | int cut1 = lo + (hi - lo) / 2; 10 | int cut2 = req - cut1; 11 | int l1 = (cut1 == 0 ? INT_MIN : a[cut1 - 1]); 12 | int l2 = (cut2 == 0 ? INT_MIN : b[cut2 - 1]); 13 | int r1 = (cut1 == m ? INT_MAX: a[cut1]); 14 | int r2 = (cut2 == n ? INT_MAX : b[cut2]); 15 | if (l1 <= r2 and l2 <= r1) { 16 | if ((m + n) & 1) 17 | return max(l1, l2); 18 | else 19 | return ((double) max(l1, l2) + min(r1, r2)) / 2; 20 | } else if (l1 > r2) { 21 | hi = cut1 - 1; 22 | } else { 23 | lo = cut1 + 1; 24 | } 25 | } 26 | return -1; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /first-bad-version/first-bad-version.cpp: -------------------------------------------------------------------------------- 1 | // The API isBadVersion is defined for you. 2 | // bool isBadVersion(int version); 3 | 4 | class Solution { 5 | public: 6 | int firstBadVersion(int n) { 7 | 8 | long long l=0, r = n; 9 | 10 | long long mid; 11 | 12 | while(l<=r){ 13 | mid = (l+r)/2; 14 | 15 | if(isBadVersion(mid)){ 16 | r = mid-1; 17 | } 18 | else{ 19 | l = mid+1; 20 | } 21 | } 22 | return l; 23 | } 24 | }; -------------------------------------------------------------------------------- /first-missing-positive/README.md: -------------------------------------------------------------------------------- 1 |

41. First Missing Positive

Hard


Given an unsorted integer array nums, return the smallest missing positive integer.

2 | 3 |

You must implement an algorithm that runs in O(n) time and uses constant extra space.

4 | 5 |

 

6 |

Example 1:

7 |
Input: nums = [1,2,0]
 8 | Output: 3
 9 | 

Example 2:

10 |
Input: nums = [3,4,-1,1]
11 | Output: 2
12 | 

Example 3:

13 |
Input: nums = [7,8,9,11,12]
14 | Output: 1
15 | 
16 |

 

17 |

Constraints:

18 | 19 |
    20 |
  • 1 <= nums.length <= 5 * 105
  • 21 |
  • -231 <= nums[i] <= 231 - 1
  • 22 |
23 |
-------------------------------------------------------------------------------- /first-missing-positive/first-missing-positive.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int firstMissingPositive(vector& nums) { 4 | int n = nums.size(); 5 | 6 | for (int i = 0; i < n; i++) { 7 | if (nums[i] <= 0 || nums[i] > n) { 8 | nums[i] = n + 1; 9 | } 10 | } 11 | 12 | for (int i = 0; i < n; i++) { 13 | int num = abs(nums[i]); 14 | if (num > n) { 15 | continue; 16 | } 17 | num--; // -1 for zero index based array (so the number 1 will be at pos 0) 18 | if (nums[num] > 0) { // prevents double negative operations 19 | nums[num] = -1 * nums[num]; 20 | } 21 | } 22 | 23 | for (int i = 0; i < n; i++) { 24 | if (nums[i] >= 0) { 25 | return i + 1; 26 | } 27 | } 28 | return n + 1; 29 | } 30 | }; -------------------------------------------------------------------------------- /flatten-binary-tree-to-linked-list/flatten-binary-tree-to-linked-list.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | void flatten(TreeNode* root) { 15 | 16 | if(!root) return; 17 | flatten(root->left); 18 | flatten(root->right); 19 | 20 | TreeNode* temp = root->right; 21 | 22 | root->right = root->left; 23 | root->left = NULL; 24 | while(root->right){ 25 | root = root->right; 26 | } 27 | root->right = temp; 28 | 29 | return; 30 | } 31 | }; -------------------------------------------------------------------------------- /flip-binary-tree/flipbinarytree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | TreeNode* invertTree(TreeNode* root) { 4 | if(root==NULL) return root; 5 | swap(root->left,root->right); 6 | invertTree(root->left); 7 | invertTree(root->right); 8 | return root; 9 | } 10 | }; -------------------------------------------------------------------------------- /flood-fill/flood-fill.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | void dfslagao(vector>& image, int i, int j,int colour, int newColor){ 5 | 6 | if(i<0 || i>=image.size() || j<0 || j>=image[0].size() || image[i][j] != colour || image[i][j] == newColor) 7 | return; 8 | 9 | image[i][j] = newColor; 10 | dfslagao(image,i+1,j,colour,newColor); 11 | dfslagao(image,i,j+1,colour,newColor); 12 | dfslagao(image,i-1,j,colour,newColor); 13 | dfslagao(image,i,j-1,colour,newColor); 14 | 15 | } 16 | 17 | vector> floodFill(vector>& image, int sr, int sc, int newColor) { 18 | int sourceColour = image[sr][sc]; 19 | dfslagao(image,sr,sc,sourceColour,newColor); 20 | return image; 21 | } 22 | }; -------------------------------------------------------------------------------- /gas-station/gas-station.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int canCompleteCircuit(vector& gas, vector& cost) { 4 | int netFuel = 0; 5 | int n = gas.size(); 6 | 7 | for(int i=0; i22. Generate Parentheses

Medium


Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

2 | 3 |

 

4 |

Example 1:

5 |
Input: n = 3
 6 | Output: ["((()))","(()())","(())()","()(())","()()()"]
 7 | 

Example 2:

8 |
Input: n = 1
 9 | Output: ["()"]
10 | 
11 |

 

12 |

Constraints:

13 | 14 |
    15 |
  • 1 <= n <= 8
  • 16 |
17 |
-------------------------------------------------------------------------------- /generate-parentheses/generate-parentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | vector ans; 5 | 6 | void backtrack(string cur, int open, int close, int max){ 7 | 8 | if(cur.length() == max*2){ 9 | ans.push_back(cur); 10 | return; 11 | } 12 | 13 | if(open < max){ 14 | backtrack(cur + "(", open+1, close, max); 15 | } 16 | 17 | if(close < open){ 18 | backtrack(cur+ ")", open, close+1, max); 19 | } 20 | 21 | } 22 | 23 | vector generateParenthesis(int n) { 24 | 25 | backtrack("",0,0,n); 26 | return ans; 27 | 28 | } 29 | 30 | 31 | }; -------------------------------------------------------------------------------- /group-anagrams/README.md: -------------------------------------------------------------------------------- 1 |

49. Group Anagrams

Medium


Given an array of strings strs, group the anagrams together. You can return the answer in any order.

2 | 3 |

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

4 | 5 |

 

6 |

Example 1:

7 |
Input: strs = ["eat","tea","tan","ate","nat","bat"]
 8 | Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
 9 | 

Example 2:

10 |
Input: strs = [""]
11 | Output: [[""]]
12 | 

Example 3:

13 |
Input: strs = ["a"]
14 | Output: [["a"]]
15 | 
16 |

 

17 |

Constraints:

18 | 19 |
    20 |
  • 1 <= strs.length <= 104
  • 21 |
  • 0 <= strs[i].length <= 100
  • 22 |
  • strs[i] consists of lower-case English letters.
  • 23 |
24 |
-------------------------------------------------------------------------------- /group-anagrams/group-anagrams.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> groupAnagrams(vector& strs) { 4 | unordered_map> mp; 5 | for (string s : strs) { 6 | mp[strSort(s)].push_back(s); 7 | } 8 | vector> anagrams; 9 | for (auto p : mp) { 10 | anagrams.push_back(p.second); 11 | } 12 | return anagrams; 13 | } 14 | private: 15 | string strSort(string s) { 16 | int counter[26] = {0}; 17 | for (char c : s) { 18 | counter[c - 'a']++; 19 | } 20 | string t; 21 | for (int c = 0; c < 26; c++) { 22 | t += string(counter[c], c + 'a'); 23 | } 24 | return t; 25 | } 26 | }; -------------------------------------------------------------------------------- /heaters/heaters.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findRadius(vector& houses, vector& heaters) { 4 | sort(heaters.begin(), heaters.end()); 5 | int minRadius = 0; 6 | 7 | for (int i = 0; i < houses.size(); i++) { 8 | 9 | auto larger = lower_bound(heaters.begin(), heaters.end(), houses[i]); 10 | int curRadius = INT_MAX; 11 | 12 | if (larger != heaters.end()) 13 | curRadius = *larger - houses[i]; 14 | 15 | if (larger != heaters.begin()) { 16 | auto smaller = larger - 1; 17 | curRadius = min(curRadius, houses[i] - *smaller); 18 | } 19 | minRadius = max(minRadius, curRadius); 20 | } 21 | return minRadius; 22 | } 23 | }; -------------------------------------------------------------------------------- /house-robber-ii/house-robber-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | unordered_map um; 5 | 6 | int rob(vector &nums) 7 | { 8 | int n = nums.size(); 9 | int v1 = nums[0] + solve(nums, 1, true, true); 10 | int v2 = solve(nums, 1, false, false); 11 | 12 | return max(v1, v2); 13 | } 14 | 15 | int solve(vector &nums, int n, bool prevrob, bool firstrob) 16 | { 17 | 18 | string key = to_string(n) + '_' + to_string(prevrob) + '_' + to_string(firstrob); 19 | 20 | if (n == nums.size()) 21 | return 0; 22 | 23 | if (n == nums.size() - 1 && firstrob) 24 | return 0; 25 | 26 | if (um.find(key) != um.end()) 27 | return um[key]; 28 | 29 | if (prevrob) 30 | { 31 | return um[key] = solve(nums, n + 1, false, firstrob); 32 | } 33 | else 34 | return um[key] = max(nums[n] + solve(nums, n + 1, true, firstrob), solve(nums, n + 1, false, firstrob)); 35 | } 36 | }; -------------------------------------------------------------------------------- /house-robber-iii/house-robber-iii.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | 15 | 16 | //Pair -> 17 | pair helper(TreeNode* root){ 18 | 19 | if(root == NULL){ 20 | return {0,0}; 21 | } 22 | 23 | pair left = helper(root->left); 24 | pair right = helper(root->right); 25 | 26 | return {left.second + right.second + root->val, max(left.first, left.second) + max(right.second, right.first)}; 27 | } 28 | 29 | int rob(TreeNode* root) { 30 | pair ans = helper(root); 31 | return max(ans.first, ans.second); 32 | } 33 | }; -------------------------------------------------------------------------------- /house-robber/House Robber.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int rob(vector& nums) { 4 | int n = nums.size(); 5 | if(n==1){ 6 | return nums[0]; 7 | }else if(n==2){ 8 | return max(nums[0],nums[1]); 9 | } 10 | nums[1] = max(nums[1],nums[0]); 11 | for(int i=2;i& nums, int n, vector& ans){ 5 | 6 | if(n<0){ 7 | return 0; 8 | } 9 | 10 | if(ans[n]!=INT_MAX) return ans[n]; 11 | 12 | ans[n] = max(nums[n]+helper(nums,n-2,ans), helper(nums,n-1,ans)); 13 | 14 | return ans[n]; 15 | } 16 | 17 | int rob(vector& nums) { 18 | int n = nums.size(); 19 | vector ans(n+1,INT_MIN); 20 | 21 | if(n<1) return 0; 22 | 23 | ans[0] = 0; 24 | ans[1] = nums[0]; 25 | 26 | for(int i=2; i<=n; i++){ 27 | ans[i] = max(nums[i-1]+ans[i-2], ans[i-1]); 28 | } 29 | 30 | return ans[n]; 31 | } 32 | }; -------------------------------------------------------------------------------- /insert-interval/insert-interval.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> insert(vector>& intervals, vector& newInterval) { 4 | 5 | vector> res; 6 | 7 | int i = 0, n = intervals.size(); 8 | 9 | // Insert left Non overlapping intervals 10 | while(i < n && intervals[i][1] < newInterval[0]){ 11 | res.push_back(intervals[i]); 12 | i++; 13 | } 14 | 15 | // Merge intervals 16 | while(i < n && intervals[i][0] <= newInterval[1]){ 17 | newInterval[0] = min(newInterval[0], intervals[i][0]); 18 | newInterval[1] = max(newInterval[1], intervals[i][1]); 19 | i++; 20 | } 21 | res.push_back(newInterval); 22 | 23 | // Insert right Non overlapping intervals 24 | while (i < n && intervals[i][0] > newInterval[1]) { 25 | res.push_back(intervals[i]); 26 | ++i; 27 | } 28 | return res; 29 | } 30 | }; -------------------------------------------------------------------------------- /integer-break/README.md: -------------------------------------------------------------------------------- 1 |

343. Integer Break

Medium


Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers.

2 | 3 |

Return the maximum product you can get.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
Input: n = 2
 9 | Output: 1
10 | Explanation: 2 = 1 + 1, 1 × 1 = 1.
11 | 
12 | 13 |

Example 2:

14 | 15 |
Input: n = 10
16 | Output: 36
17 | Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.
18 | 
19 | 20 |

 

21 |

Constraints:

22 | 23 |
    24 |
  • 2 <= n <= 58
  • 25 |
26 |
-------------------------------------------------------------------------------- /integer-break/integer-break.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int integerBreak(int n) { 4 | if (n <= 2) 5 | return 1; 6 | 7 | vector maxArr(n+1, 0); 8 | 9 | maxArr[1] = 0; 10 | maxArr[2] = 1; 11 | 12 | for (int i=3; i<=n; i++) { 13 | for (int j=1; j> intervalIntersection(vector> &firstList, vector> &secondList) 5 | { 6 | vector> ans; 7 | int i = 0, j = 0; 8 | while (i < firstList.size() && j < secondList.size()) 9 | { 10 | int lo = max(firstList[i][0], secondList[j][0]); 11 | int hi = min(firstList[i][1], secondList[j][1]); 12 | if (lo <= hi) 13 | { 14 | ans.push_back({lo, hi}); 15 | } 16 | if (firstList[i][1] < secondList[j][1]) 17 | { 18 | i++; 19 | } 20 | else 21 | j++; 22 | } 23 | return ans; 24 | } 25 | }; -------------------------------------------------------------------------------- /invert-binary-tree/README.md: -------------------------------------------------------------------------------- 1 |

226. Invert Binary Tree

Easy


Given the root of a binary tree, invert the tree, and return its root.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
Input: root = [4,2,7,1,3,6,9]
 7 | Output: [4,7,2,9,6,3,1]
 8 | 
9 | 10 |

Example 2:

11 | 12 |
Input: root = [2,1,3]
13 | Output: [2,3,1]
14 | 
15 | 16 |

Example 3:

17 | 18 |
Input: root = []
19 | Output: []
20 | 
21 | 22 |

 

23 |

Constraints:

24 | 25 |
    26 |
  • The number of nodes in the tree is in the range [0, 100].
  • 27 |
  • -100 <= Node.val <= 100
  • 28 |
29 |
-------------------------------------------------------------------------------- /invert-binary-tree/invert-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | TreeNode* invertTree(TreeNode* root) { 15 | if(!root) return NULL; 16 | 17 | 18 | TreeNode* left = invertTree(root->left); 19 | TreeNode* right = invertTree(root->right); 20 | root->right = left; 21 | root->left = right; 22 | 23 | return root; 24 | 25 | } 26 | }; -------------------------------------------------------------------------------- /is-graph-bipartite/is-graph-bipartite.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | bool helper(vector> &graph, int node, vector &visited, int parent, int color){ 5 | 6 | if(visited[node]) return color == visited[node]; 7 | 8 | visited[node] = color; 9 | 10 | for(auto nbr: graph[node]){ 11 | 12 | // if(!visited[node]){ 13 | if(!helper(graph,nbr,visited,node,3-color)) return false; 14 | // } 15 | 16 | // else if(nbr!=parent && color==visited[nbr]) return false; 17 | 18 | } 19 | return true; 20 | } 21 | 22 | 23 | bool dfs(vector> &graph){ 24 | 25 | vector visited(graph.size(),0); 26 | 27 | int color = 1; 28 | 29 | for(int i=0; i>& graph) { 39 | return dfs(graph); 40 | } 41 | }; -------------------------------------------------------------------------------- /is-subsequence/is_subsequence.cpp: -------------------------------------------------------------------------------- 1 | bool isSubsequence(string s, string t) { 2 | int i=0,j=0; 3 | while(j>& grid) { 4 | int perimeter = 0; 5 | 6 | for(int i=0; i= 0 && grid[i-1][j] == 1) s++; 11 | if(i+1 < grid.size() && grid[i+1][j] == 1) s++; 12 | if(j-1 >= 0 && grid[i][j-1] == 1) s++; 13 | if(j+1 < grid[i].size() && grid[i][j+1] == 1) s++; 14 | perimeter+=(4-s); 15 | } 16 | } 17 | } 18 | return perimeter; 19 | } 20 | }; -------------------------------------------------------------------------------- /jump-game-ii/README.md: -------------------------------------------------------------------------------- 1 |

45. Jump Game II

Medium


Given an array of non-negative integers nums, you are initially positioned at the first index of the array.

2 | 3 |

Each element in the array represents your maximum jump length at that position.

4 | 5 |

Your goal is to reach the last index in the minimum number of jumps.

6 | 7 |

You can assume that you can always reach the last index.

8 | 9 |

 

10 |

Example 1:

11 | 12 |
Input: nums = [2,3,1,1,4]
13 | Output: 2
14 | Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.
15 | 
16 | 17 |

Example 2:

18 | 19 |
Input: nums = [2,3,0,1,4]
20 | Output: 2
21 | 
22 | 23 |

 

24 |

Constraints:

25 | 26 |
    27 |
  • 1 <= nums.length <= 104
  • 28 |
  • 0 <= nums[i] <= 1000
  • 29 |
30 |
-------------------------------------------------------------------------------- /jump-game-ii/jump-game-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int helper(vector& nums, vector& dp, int pos){ 5 | 6 | if(pos>=(int)nums.size()-1) return 0; 7 | 8 | if(dp[pos] != 10000) return dp[pos]; 9 | 10 | for(int i=1; i<=nums[pos]; i++){ 11 | dp[pos] = min(dp[pos],1+helper(nums,dp,pos+i)); 12 | } 13 | return dp[pos]; 14 | } 15 | 16 | int jump(vector& nums) { 17 | vector dp(size(nums), 10000); 18 | return helper(nums, dp, 0); 19 | } 20 | }; -------------------------------------------------------------------------------- /jump-game/README.md: -------------------------------------------------------------------------------- 1 |

55. Jump Game

Medium


You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.

2 | 3 |

Return true if you can reach the last index, or false otherwise.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
Input: nums = [2,3,1,1,4]
 9 | Output: true
10 | Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
11 | 
12 | 13 |

Example 2:

14 | 15 |
Input: nums = [3,2,1,0,4]
16 | Output: false
17 | Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
18 | 
19 | 20 |

 

21 |

Constraints:

22 | 23 |
    24 |
  • 1 <= nums.length <= 104
  • 25 |
  • 0 <= nums[i] <= 105
  • 26 |
27 |
-------------------------------------------------------------------------------- /jump-game/jump-game.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canJump(vector& nums) { 4 | int n = nums.size(); 5 | 6 | int reachable = 0; 7 | 8 | for(int i=0; ireachable){ 10 | return false; 11 | } 12 | reachable = max(reachable, i+nums[i]); 13 | } 14 | return true; 15 | } 16 | }; -------------------------------------------------------------------------------- /koko-eating-bananas/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int minEatingSpeed(vectorpiles, int h) { 5 | int n = piles.size(); 6 | if(n == 1) 7 | return ceil(((double)piles[0]) / ((double)h)); 8 | 9 | sort(piles.begin(),piles.end()); 10 | int r = 1000000000; 11 | int l = 1,ans; 12 | while(l<=r) 13 | { 14 | int mid = (l+r)/2; 15 | 16 | int c=0; 17 | for(int i=0;ipiles; 31 | int h,n; 32 | cin>>n; 33 | for(int i=0;i>x; 37 | piles.push_back(x); 38 | } 39 | cin>>h; 40 | cout<left,k); 22 | i++; 23 | if(i==k){ 24 | ans = root->val; 25 | } 26 | helper(root->right,k); 27 | 28 | } 29 | 30 | int kthSmallest(TreeNode* root, int k) { 31 | 32 | helper(root,k); 33 | return ans; 34 | } 35 | }; -------------------------------------------------------------------------------- /largest-rectangle-in-histogram/README.md: -------------------------------------------------------------------------------- 1 |

84. Largest Rectangle in Histogram

Hard


Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
Input: heights = [2,1,5,6,2,3]
 7 | Output: 10
 8 | Explanation: The above is a histogram where width of each bar is 1.
 9 | The largest rectangle is shown in the red area, which has an area = 10 units.
10 | 
11 | 12 |

Example 2:

13 | 14 |
Input: heights = [2,4]
15 | Output: 4
16 | 
17 | 18 |

 

19 |

Constraints:

20 | 21 |
    22 |
  • 1 <= heights.length <= 105
  • 23 |
  • 0 <= heights[i] <= 104
  • 24 |
25 |
-------------------------------------------------------------------------------- /letter-case-permutation/README.md: -------------------------------------------------------------------------------- 1 |

784. Letter Case Permutation

Medium


Given a string s, we can transform every letter individually to be lowercase or uppercase to create another string.

2 | 3 |

Return a list of all possible strings we could create. You can return the output in any order.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
Input: s = "a1b2"
 9 | Output: ["a1b2","a1B2","A1b2","A1B2"]
10 | 
11 | 12 |

Example 2:

13 | 14 |
Input: s = "3z4"
15 | Output: ["3z4","3Z4"]
16 | 
17 | 18 |

Example 3:

19 | 20 |
Input: s = "12345"
21 | Output: ["12345"]
22 | 
23 | 24 |

Example 4:

25 | 26 |
Input: s = "0"
27 | Output: ["0"]
28 | 
29 | 30 |

 

31 |

Constraints:

32 | 33 |
    34 |
  • s will be a string with length between 1 and 12.
  • 35 |
  • s will consist only of letters or digits.
  • 36 |
37 |
-------------------------------------------------------------------------------- /letter-case-permutation/letter-case-permutation.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | vector ans; 5 | string temp = ""; 6 | 7 | bool isAlphabet(char c){ 8 | return (c>='a' && c<='z')||(c>='A'&&c<='Z'); 9 | } 10 | 11 | void helper(string s, int i, int n){ 12 | 13 | if(i == n){ 14 | ans.push_back(temp); 15 | return; 16 | } 17 | 18 | if(isAlphabet(s[i])){ 19 | 20 | temp+=tolower(s[i]); 21 | helper(s,i+1,n); 22 | temp.pop_back(); 23 | temp+=toupper(s[i]); 24 | helper(s,i+1,n); 25 | temp.pop_back(); 26 | } 27 | else{ 28 | 29 | temp+=s[i]; 30 | helper(s,i+1,n); 31 | temp.pop_back(); 32 | } 33 | 34 | } 35 | 36 | vector letterCasePermutation(string s) { 37 | 38 | int n = s.length(); 39 | 40 | if(n == 0) return ans; 41 | helper(s, 0, n); 42 | 43 | return ans; 44 | } 45 | }; -------------------------------------------------------------------------------- /linked-list-cycle/linked-list-cycle.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution 10 | { 11 | public: 12 | bool hasCycle(ListNode *head) 13 | { 14 | 15 | ListNode *slow = head; 16 | ListNode *fast = head; 17 | 18 | while (fast && fast->next) 19 | { 20 | slow = slow->next; 21 | fast = fast->next->next; 22 | if (slow == fast) 23 | { 24 | return true; 25 | } 26 | } 27 | 28 | return false; 29 | } 30 | }; -------------------------------------------------------------------------------- /longest-common-subsequence/longest-common-subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestCommonSubsequence(string text1, string text2) { 4 | int m = text1.length(); 5 | int n = text2.length(); 6 | 7 | int dp[m+1][n+1]; 8 | 9 | for(int i=0; i<=m; i++){ 10 | for(int j=0; j<=n; j++){ 11 | if(i==0 || j==0){ 12 | dp[i][j] = 0; 13 | } 14 | else{ 15 | if(text1[i-1] == text2[j-1]){ 16 | dp[i][j] = 1+dp[i-1][j-1]; 17 | } 18 | else{ 19 | dp[i][j] = max(dp[i-1][j],dp[i][j-1]); 20 | } 21 | } 22 | } 23 | } 24 | return dp[m][n]; 25 | } 26 | }; -------------------------------------------------------------------------------- /longest-increasing-subsequence/lis.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLIS(vector& nums) { 4 | int n=nums.size(); 5 | if(n==1) return 1; 6 | vector dp(n+1); 7 | dp[0]=INT_MIN; 8 | for(int i=1;i<=n;i++) dp[i]=INT_MAX; 9 | for(int i=0;i516. Longest Palindromic Subsequence

Medium


Given a string s, find the longest palindromic subsequence's length in s.

2 | 3 |

A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
Input: s = "bbbab"
 9 | Output: 4
10 | Explanation: One possible longest palindromic subsequence is "bbbb".
11 | 
12 | 13 |

Example 2:

14 | 15 |
Input: s = "cbbd"
16 | Output: 2
17 | Explanation: One possible longest palindromic subsequence is "bb".
18 | 
19 | 20 |

 

21 |

Constraints:

22 | 23 |
    24 |
  • 1 <= s.length <= 1000
  • 25 |
  • s consists only of lowercase English letters.
  • 26 |
27 |
-------------------------------------------------------------------------------- /longest-palindromic-subsequence/longest-palindromic-subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int lcs(string a, string b){ 5 | 6 | int n = a.size(); 7 | 8 | int dp[n+1][n+1]; 9 | 10 | for(int i=0; i<=n; i++){ 11 | for(int j=0; j<=n; j++){ 12 | if(i == 0 || j == 0){ 13 | dp[i][j] = 0; 14 | } 15 | else if(a[i-1] == b[j-1]){ 16 | dp[i][j] = dp[i-1][j-1]+1; 17 | } 18 | else{ 19 | dp[i][j] = max(dp[i-1][j],dp[i][j-1]); 20 | } 21 | } 22 | } 23 | return dp[n][n]; 24 | } 25 | 26 | int longestPalindromeSubseq(string s) { 27 | 28 | string s1 = s; 29 | 30 | reverse(s.begin(),s.end()); 31 | return lcs(s,s1); 32 | 33 | } 34 | }; -------------------------------------------------------------------------------- /longest-palindromic-substring/README.md: -------------------------------------------------------------------------------- 1 |

5. Longest Palindromic Substring

Medium


Given a string s, return the longest palindromic substring in s.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
Input: s = "babad"
 7 | Output: "bab"
 8 | Note: "aba" is also a valid answer.
 9 | 
10 | 11 |

Example 2:

12 | 13 |
Input: s = "cbbd"
14 | Output: "bb"
15 | 
16 | 17 |

Example 3:

18 | 19 |
Input: s = "a"
20 | Output: "a"
21 | 
22 | 23 |

Example 4:

24 | 25 |
Input: s = "ac"
26 | Output: "a"
27 | 
28 | 29 |

 

30 |

Constraints:

31 | 32 |
    33 |
  • 1 <= s.length <= 1000
  • 34 |
  • s consist of only digits and English letters.
  • 35 |
36 |
-------------------------------------------------------------------------------- /longest-palindromic-substring/longest-palindromic-substring.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | string ans=""; 5 | 6 | string solve(string &s, int i, int j){ 7 | 8 | string temp = ""; 9 | 10 | if(i==j) return temp+s[i]; 11 | 12 | if(s[i] == s[j]){ 13 | string temp = s[i]+solve(s,i+1,j-1)+s[i]; 14 | ans = ans.length()>=temp.length() ? ans:temp; 15 | return temp; 16 | } 17 | 18 | else{ 19 | return ""; 20 | } 21 | 22 | } 23 | 24 | string longestPalindrome(string s) 25 | { 26 | if (s.empty()) return ""; 27 | if (s.size() == 1) return s; 28 | int min_start = 0, max_len = 1; 29 | for (int i = 0; i < s.size();) { 30 | if (s.size() - i <= max_len / 2) break; 31 | int j = i, k = i; 32 | while (k < s.size()-1 && s[k+1] == s[k]) ++k; // Skip duplicate characters. 33 | i = k+1; 34 | while (k < s.size()-1 && j > 0 && s[k + 1] == s[j - 1]) { ++k; --j; } // Expand. 35 | int new_len = k - j + 1; 36 | if (new_len > max_len) { min_start = j; max_len = new_len; } 37 | } 38 | return s.substr(min_start, max_len); 39 | } 40 | 41 | }; -------------------------------------------------------------------------------- /longest-substring-without-repeating-characters/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLongestSubstring(string s) { 4 | vector last(256,-1); 5 | 6 | int maxLen = 0; 7 | int start = -1; 8 | 9 | for(int i=0; i != (int)s.length(); i++){ 10 | if(last[s[i]] > start){ 11 | start = last[s[i]]; 12 | } 13 | last[s[i]] = i; 14 | maxLen = max(maxLen, i-start); 15 | } 16 | return maxLen; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /majority-element/README.md: -------------------------------------------------------------------------------- 1 |

169. Majority Element

Easy


Given an array nums of size n, return the majority element.

2 | 3 |

The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.

4 | 5 |

 

6 |

Example 1:

7 |
Input: nums = [3,2,3]
 8 | Output: 3
 9 | 

Example 2:

10 |
Input: nums = [2,2,1,1,1,2,2]
11 | Output: 2
12 | 
13 |

 

14 |

Constraints:

15 | 16 |
    17 |
  • n == nums.length
  • 18 |
  • 1 <= n <= 5 * 104
  • 19 |
  • -231 <= nums[i] <= 231 - 1
  • 20 |
21 | 22 |

 

23 | Follow-up: Could you solve the problem in linear time and in O(1) space?
-------------------------------------------------------------------------------- /majority-element/majority-element.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int majorityElement(vector& nums) { 4 | 5 | int n = nums.size(); 6 | sort(nums.begin(), nums.end()); 7 | 8 | return nums[n/2]; 9 | } 10 | }; -------------------------------------------------------------------------------- /majority-element/majority_element_another_approach.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int majorityElement(vector& nums) { 4 | sort(nums.begin(),nums.end()); 5 | int i,count=1,ans=nums[0]; 6 | for(i=0;i(nums.size()/2)) 17 | { 18 | ans=nums[i]; 19 | break; 20 | } 21 | } 22 | return ans; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /map-sum-pairs/map-sum-pairs.cpp: -------------------------------------------------------------------------------- 1 | class MapSum { 2 | public: 3 | /** Initialize your data structure here. */ 4 | map count; 5 | MapSum() { 6 | 7 | } 8 | 9 | void insert(string key, int val) { 10 | count[key] = val; 11 | } 12 | 13 | int sum(string prefix) { 14 | int answer = 0; 15 | for(map::iterator i = count.begin(); i != count.end(); i++) 16 | { 17 | if(i->first.find(prefix) == 0) 18 | answer += i->second; 19 | } 20 | return answer; 21 | } 22 | }; 23 | 24 | /** 25 | * Your MapSum object will be instantiated and called as such: 26 | * MapSum* obj = new MapSum(); 27 | * obj->insert(key,val); 28 | * int param_2 = obj->sum(prefix); 29 | */ -------------------------------------------------------------------------------- /matrix-block-sum/README.md: -------------------------------------------------------------------------------- 1 |

1314. Matrix Block Sum

Medium


Given a m x n matrix mat and an integer k, return a matrix answer where each answer[i][j] is the sum of all elements mat[r][c] for:

2 | 3 |
    4 |
  • i - k <= r <= i + k,
  • 5 |
  • j - k <= c <= j + k, and
  • 6 |
  • (r, c) is a valid position in the matrix.
  • 7 |
8 | 9 |

 

10 |

Example 1:

11 | 12 |
Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 1
13 | Output: [[12,21,16],[27,45,33],[24,39,28]]
14 | 
15 | 16 |

Example 2:

17 | 18 |
Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 2
19 | Output: [[45,45,45],[45,45,45],[45,45,45]]
20 | 
21 | 22 |

 

23 |

Constraints:

24 | 25 |
    26 |
  • m == mat.length
  • 27 |
  • n == mat[i].length
  • 28 |
  • 1 <= m, n, k <= 100
  • 29 |
  • 1 <= mat[i][j] <= 100
  • 30 |
31 |
-------------------------------------------------------------------------------- /max-area-of-island/max-area-of-island.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int dfs(vector>& grid,vector>& visited, int i, int j){ 5 | if(i<0 || j<0 || i>=grid.size() || j>=grid[0].size() || visited[i][j] || grid[i][j] == 0) 6 | return 0; 7 | visited[i][j] = true; 8 | return dfs(grid,visited,i+1,j) + dfs(grid,visited,i,j+1) + dfs(grid,visited,i-1,j) + dfs(grid,visited,i,j-1)+1; 9 | } 10 | 11 | int maxAreaOfIsland(vector>& grid) { 12 | int ans = 0; 13 | vector> visited(grid.size(), vector (grid[0].size(),false)); 14 | 15 | for(int i=0; i& nums) { 4 | int max_sum=nums[0], sum=nums[0]; 5 | for(int i=1; imax_sum) { 8 | max_sum=sum; 9 | } 10 | } 11 | 12 | return max_sum; 13 | } 14 | }; -------------------------------------------------------------------------------- /maximal-square/maximal-square.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maximalSquare(vector>& matrix) { 4 | if (matrix.empty()) { 5 | return 0; 6 | } 7 | int m = matrix.size(), n = matrix[0].size(), sz = 0; 8 | vector> dp(m, vector(n, 0)); 9 | for (int i = 0; i < m; i++) { 10 | for (int j = 0; j < n; j++) { 11 | if (!i || !j || matrix[i][j] == '0') { 12 | dp[i][j] = matrix[i][j] - '0'; 13 | } else { 14 | dp[i][j] = min(dp[i - 1][j - 1], min(dp[i - 1][j], dp[i][j - 1])) + 1; 15 | } 16 | sz = max(dp[i][j], sz); 17 | } 18 | } 19 | return sz * sz; 20 | } 21 | }; -------------------------------------------------------------------------------- /maximum-length-of-subarray-with-positive-product/maximum-length-of-subarray-with-positive-product.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int getMaxLen(vector& nums) { 4 | int positive = 0, negative = 0; // length of positive and negative results 5 | int ans = 0; 6 | for(int x : nums) { 7 | if(x == 0) { 8 | positive = 0; 9 | negative = 0; 10 | } 11 | else if(x > 0) { 12 | positive++; 13 | negative = negative == 0 ? 0 : negative+1; 14 | } 15 | else { 16 | int temp = positive; 17 | positive = negative == 0 ? 0 : negative+1; 18 | negative = temp+1; 19 | } 20 | ans = max(ans, positive); 21 | } 22 | return ans; 23 | } 24 | }; -------------------------------------------------------------------------------- /maximum-product-subarray/README.md: -------------------------------------------------------------------------------- 1 |

152. Maximum Product Subarray

Medium


Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product.

2 | 3 |

It is guaranteed that the answer will fit in a 32-bit integer.

4 | 5 |

A subarray is a contiguous subsequence of the array.

6 | 7 |

 

8 |

Example 1:

9 | 10 |
Input: nums = [2,3,-2,4]
11 | Output: 6
12 | Explanation: [2,3] has the largest product 6.
13 | 
14 | 15 |

Example 2:

16 | 17 |
Input: nums = [-2,0,-1]
18 | Output: 0
19 | Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
20 | 
21 | 22 |

 

23 |

Constraints:

24 | 25 |
    26 |
  • 1 <= nums.length <= 2 * 104
  • 27 |
  • -10 <= nums[i] <= 10
  • 28 |
  • The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
  • 29 |
30 |
-------------------------------------------------------------------------------- /maximum-product-subarray/maximum-product-subarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProduct(vector& nums) { 4 | 5 | int n = nums.size(); 6 | 7 | if(n==0) return 0; 8 | 9 | int ans = INT_MIN; 10 | 11 | int minProd = 1; 12 | int maxProd = 1; 13 | 14 | for(int num: nums){ 15 | 16 | if(num<0){ 17 | swap(maxProd,minProd); 18 | } 19 | 20 | maxProd = max(maxProd*num, num); 21 | minProd = min(minProd*num, num); 22 | 23 | ans = max(ans,maxProd); 24 | 25 | } 26 | return ans; 27 | } 28 | }; -------------------------------------------------------------------------------- /maximum-subarray/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | int maxSubArray(vector &nums) 5 | { 6 | int n = nums.size(); 7 | int dp[n]; 8 | dp[0] = nums[0]; 9 | int res = dp[0]; 10 | for (int i = 1; i < n; i++) 11 | { 12 | dp[i] = nums[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0); 13 | res = max(res, dp[i]); 14 | } 15 | return res; 16 | } 17 | }; -------------------------------------------------------------------------------- /maximum-sum-circular-subarray/maximum-sum-circular-subarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxSubarraySumCircular(vector& nums) { 4 | 5 | int sum=0; 6 | for(int x: nums) sum+=x; 7 | 8 | int ans1 = INT_MIN; 9 | int cur = INT_MIN; 10 | 11 | for(int x: nums){ 12 | cur = x + max(cur,0); 13 | ans1 = max(ans1, cur); 14 | } 15 | 16 | int ans2 = INT_MAX; 17 | cur = INT_MAX; 18 | 19 | for(int i = 1; i < nums.size(); ++i){ 20 | cur = nums[i] + min(cur,0); 21 | ans2 = min(ans2, cur); 22 | } 23 | if(ans2 == INT_MAX) ans2 = INT_MIN; 24 | else ans2 = sum-ans2; 25 | 26 | 27 | int ans3 = INT_MAX; 28 | cur = INT_MAX; 29 | 30 | for(int i = 0; i < nums.size()-1; ++i){ 31 | cur = nums[i] + min(cur,0); 32 | ans3 = min(ans3, cur); 33 | } 34 | 35 | if(ans3 = INT_MAX) ans3 = INT_MIN; 36 | 37 | return max(ans1, max(ans2,ans3)); 38 | } 39 | }; -------------------------------------------------------------------------------- /merge-k-sorted-lists/merge-k-sorted-lists.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | struct compare { 14 | bool operator()(const ListNode* l, const ListNode* r) { 15 | return l->val > r->val; 16 | } 17 | }; 18 | ListNode *mergeKLists(vector &lists) { //priority_queue 19 | priority_queue, compare> q; 20 | for(auto l : lists) { 21 | if(l) q.push(l); 22 | } 23 | if(q.empty()) return NULL; 24 | 25 | ListNode* result = q.top(); 26 | q.pop(); 27 | if(result->next) q.push(result->next); 28 | ListNode* tail = result; 29 | while(!q.empty()) { 30 | tail->next = q.top(); 31 | q.pop(); 32 | tail = tail->next; 33 | if(tail->next) q.push(tail->next); 34 | } 35 | return result; 36 | } 37 | }; 38 | 39 | -------------------------------------------------------------------------------- /merge-two-sorted-lists/README.md: -------------------------------------------------------------------------------- 1 |

21. Merge Two Sorted Lists

Easy


Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
Input: l1 = [1,2,4], l2 = [1,3,4]
 7 | Output: [1,1,2,3,4,4]
 8 | 
9 | 10 |

Example 2:

11 | 12 |
Input: l1 = [], l2 = []
13 | Output: []
14 | 
15 | 16 |

Example 3:

17 | 18 |
Input: l1 = [], l2 = [0]
19 | Output: [0]
20 | 
21 | 22 |

 

23 |

Constraints:

24 | 25 |
    26 |
  • The number of nodes in both lists is in the range [0, 50].
  • 27 |
  • -100 <= Node.val <= 100
  • 28 |
  • Both l1 and l2 are sorted in non-decreasing order.
  • 29 |
30 |
-------------------------------------------------------------------------------- /middle-of-the-linked-list/README.md: -------------------------------------------------------------------------------- 1 |

876. Middle of the Linked List

Easy


Given the head of a singly linked list, return the middle node of the linked list.

2 | 3 |

If there are two middle nodes, return the second middle node.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
Input: head = [1,2,3,4,5]
 9 | Output: [3,4,5]
10 | Explanation: The middle node of the list is node 3.
11 | 
12 | 13 |

Example 2:

14 | 15 |
Input: head = [1,2,3,4,5,6]
16 | Output: [4,5,6]
17 | Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.
18 | 
19 | 20 |

 

21 |

Constraints:

22 | 23 |
    24 |
  • The number of nodes in the list is in the range [1, 100].
  • 25 |
  • 1 <= Node.val <= 100
  • 26 |
27 |
-------------------------------------------------------------------------------- /middle-of-the-linked-list/middle-of-the-linked-list.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* middleNode(ListNode* head) { 14 | ListNode* slow = head; 15 | ListNode* fast = head; 16 | while(fast != NULL && fast->next != NULL){ 17 | slow = slow->next; 18 | fast = fast->next->next; 19 | } 20 | return slow; 21 | } 22 | }; -------------------------------------------------------------------------------- /min-cost-climbing-stairs/README.md: -------------------------------------------------------------------------------- 1 |

746. Min Cost Climbing Stairs

Easy


You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps.

2 | 3 |

You can either start from the step with index 0, or the step with index 1.

4 | 5 |

Return the minimum cost to reach the top of the floor.

6 | 7 |

 

8 |

Example 1:

9 | 10 |
Input: cost = [10,15,20]
11 | Output: 15
12 | Explanation: Cheapest is: start on cost[1], pay that cost, and go to the top.
13 | 
14 | 15 |

Example 2:

16 | 17 |
Input: cost = [1,100,1,1,1,100,1,1,100,1]
18 | Output: 6
19 | Explanation: Cheapest is: start on cost[0], and only step on 1s, skipping cost[3].
20 | 
21 | 22 |

 

23 |

Constraints:

24 | 25 |
    26 |
  • 2 <= cost.length <= 1000
  • 27 |
  • 0 <= cost[i] <= 999
  • 28 |
29 |
-------------------------------------------------------------------------------- /min-cost-climbing-stairs/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minCostClimbingStairs(vector& cost) { 4 | int n = cost.size(); 5 | vector dp(n + 1); 6 | for (int i = 2; i <= n; i++) { 7 | int jumpOneStep = dp[i - 1] + cost[i - 1]; 8 | int jumpTwoStep = dp[i - 2] + cost[i - 2]; 9 | dp[i] = min(jumpOneStep, jumpTwoStep); 10 | } 11 | return dp[n]; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /min-stack/min-stack.cpp: -------------------------------------------------------------------------------- 1 | class MinStack { 2 | private: 3 | stack s1; 4 | stack s2; 5 | public: 6 | /** initialize your data structure here. */ 7 | void push(int x) { 8 | s1.push(x); 9 | if (s2.empty() || x <= getMin()) s2.push(x); 10 | } 11 | void pop() { 12 | if (s1.top() == getMin()) s2.pop(); 13 | s1.pop(); 14 | } 15 | int top() { 16 | return s1.top(); 17 | } 18 | int getMin() { 19 | return s2.top(); 20 | } 21 | }; 22 | 23 | /** 24 | * Your MinStack object will be instantiated and called as such: 25 | * MinStack* obj = new MinStack(); 26 | * obj->push(val); 27 | * obj->pop(); 28 | * int param_3 = obj->top(); 29 | * int param_4 = obj->getMin(); 30 | */ -------------------------------------------------------------------------------- /minimum-falling-path-sum/minimum-falling-path-sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minFallingPathSum(vector>& matrix) { 4 | 5 | int n = matrix.size(); 6 | 7 | if(n==1) return matrix[0][0]; 8 | 9 | vector> dp(n, vector (n,0)); 10 | 11 | for(int i=0; i0) dp[i][j] = min(dp[i][j], dp[i-1][j-1] + matrix[i][j]); 19 | if(j64. Minimum Path Sum

Medium


Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.

2 | 3 |

Note: You can only move either down or right at any point in time.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
 9 | Output: 7
10 | Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.
11 | 
12 | 13 |

Example 2:

14 | 15 |
Input: grid = [[1,2,3],[4,5,6]]
16 | Output: 12
17 | 
18 | 19 |

 

20 |

Constraints:

21 | 22 |
    23 |
  • m == grid.length
  • 24 |
  • n == grid[i].length
  • 25 |
  • 1 <= m, n <= 200
  • 26 |
  • 0 <= grid[i][j] <= 100
  • 27 |
28 |
-------------------------------------------------------------------------------- /minimum-path-sum/minimum-path-sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minPathSum(vector>& grid) { 4 | int m = grid.size(); 5 | int n = grid[0].size(); 6 | vector > sum(m, vector(n, grid[0][0])); 7 | for (int i = 1; i < m; i++) 8 | sum[i][0] = sum[i - 1][0] + grid[i][0]; 9 | for (int j = 1; j < n; j++) 10 | sum[0][j] = sum[0][j - 1] + grid[0][j]; 11 | for (int i = 1; i < m; i++) 12 | for (int j = 1; j < n; j++) 13 | sum[i][j] = min(sum[i - 1][j], sum[i][j - 1]) + grid[i][j]; 14 | return sum[m - 1][n - 1]; 15 | } 16 | }; -------------------------------------------------------------------------------- /minimum-window-substring/minimum-window-substring.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string minWindow(string s, string t) { 4 | 5 | unordered_map freq; 6 | 7 | for(char c: t){ 8 | freq[c]++; 9 | } 10 | 11 | int cnt = t.length(); 12 | 13 | int i=0, j=0; 14 | int minLength = INT_MAX; 15 | int minStart = -1; 16 | 17 | while(j 0) 20 | cnt--; 21 | 22 | freq[s[j]]--; 23 | 24 | while(!cnt){ 25 | 26 | if(j-i+1 < minLength){ 27 | minLength = j-i+1; 28 | minStart = i; 29 | } 30 | 31 | freq[s[i]]++; 32 | if(freq[s[i]] > 0){ 33 | cnt++; 34 | } 35 | i++; 36 | } 37 | j++; 38 | } 39 | 40 | return minLength == INT_MAX ? "" : s.substr(minStart,minLength); 41 | 42 | } 43 | }; -------------------------------------------------------------------------------- /move-zeroes/README.md: -------------------------------------------------------------------------------- 1 |

283. Move Zeroes

Easy


Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.

2 | 3 |

Note that you must do this in-place without making a copy of the array.

4 | 5 |

 

6 |

Example 1:

7 |
Input: nums = [0,1,0,3,12]
 8 | Output: [1,3,12,0,0]
 9 | 

Example 2:

10 |
Input: nums = [0]
11 | Output: [0]
12 | 
13 |

 

14 |

Constraints:

15 | 16 |
    17 |
  • 1 <= nums.length <= 104
  • 18 |
  • -231 <= nums[i] <= 231 - 1
  • 19 |
20 | 21 |

 

22 | Follow up: Could you minimize the total number of operations done?
-------------------------------------------------------------------------------- /move-zeroes/move-zeroes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void moveZeroes(vector& nums) { 4 | 5 | int lastNonZeroFoundAt = 0; 6 | 7 | for (int i = 0; i < nums.size(); i++) { 8 | if (nums[i] != 0) { 9 | nums[lastNonZeroFoundAt++] = nums[i]; 10 | } 11 | } 12 | for (int i = lastNonZeroFoundAt; i < nums.size(); i++) { 13 | nums[i] = 0; 14 | } 15 | } 16 | }; -------------------------------------------------------------------------------- /n-ary-tree-level-order-traversal/n-ary-tree-level-order-traversal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | // Definition for a Node. 3 | class Node { 4 | public: 5 | int val; 6 | vector children; 7 | 8 | Node() {} 9 | 10 | Node(int _val) { 11 | val = _val; 12 | } 13 | 14 | Node(int _val, vector _children) { 15 | val = _val; 16 | children = _children; 17 | } 18 | }; 19 | */ 20 | 21 | class Solution { 22 | public: 23 | vector> levelOrder(Node* root) { 24 | if (root == NULL) 25 | return {}; 26 | vector> res; 27 | queue q; 28 | q.push(root); 29 | while (!q.empty()) 30 | { 31 | int size = q.size(); 32 | vector currlevel; 33 | for(int i=0;ival); 37 | for (auto n : tmp -> children) 38 | q.push(n); 39 | } 40 | res.push_back(currlevel); 41 | } 42 | return res; 43 | } 44 | }; -------------------------------------------------------------------------------- /n-th-tribonacci-number/README.md: -------------------------------------------------------------------------------- 1 |

1137. N-th Tribonacci Number

Easy


The Tribonacci sequence Tn is defined as follows: 

2 | 3 |

T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0.

4 | 5 |

Given n, return the value of Tn.

6 | 7 |

 

8 |

Example 1:

9 | 10 |
Input: n = 4
11 | Output: 4
12 | Explanation:
13 | T_3 = 0 + 1 + 1 = 2
14 | T_4 = 1 + 1 + 2 = 4
15 | 
16 | 17 |

Example 2:

18 | 19 |
Input: n = 25
20 | Output: 1389537
21 | 
22 | 23 |

 

24 |

Constraints:

25 | 26 |
    27 |
  • 0 <= n <= 37
  • 28 |
  • The answer is guaranteed to fit within a 32-bit integer, ie. answer <= 2^31 - 1.
  • 29 |
-------------------------------------------------------------------------------- /n-th-tribonacci-number/n-th-tribonacci-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int tribonacci(int n) { 4 | int a = 0, b = 1, c = 1, d; 5 | 6 | if(n == 0 || n == 1) return n; 7 | 8 | if(n == 2) return c; 9 | 10 | for(int i=3; i<=n; i++){ 11 | d = a + b + c; 12 | a = b; 13 | b = c; 14 | c = d; 15 | } 16 | return d; 17 | } 18 | }; -------------------------------------------------------------------------------- /next-permutation/README.md: -------------------------------------------------------------------------------- 1 |

31. Next Permutation

Medium


Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

2 | 3 |

If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order).

4 | 5 |

The replacement must be in place and use only constant extra memory.

6 | 7 |

 

8 |

Example 1:

9 |
Input: nums = [1,2,3]
10 | Output: [1,3,2]
11 | 

Example 2:

12 |
Input: nums = [3,2,1]
13 | Output: [1,2,3]
14 | 

Example 3:

15 |
Input: nums = [1,1,5]
16 | Output: [1,5,1]
17 | 

Example 4:

18 |
Input: nums = [1]
19 | Output: [1]
20 | 
21 |

 

22 |

Constraints:

23 | 24 |
    25 |
  • 1 <= nums.length <= 100
  • 26 |
  • 0 <= nums[i] <= 100
  • 27 |
28 |
-------------------------------------------------------------------------------- /next-permutation/next-permutation.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void nextPermutation(vector& nums) { 4 | 5 | int i = nums.size()-2; 6 | 7 | while(i>=0 && nums[i+1] <= nums[i]) i--; 8 | 9 | if(i>=0){ 10 | int j=nums.size()-1; 11 | 12 | while(nums[j] <= nums[i]) j--; 13 | 14 | swap(nums[i], nums[j]); 15 | } 16 | 17 | i = i+1; 18 | int j = nums.size()-1; 19 | 20 | while(i600. Non-negative Integers without Consecutive Ones

Hard


Given a positive integer n, return the number of the integers in the range [0, n] whose binary representations do not contain consecutive ones.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
Input: n = 5
 7 | Output: 5
 8 | Explanation:
 9 | Here are the non-negative integers <= 5 with their corresponding binary representations:
10 | 0 : 0
11 | 1 : 1
12 | 2 : 10
13 | 3 : 11
14 | 4 : 100
15 | 5 : 101
16 | Among them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule. 
17 | 
18 | 19 |

Example 2:

20 | 21 |
Input: n = 1
22 | Output: 2
23 | 
24 | 25 |

Example 3:

26 | 27 |
Input: n = 2
28 | Output: 3
29 | 
30 | 31 |

 

32 |

Constraints:

33 | 34 |
    35 |
  • 1 <= n <= 109
  • 36 |
37 |
-------------------------------------------------------------------------------- /non-negative-integers-without-consecutive-ones/non-negative-integers-without-consecutive-ones.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findIntegers(int num) { 4 | 5 | int *f = new int[32]; 6 | f[0] = 1; 7 | f[1] = 2; 8 | 9 | for(int i=2; i<32; i++){ 10 | f[i] = f[i-1] + f[i-2]; 11 | } 12 | 13 | int i=30; 14 | int sum = 0, prev_bit = 0; 15 | 16 | while(i>=0){ 17 | 18 | if((num&(1<>& grid){ 7 | 8 | //Base Condition 9 | if (i < 0 || j < 0 || i >= n || j >= m || grid[i][j] != '1') return; 10 | 11 | grid[i][j] = '0'; // Mark 0 (visited) 12 | 13 | // DFS Neighbours 14 | DFS(i+1,j,grid); 15 | DFS(i,j+1,grid); 16 | DFS(i-1,j,grid); 17 | DFS(i,j-1,grid); 18 | return; 19 | } 20 | 21 | int numIslands(vector>& grid) { 22 | int count = 0; 23 | n = grid.size(); 24 | m = grid[0].size(); 25 | 26 | if(n==0) return 0; // No islands if size of grid is 0 27 | 28 | //Loop to traverse all the elements of the grid 29 | for(int i=0; i>& isConnected, vector &visited, int i){ 7 | 8 | for(int j=0; j>& isConnected) { 18 | 19 | vector visited(isConnected.size(),false); 20 | 21 | int cnt = 0; 22 | 23 | for(int i=0; i234. Palindrome Linked List

Easy


Given the head of a singly linked list, return true if it is a palindrome.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
Input: head = [1,2,2,1]
 7 | Output: true
 8 | 
9 | 10 |

Example 2:

11 | 12 |
Input: head = [1,2]
13 | Output: false
14 | 
15 | 16 |

 

17 |

Constraints:

18 | 19 |
    20 |
  • The number of nodes in the list is in the range [1, 105].
  • 21 |
  • 0 <= Node.val <= 9
  • 22 |
23 | 24 |

 

25 | Follow up: Could you do it in O(n) time and O(1) space?
-------------------------------------------------------------------------------- /palindromic-substrings/README.md: -------------------------------------------------------------------------------- 1 |

647. Palindromic Substrings

Medium


Given a string s, return the number of palindromic substrings in it.

2 | 3 |

A string is a palindrome when it reads the same backward as forward.

4 | 5 |

A substring is a contiguous sequence of characters within the string.

6 | 7 |

 

8 |

Example 1:

9 | 10 |
Input: s = "abc"
11 | Output: 3
12 | Explanation: Three palindromic strings: "a", "b", "c".
13 | 
14 | 15 |

Example 2:

16 | 17 |
Input: s = "aaa"
18 | Output: 6
19 | Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
20 | 
21 | 22 |

 

23 |

Constraints:

24 | 25 |
    26 |
  • 1 <= s.length <= 1000
  • 27 |
  • s consists of lowercase English letters.
  • 28 |
29 |
-------------------------------------------------------------------------------- /palindromic-substrings/palindromic-substrings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countSubstrings(string s) { 4 | 5 | int n = s.size(); 6 | 7 | int dp[n+1][n+1]; 8 | memset(dp, 0, sizeof(dp)); 9 | 10 | int ans = 0; 11 | 12 | // dp[i][j] == 1 for every i==j as every char is a pallindromic substring of length 1 13 | for(int i=0; i763. Partition Labels

Medium


You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part.

2 | 3 |

Return a list of integers representing the size of these parts.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
Input: s = "ababcbacadefegdehijhklij"
 9 | Output: [9,7,8]
10 | Explanation:
11 | The partition is "ababcbaca", "defegde", "hijhklij".
12 | This is a partition so that each letter appears in at most one part.
13 | A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits s into less parts.
14 | 
15 | 16 |

Example 2:

17 | 18 |
Input: s = "eccbbbbdec"
19 | Output: [10]
20 | 
21 | 22 |

 

23 |

Constraints:

24 | 25 |
    26 |
  • 1 <= s.length <= 500
  • 27 |
  • s consists of lowercase English letters.
  • 28 |
29 |
-------------------------------------------------------------------------------- /partition-labels/partition-labels.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector partitionLabels(string s) { 4 | vector lastidx(26); 5 | 6 | for(int i=0; i ans; 12 | for(int i=0; i119. Pascal's Triangle II

Easy


Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle.

2 | 3 |

In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:

4 | 5 |

 

6 |

Example 1:

7 |
Input: rowIndex = 3
 8 | Output: [1,3,3,1]
 9 | 

Example 2:

10 |
Input: rowIndex = 0
11 | Output: [1]
12 | 

Example 3:

13 |
Input: rowIndex = 1
14 | Output: [1,1]
15 | 
16 |

 

17 |

Constraints:

18 | 19 |
    20 |
  • 0 <= rowIndex <= 33
  • 21 |
22 | 23 |

 

24 |

Follow up: Could you optimize your algorithm to use only O(rowIndex) extra space?

25 |
-------------------------------------------------------------------------------- /pascals-triangle-ii/pascals triangle2.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector getRow(int rowIndex) { 4 | vector>v; 5 | vectorans; 6 | int n=rowIndex+1; 7 | for(int i=0;ib; 10 | for(int j=0;j<=i;j++) 11 | { 12 | if(j==0 || j==i) 13 | { 14 | b.push_back(1); 15 | } 16 | else{ 17 | b.push_back(v[i-1][j-1]+v[i-1][j]); 18 | } 19 | } 20 | v.push_back(b); 21 | b.clear(); 22 | } 23 | for(int j=0;j118. Pascal's Triangle

Easy


Given an integer numRows, return the first numRows of Pascal's triangle.

2 | 3 |

In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:

4 | 5 |

 

6 |

Example 1:

7 |
Input: numRows = 5
 8 | Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
 9 | 

Example 2:

10 |
Input: numRows = 1
11 | Output: [[1]]
12 | 
13 |

 

14 |

Constraints:

15 | 16 |
    17 |
  • 1 <= numRows <= 30
  • 18 |
19 |
-------------------------------------------------------------------------------- /pascals-triangle/pascals-triangle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> generate(int numRows) { 4 | vector> res; 5 | for(auto i=0;i(i+1,1)); 8 | for(auto j=1; j& nums, int n) { 4 | int cnt=0,i=0; 5 | long long maxNum=0; 6 | while (maxNum279. Perfect Squares

Medium


Given an integer n, return the least number of perfect square numbers that sum to n.

2 | 3 |

A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
Input: n = 12
 9 | Output: 3
10 | Explanation: 12 = 4 + 4 + 4.
11 | 
12 | 13 |

Example 2:

14 | 15 |
Input: n = 13
16 | Output: 2
17 | Explanation: 13 = 4 + 9.
18 | 
19 | 20 |

 

21 |

Constraints:

22 | 23 |
    24 |
  • 1 <= n <= 104
  • 25 |
26 |
-------------------------------------------------------------------------------- /perfect-squares/perfect-squares.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numSquares(int n) { 4 | if (n <= 0) 5 | { 6 | return 0; 7 | } 8 | 9 | vector cntPerfectSquares(n + 1, INT_MAX); 10 | cntPerfectSquares[0] = 0; 11 | for (int i = 1; i <= n; i++) 12 | { 13 | for (int j = 1; j*j <= i; j++) 14 | { 15 | cntPerfectSquares[i] = 16 | min(cntPerfectSquares[i], cntPerfectSquares[i - j*j] + 1); 17 | } 18 | } 19 | 20 | return cntPerfectSquares.back(); 21 | } 22 | }; -------------------------------------------------------------------------------- /permutation-in-string/README.md: -------------------------------------------------------------------------------- 1 |

567. Permutation in String

Medium


Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.

2 | 3 |

In other words, return true if one of s1's permutations is the substring of s2.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
Input: s1 = "ab", s2 = "eidbaooo"
 9 | Output: true
10 | Explanation: s2 contains one permutation of s1 ("ba").
11 | 
12 | 13 |

Example 2:

14 | 15 |
Input: s1 = "ab", s2 = "eidboaoo"
16 | Output: false
17 | 
18 | 19 |

 

20 |

Constraints:

21 | 22 |
    23 |
  • 1 <= s1.length, s2.length <= 104
  • 24 |
  • s1 and s2 consist of lowercase English letters.
  • 25 |
26 |
-------------------------------------------------------------------------------- /permutation-in-string/permutation-in-string.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkInclusion(string s1, string s2) { 4 | vector cur(26), goal(26); 5 | for(char c : s1) goal[c - 'a']++; 6 | for(int i = 0; i < s2.size(); i++) { 7 | cur[s2[i] - 'a']++; 8 | if(i >= s1.size()) cur[s2[i - s1.size()] - 'a']--; 9 | if(goal == cur) return true; 10 | } 11 | return false; 12 | } 13 | }; -------------------------------------------------------------------------------- /permutations/README.md: -------------------------------------------------------------------------------- 1 |

46. Permutations

Medium


Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

2 | 3 |

 

4 |

Example 1:

5 |
Input: nums = [1,2,3]
 6 | Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
 7 | 

Example 2:

8 |
Input: nums = [0,1]
 9 | Output: [[0,1],[1,0]]
10 | 

Example 3:

11 |
Input: nums = [1]
12 | Output: [[1]]
13 | 
14 |

 

15 |

Constraints:

16 | 17 |
    18 |
  • 1 <= nums.length <= 6
  • 19 |
  • -10 <= nums[i] <= 10
  • 20 |
  • All the integers of nums are unique.
  • 21 |
22 |
-------------------------------------------------------------------------------- /permutations/permutations.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | vector> res; 5 | 6 | vector> permute(vector& nums) { 7 | helper(nums,0,nums.size()-1); 8 | return res; 9 | } 10 | 11 | void helper(vector& nums, int i, int n){ 12 | 13 | if(i==n){ 14 | res.push_back(nums); 15 | return; 16 | } 17 | 18 | for(int j=i; j<=n; j++){ 19 | swap(nums[i], nums[j]); 20 | helper(nums, i+1, n); 21 | swap(nums[j], nums[i]); 22 | } 23 | 24 | } 25 | 26 | }; -------------------------------------------------------------------------------- /populating-next-right-pointers-in-each-node/populating-next-right-pointers-in-each-node.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | // Definition for a Node. 3 | class Node { 4 | public: 5 | int val; 6 | Node* left; 7 | Node* right; 8 | Node* next; 9 | 10 | Node() : val(0), left(NULL), right(NULL), next(NULL) {} 11 | 12 | Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} 13 | 14 | Node(int _val, Node* _left, Node* _right, Node* _next) 15 | : val(_val), left(_left), right(_right), next(_next) {} 16 | }; 17 | */ 18 | 19 | class Solution { 20 | public: 21 | 22 | void connectHelper(Node* root){ 23 | 24 | if(!root){ 25 | return; 26 | } 27 | 28 | if(root->left != NULL){ 29 | root->left->next = root->right; 30 | } 31 | if(root->right != NULL && root->next != NULL){ 32 | root->right->next = root->next->left; 33 | } 34 | 35 | connectHelper(root->left); 36 | connectHelper(root->right); 37 | 38 | } 39 | 40 | Node* connect(Node* root) { 41 | connectHelper(root); 42 | return root; 43 | } 44 | }; -------------------------------------------------------------------------------- /postorder.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node { 5 | int data; 6 | struct Node *left, *right; 7 | Node(int data) 8 | { 9 | this->data = data; 10 | left = right = NULL; 11 | } 12 | }; 13 | 14 | void printPostorder(struct Node* node) 15 | { 16 | if (node == NULL) 17 | return; 18 | 19 | // left subtree 20 | printPostorder(node->left); 21 | 22 | // right subtree 23 | printPostorder(node->right); 24 | 25 | cout << node->data << " "; 26 | } 27 | 28 | int main() 29 | { 30 | struct Node* root = new Node(1); 31 | root->left = new Node(2); 32 | root->right = new Node(3); 33 | root->left->left = new Node(4); 34 | root->left->right = new Node(5); 35 | 36 | cout << "Postorder traversal of binary tree is"< productExceptSelf(vector& nums) { 4 | 5 | int n = nums.size(); 6 | 7 | vector preProd(n,1), postProd(n,1), ans(n,1); 8 | 9 | //Compute preProd 10 | for(int i=1; i=0; i--){ 16 | postProd[i] = postProd[i+1]*nums[i+1]; 17 | } 18 | 19 | for(int i=0; i0) res += dominoes[i]; 19 | 20 | if(dominoes[i] == dominoes[j]){ 21 | res += string(freq, dominoes[i]); 22 | } 23 | else if(dominoes[i] == 'L' && dominoes[j] == 'R'){ 24 | res += string(freq,'.'); 25 | } 26 | else{ 27 | res+= string(freq/2,'R') + string(freq%2,'.') + string(freq/2,'L'); 28 | } 29 | i=j; 30 | j++; 31 | } 32 | return res; 33 | } 34 | }; -------------------------------------------------------------------------------- /range-sum-query-immutable/range-sum-query-immutable.cpp: -------------------------------------------------------------------------------- 1 | class NumArray { 2 | 3 | private: 4 | vector preSum; 5 | 6 | public: 7 | NumArray(vector& nums) { 8 | int n = nums.size(); 9 | preSum.assign(n+1,0); 10 | 11 | preSum[0] = 0; 12 | 13 | for(int i=1; i<=n; i++){ 14 | preSum[i] = preSum[i-1]+nums[i-1]; 15 | } 16 | 17 | } 18 | 19 | int sumRange(int left, int right) { 20 | return preSum[right+1]-preSum[left]; 21 | } 22 | }; 23 | 24 | /** 25 | * Your NumArray object will be instantiated and called as such: 26 | * NumArray* obj = new NumArray(nums); 27 | * int param_1 = obj->sumRange(left,right); 28 | */ -------------------------------------------------------------------------------- /remove-boxes/remove-boxes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int dp[100][100][100]; 5 | 6 | int removeBoxes(vector& boxes) { 7 | int n = boxes.size(); 8 | memset(dp, 0, sizeof(dp)); 9 | return helper(boxes, 0, n-1, 0); 10 | } 11 | 12 | int helper(vector &boxes, int l, int r, int k){ 13 | 14 | if(l>r) return 0; 15 | 16 | while(r>l && boxes[r] == boxes[r-1]){ 17 | r--; 18 | k++; 19 | } 20 | 21 | if(dp[l][r][k] != 0){ 22 | return dp[l][r][k]; 23 | } 24 | 25 | dp[l][r][k] = helper(boxes, l, r - 1, 0) + (k + 1) * (k + 1); 26 | 27 | for(int i=l; i82. Remove Duplicates from Sorted List II

Medium


Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
Input: head = [1,2,3,3,4,4,5]
 7 | Output: [1,2,5]
 8 | 
9 | 10 |

Example 2:

11 | 12 |
Input: head = [1,1,1,2,3]
13 | Output: [2,3]
14 | 
15 | 16 |

 

17 |

Constraints:

18 | 19 |
    20 |
  • The number of nodes in the list is in the range [0, 300].
  • 21 |
  • -100 <= Node.val <= 100
  • 22 |
  • The list is guaranteed to be sorted in ascending order.
  • 23 |
24 |
-------------------------------------------------------------------------------- /remove-duplicates-from-sorted-list-ii/remove-duplicates-from-sorted-list-ii.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* deleteDuplicates(ListNode* head) { 14 | 15 | ListNode *dummy = new ListNode(0, head); 16 | 17 | ListNode *temp = dummy; 18 | 19 | while(head){ 20 | 21 | if(head->next && head->val == head->next->val){ 22 | 23 | while(head->next && head->val == head->next->val){ 24 | head = head->next; 25 | } 26 | temp->next = head->next; 27 | } 28 | else{ 29 | temp = temp->next; 30 | } 31 | head = head->next; 32 | } 33 | return dummy->next; 34 | } 35 | }; -------------------------------------------------------------------------------- /remove-nth-node-from-end-of-list/README.md: -------------------------------------------------------------------------------- 1 |

19. Remove Nth Node From End of List

Medium


Given the head of a linked list, remove the nth node from the end of the list and return its head.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
Input: head = [1,2,3,4,5], n = 2
 7 | Output: [1,2,3,5]
 8 | 
9 | 10 |

Example 2:

11 | 12 |
Input: head = [1], n = 1
13 | Output: []
14 | 
15 | 16 |

Example 3:

17 | 18 |
Input: head = [1,2], n = 1
19 | Output: [1]
20 | 
21 | 22 |

 

23 |

Constraints:

24 | 25 |
    26 |
  • The number of nodes in the list is sz.
  • 27 |
  • 1 <= sz <= 30
  • 28 |
  • 0 <= Node.val <= 100
  • 29 |
  • 1 <= n <= sz
  • 30 |
31 | 32 |

 

33 |

Follow up: Could you do this in one pass?

34 |
-------------------------------------------------------------------------------- /remove-nth-node-from-end-of-list/remove-nth-node-from-end-of-list.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* removeNthFromEnd(ListNode* head, int n) { 14 | 15 | ListNode *dummy = new ListNode(0); 16 | dummy->next = head; 17 | 18 | ListNode *first = dummy; 19 | ListNode *second = dummy; 20 | 21 | for(int i=0; i<=n; i++) first = first->next; 22 | 23 | while(first!=NULL){ 24 | first = first->next; 25 | second = second->next; 26 | } 27 | second->next = second->next->next; 28 | return dummy->next; 29 | } 30 | }; -------------------------------------------------------------------------------- /reverse-bits/reverse-bits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | uint32_t reverseBits(uint32_t n) { 4 | uint32_t result= 0; 5 | for(int i=0; i<32; i++) 6 | result = (result<<1) + (n>>i &1); 7 | 8 | return result; 9 | } 10 | }; -------------------------------------------------------------------------------- /reverse-linked-list/README.md: -------------------------------------------------------------------------------- 1 |

206. Reverse Linked List

Easy


Given the head of a singly linked list, reverse the list, and return the reversed list.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
Input: head = [1,2,3,4,5]
 7 | Output: [5,4,3,2,1]
 8 | 
9 | 10 |

Example 2:

11 | 12 |
Input: head = [1,2]
13 | Output: [2,1]
14 | 
15 | 16 |

Example 3:

17 | 18 |
Input: head = []
19 | Output: []
20 | 
21 | 22 |

 

23 |

Constraints:

24 | 25 |
    26 |
  • The number of nodes in the list is the range [0, 5000].
  • 27 |
  • -5000 <= Node.val <= 5000
  • 28 |
29 | 30 |

 

31 |

Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?

32 |
-------------------------------------------------------------------------------- /reverse-linked-list/reverse-linked-list.cpp: -------------------------------------------------------------------------------- 1 | ListNode* reverseList(ListNode* head) { 2 | ListNode *prev=NULL,*curr=head,*newcurr; 3 | while(curr) 4 | { 5 | newcurr=curr->next; 6 | curr->next=prev; 7 | prev=curr; 8 | curr=newcurr; 9 | } 10 | return prev; 11 | 12 | } 13 | -------------------------------------------------------------------------------- /reverse-string/README.md: -------------------------------------------------------------------------------- 1 |

344. Reverse String

Easy


Write a function that reverses a string. The input string is given as an array of characters s.

2 | 3 |

 

4 |

Example 1:

5 |
Input: s = ["h","e","l","l","o"]
 6 | Output: ["o","l","l","e","h"]
 7 | 

Example 2:

8 |
Input: s = ["H","a","n","n","a","h"]
 9 | Output: ["h","a","n","n","a","H"]
10 | 
11 |

 

12 |

Constraints:

13 | 14 | 18 | 19 |

 

20 |

Follow up: Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

21 |
-------------------------------------------------------------------------------- /reverse-string/reverse-string.cpp: -------------------------------------------------------------------------------- 1 | void reverseString(vector& s) { 2 | int l=0,r=s.size()-1; 3 | while(l557. Reverse Words in a String III

Easy


Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

2 | 3 |

 

4 |

Example 1:

5 |
Input: s = "Let's take LeetCode contest"
 6 | Output: "s'teL ekat edoCteeL tsetnoc"
 7 | 

Example 2:

8 |
Input: s = "God Ding"
 9 | Output: "doG gniD"
10 | 
11 |

 

12 |

Constraints:

13 | 14 |
    15 |
  • 1 <= s.length <= 5 * 104
  • 16 |
  • s contains printable ASCII characters.
  • 17 |
  • s does not contain any leading or trailing spaces.
  • 18 |
  • There is at least one word in s.
  • 19 |
  • All the words in s are separated by a single space.
  • 20 |
21 |
-------------------------------------------------------------------------------- /reverse-words-in-a-string-iii/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string reverseWords(string s) { 4 | int i = 0; 5 | for(int j=0;j& nums, int low, int high){ 5 | while(low& nums, int k) { 13 | int n = nums.size(); 14 | k = k%n; 15 | reverse(nums,0,n-k-1); 16 | reverse(nums,n-k,n-1); 17 | reverse(nums,0,n-1); 18 | } 19 | }; -------------------------------------------------------------------------------- /rotate-image/rotate-image.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | void transpose(vector>& matrix){ 5 | for(int i=0; i>& matrix) { 14 | 15 | transpose(matrix); 16 | 17 | for(int i=0; i>& matrix, int target) { 2 | int rmax=matrix.size(), cmax=matrix[0].size(); 3 | int r,c,start=0, end=rmax*cmax-1,mid; 4 | while(start<=end) //Binary search 5 | { 6 | mid=(start+end)/2; // in 1d array 7 | r=mid/cmax; 8 | c=mid-r*cmax; //finding respective index in matrix 9 | if(matrix[r][c]>target) 10 | end=mid-1; 11 | else if(matrix[r][c]& nums, int target) { 4 | 5 | int low = 0; 6 | int high = nums.size()-1; 7 | 8 | while(low<=high){ 9 | 10 | int mid = (low+high)/2; 11 | 12 | if(nums[mid] == target) return mid; 13 | 14 | else if(nums[mid]>=nums[low]){ 15 | if(target<=nums[mid] && target>=nums[low]) 16 | high = mid-1; 17 | else 18 | low = mid+1; 19 | } 20 | else{ 21 | if(target>=nums[mid] && target<=nums[high]) 22 | low = mid+1; 23 | else 24 | high = mid-1; 25 | } 26 | 27 | } 28 | return -1; 29 | } 30 | }; -------------------------------------------------------------------------------- /search-insert-position/search-insert-position.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int searchInsert(vector& nums, int target) { 4 | 5 | int n = nums.size(); 6 | 7 | int l=0, r=n-1; 8 | 9 | int mid; 10 | 11 | while(l<=r){ 12 | 13 | mid = (l+r)/2; 14 | 15 | if(nums[mid] == target){ 16 | return mid; 17 | } 18 | else if(nums[mid] > target){ 19 | r = mid-1; 20 | } 21 | else{ 22 | l = mid+1; 23 | } 24 | 25 | } 26 | 27 | return l; 28 | 29 | } 30 | }; -------------------------------------------------------------------------------- /single-number/README.md: -------------------------------------------------------------------------------- 1 |

136. Single Number

Easy


Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.

2 | 3 |

You must implement a solution with a linear runtime complexity and use only constant extra space.

4 | 5 |

 

6 |

Example 1:

7 |
Input: nums = [2,2,1]
 8 | Output: 1
 9 | 

Example 2:

10 |
Input: nums = [4,1,2,1,2]
11 | Output: 4
12 | 

Example 3:

13 |
Input: nums = [1]
14 | Output: 1
15 | 
16 |

 

17 |

Constraints:

18 | 19 |
    20 |
  • 1 <= nums.length <= 3 * 104
  • 21 |
  • -3 * 104 <= nums[i] <= 3 * 104
  • 22 |
  • Each element in the array appears twice except for one element which appears only once.
  • 23 |
24 |
-------------------------------------------------------------------------------- /single-number/single-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int singleNumber(vector& nums) { 4 | 5 | int ans = 0; 6 | 7 | for(int i: nums){ 8 | ans^=i; 9 | } 10 | return ans; 11 | } 12 | }; -------------------------------------------------------------------------------- /sliding-window-maximum/sliding-window-maximum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector maxSlidingWindow(vector& nums, int k) { 4 | 5 | deque dq; 6 | vector ans; 7 | 8 | for(int i=0; i=k-1) ans.push_back(nums[dq.front()]); 20 | } 21 | return ans; 22 | } 23 | }; -------------------------------------------------------------------------------- /sort-colors/sort-colors.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void sortColors(vector& nums) { 4 | 5 | int i=0,j=0,k=nums.size()-1; 6 | 7 | while(i<=k){ 8 | if(nums[i] == 0){ 9 | swap(nums[i++],nums[j++]); 10 | } 11 | else if(nums[i] == 2){ 12 | swap(nums[i],nums[k--]); 13 | } 14 | else{ 15 | i++; 16 | } 17 | } 18 | 19 | 20 | } 21 | }; -------------------------------------------------------------------------------- /spiral-matrix/README.md: -------------------------------------------------------------------------------- 1 |

54. Spiral Matrix

Medium


Given an m x n matrix, return all elements of the matrix in spiral order.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
 7 | Output: [1,2,3,6,9,8,7,4,5]
 8 | 
9 | 10 |

Example 2:

11 | 12 |
Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
13 | Output: [1,2,3,4,8,12,11,10,9,5,6,7]
14 | 
15 | 16 |

 

17 |

Constraints:

18 | 19 |
    20 |
  • m == matrix.length
  • 21 |
  • n == matrix[i].length
  • 22 |
  • 1 <= m, n <= 10
  • 23 |
  • -100 <= matrix[i][j] <= 100
  • 24 |
25 |
-------------------------------------------------------------------------------- /squares-of-a-sorted-array/README.md: -------------------------------------------------------------------------------- 1 |

977. Squares of a Sorted Array

Easy


Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
Input: nums = [-4,-1,0,3,10]
 7 | Output: [0,1,9,16,100]
 8 | Explanation: After squaring, the array becomes [16,1,0,9,100].
 9 | After sorting, it becomes [0,1,9,16,100].
10 | 
11 | 12 |

Example 2:

13 | 14 |
Input: nums = [-7,-3,2,3,11]
15 | Output: [4,9,9,49,121]
16 | 
17 | 18 |

 

19 |

Constraints:

20 | 21 |
    22 |
  • 1 <= nums.length <= 104
  • 23 |
  • -104 <= nums[i] <= 104
  • 24 |
  • nums is sorted in non-decreasing order.
  • 25 |
26 | 27 |

 

28 | Follow up: Squaring each element and sorting the new array is very trivial, could you find an O(n) solution using a different approach?
-------------------------------------------------------------------------------- /squares-of-a-sorted-array/squares-of-a-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector sortedSquares(vector& A) { 4 | vector res(A.size()); 5 | int l = 0, r = A.size() - 1; 6 | for (int k = A.size() - 1; k >= 0; k--) { 7 | if (abs(A[r]) > abs(A[l])) res[k] = A[r] * A[r--]; 8 | else res[k] = A[l] * A[l++]; 9 | } 10 | return res; 11 | } 12 | }; -------------------------------------------------------------------------------- /subsets-ii/README.md: -------------------------------------------------------------------------------- 1 |

90. Subsets II

Medium


Given an integer array nums that may contain duplicates, return all possible subsets (the power set).

2 | 3 |

The solution set must not contain duplicate subsets. Return the solution in any order.

4 | 5 |

 

6 |

Example 1:

7 |
Input: nums = [1,2,2]
 8 | Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]
 9 | 

Example 2:

10 |
Input: nums = [0]
11 | Output: [[],[0]]
12 | 
13 |

 

14 |

Constraints:

15 | 16 |
    17 |
  • 1 <= nums.length <= 10
  • 18 |
  • -10 <= nums[i] <= 10
  • 19 |
20 |
-------------------------------------------------------------------------------- /subsets-ii/subsets-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | vector> ans; 5 | vector temp; 6 | 7 | void helper(vector& nums, int i, int n, int isPicked){ 8 | 9 | if(i>=n){ 10 | ans.push_back(temp); 11 | return; 12 | } 13 | 14 | //Include the element 15 | if(i == 0 || nums[i-1] != nums[i] || isPicked){ 16 | temp.push_back(nums[i]); 17 | helper(nums, i+1,n, true); 18 | 19 | //Exclude the element 20 | temp.pop_back(); 21 | } 22 | helper(nums,i+1,n, false); 23 | } 24 | 25 | vector> subsetsWithDup(vector& nums) { 26 | 27 | int n = nums.size(); 28 | sort(nums.begin(), nums.end()); 29 | 30 | helper(nums,0,n, true); 31 | 32 | return ans; 33 | } 34 | }; -------------------------------------------------------------------------------- /subsets/README.md: -------------------------------------------------------------------------------- 1 |

78. Subsets

Medium


Given an integer array nums of unique elements, return all possible subsets (the power set).

2 | 3 |

The solution set must not contain duplicate subsets. Return the solution in any order.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
Input: nums = [1,2,3]
 9 | Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
10 | 
11 | 12 |

Example 2:

13 | 14 |
Input: nums = [0]
15 | Output: [[],[0]]
16 | 
17 | 18 |

 

19 |

Constraints:

20 | 21 |
    22 |
  • 1 <= nums.length <= 10
  • 23 |
  • -10 <= nums[i] <= 10
  • 24 |
  • All the numbers of nums are unique.
  • 25 |
26 |
-------------------------------------------------------------------------------- /subsets/subsets.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | vector> ans; 5 | vector temp; 6 | 7 | 8 | void helper(vector &nums, int i, int n){ 9 | if(i==n){ 10 | ans.push_back(temp); 11 | return; 12 | } 13 | 14 | temp.push_back(nums[i]); 15 | helper(nums,i+1,n); 16 | temp.pop_back(); 17 | helper(nums,i+1,n); 18 | } 19 | 20 | vector> subsets(vector& nums) { 21 | 22 | int n = nums.size(); 23 | 24 | helper(nums,0,n); 25 | return ans; 26 | } 27 | }; -------------------------------------------------------------------------------- /symmetric-tree/README.md: -------------------------------------------------------------------------------- 1 |

101. Symmetric Tree

Easy


Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).

2 | 3 |

 

4 |

Example 1:

5 | 6 |
Input: root = [1,2,2,3,4,4,3]
 7 | Output: true
 8 | 
9 | 10 |

Example 2:

11 | 12 |
Input: root = [1,2,2,null,3,null,3]
13 | Output: false
14 | 
15 | 16 |

 

17 |

Constraints:

18 | 19 |
    20 |
  • The number of nodes in the tree is in the range [1, 1000].
  • 21 |
  • -100 <= Node.val <= 100
  • 22 |
23 | 24 |

 

25 | Follow up: Could you solve it both recursively and iteratively?
-------------------------------------------------------------------------------- /symmetric-tree/symmetric-tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | 15 | bool isMirror(TreeNode* r1, TreeNode* r2){ 16 | 17 | if(!r1 && !r2) return true; 18 | if(!r1 || !r2) return false; 19 | 20 | return (r1->val == r2->val) && isMirror(r1->right, r2->left) && isMirror(r2->right, r1->left); 21 | 22 | 23 | } 24 | 25 | bool isSymmetric(TreeNode* root) { 26 | return isMirror(root, root); 27 | } 28 | }; -------------------------------------------------------------------------------- /task-scheduler/task-scheduler.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int leastInterval(vector& tasks, int n) { 4 | unordered_map freq; 5 | 6 | int maxFreq = 0; 7 | 8 | for(char ch: tasks){ 9 | freq[ch]++; 10 | maxFreq = max(freq[ch], maxFreq); 11 | } 12 | 13 | int ans = (n+1)*(maxFreq-1); 14 | 15 | for(auto it: freq){ 16 | if(it.second == maxFreq) ans++; 17 | } 18 | 19 | return max((int)tasks.size(), ans); 20 | } 21 | }; -------------------------------------------------------------------------------- /top-k-frequent-elements/README.md: -------------------------------------------------------------------------------- 1 |

347. Top K Frequent Elements

Medium


Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

2 | 3 |

 

4 |

Example 1:

5 |
Input: nums = [1,1,1,2,2,3], k = 2
 6 | Output: [1,2]
 7 | 

Example 2:

8 |
Input: nums = [1], k = 1
 9 | Output: [1]
10 | 
11 |

 

12 |

Constraints:

13 | 14 |
    15 |
  • 1 <= nums.length <= 105
  • 16 |
  • k is in the range [1, the number of unique elements in the array].
  • 17 |
  • It is guaranteed that the answer is unique.
  • 18 |
19 | 20 |

 

21 |

Follow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size.

22 |
-------------------------------------------------------------------------------- /top-k-frequent-elements/top-k-frequent-elements.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector topKFrequent(vector& nums, int k) { 4 | if (k == nums.size()) { 5 | return nums; 6 | } 7 | 8 | 9 | map count_map; 10 | for (int n : nums) { 11 | count_map[n] += 1; 12 | } 13 | 14 | auto comp = [&count_map](int n1, int n2) { return count_map[n1] > count_map[n2]; }; 15 | priority_queue, decltype(comp)> heap(comp); 16 | 17 | for (pair p : count_map) { 18 | heap.push(p.first); 19 | if (heap.size() > k) heap.pop(); 20 | } 21 | 22 | vector top(k); 23 | for (int i = k - 1; i >= 0; i--) { 24 | top[i] = heap.top(); 25 | heap.pop(); 26 | } 27 | return top; 28 | } 29 | }; -------------------------------------------------------------------------------- /trapping-rain-water/README.md: -------------------------------------------------------------------------------- 1 |

42. Trapping Rain Water

Hard


Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
 7 | Output: 6
 8 | Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.
 9 | 
10 | 11 |

Example 2:

12 | 13 |
Input: height = [4,2,0,3,2,5]
14 | Output: 9
15 | 
16 | 17 |

 

18 |

Constraints:

19 | 20 |
    21 |
  • n == height.length
  • 22 |
  • 0 <= n <= 3 * 104
  • 23 |
  • 0 <= height[i] <= 105
  • 24 |
25 |
-------------------------------------------------------------------------------- /trapping-rain-water/trapping-rain-water.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int trap(vector& A) { 4 | int n = A.size(); 5 | int left=0; int right=n-1; 6 | int res=0; 7 | int maxleft=0, maxright=0; 8 | while(left<=right){ 9 | if(A[left]<=A[right]){ 10 | if(A[left]>=maxleft) maxleft=A[left]; 11 | else res+=maxleft-A[left]; 12 | left++; 13 | } 14 | else{ 15 | if(A[right]>=maxright) maxright= A[right]; 16 | else res+=maxright-A[right]; 17 | right--; 18 | } 19 | } 20 | return res; 21 | } 22 | }; -------------------------------------------------------------------------------- /triangle/triangle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimumTotal(vector>& triangle) { 4 | int n = triangle.size(); 5 | vector minlen(triangle.back()); 6 | for (int layer = n-2; layer >= 0; layer--) // For each layer 7 | { 8 | for (int i = 0; i <= layer; i++) // Check its every 'node' 9 | { 10 | // Find the lesser of its two children, and sum the current value in the triangle with it. 11 | minlen[i] = min(minlen[i], minlen[i+1]) + triangle[layer][i]; 12 | } 13 | } 14 | return minlen[0]; 15 | } 16 | }; -------------------------------------------------------------------------------- /two-sum-ii-input-array-is-sorted/two-sum-ii-input-array-is-sorted.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector twoSum(vector& nums, int target) { 4 | int i=0, j=nums.size()-1; 5 | 6 | while(i target){ 9 | j--; 10 | } 11 | else if(nums[i] + nums[j] < target){ 12 | i++; 13 | } 14 | else{ 15 | return {i+1, j+1}; 16 | } 17 | 18 | } 19 | return {}; 20 | } 21 | }; -------------------------------------------------------------------------------- /two-sum-iv-input-is-a-bst/two-sum-iv-input-is-a-bst.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | 14 | private: 15 | 16 | unordered_set s; 17 | 18 | public: 19 | bool findTarget(TreeNode* root, int k) { 20 | if (!root) return false; 21 | if (s.count(k - root->val)) return true; 22 | s.insert(root->val); 23 | return findTarget(root->left, k) || findTarget(root->right, k); 24 | } 25 | }; -------------------------------------------------------------------------------- /two-sum/two-sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector twoSum(vector& numbers, int target) { 4 | unordered_map hash; 5 | vector result; 6 | for (int i = 0; i < numbers.size(); i++) { 7 | int numberToFind = target - numbers[i]; 8 | 9 | 10 | if (hash.find(numberToFind) != hash.end()) { 11 | 12 | result.push_back(hash[numberToFind] ); 13 | result.push_back(i); 14 | return result; 15 | } 16 | 17 | hash[numbers[i]] = i; 18 | } 19 | return result; 20 | } 21 | }; -------------------------------------------------------------------------------- /ugly-number-ii/README.md: -------------------------------------------------------------------------------- 1 |

264. Ugly Number II

Medium


An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.

2 | 3 |

Given an integer n, return the nth ugly number.

4 | 5 |

 

6 |

Example 1:

7 | 8 |
Input: n = 10
 9 | Output: 12
10 | Explanation: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers.
11 | 
12 | 13 |

Example 2:

14 | 15 |
Input: n = 1
16 | Output: 1
17 | Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.
18 | 
19 | 20 |

 

21 |

Constraints:

22 | 23 |
    24 |
  • 1 <= n <= 1690
  • 25 |
26 |
-------------------------------------------------------------------------------- /ugly-number-ii/ugly-number-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int nthUglyNumber(int n) { 4 | if(n <= 0) return false; // get rid of corner cases 5 | if(n == 1) return true; // base case 6 | int t2 = 0, t3 = 0, t5 = 0; //pointers for 2, 3, 5 7 | vector k(n); 8 | k[0] = 1; 9 | for(int i = 1; i < n ; i ++) 10 | { 11 | k[i] = min({k[t2]*2,k[t3]*3,k[t5]*5}); 12 | if(k[i] == k[t2]*2) t2++; 13 | if(k[i] == k[t3]*3) t3++; 14 | if(k[i] == k[t5]*5) t5++; 15 | } 16 | return k[n-1]; 17 | } 18 | }; -------------------------------------------------------------------------------- /unique-binary-search-trees/README.md: -------------------------------------------------------------------------------- 1 |

96. Unique Binary Search Trees

Medium


Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n.

2 | 3 |

 

4 |

Example 1:

5 | 6 |
Input: n = 3
 7 | Output: 5
 8 | 
9 | 10 |

Example 2:

11 | 12 |
Input: n = 1
13 | Output: 1
14 | 
15 | 16 |

 

17 |

Constraints:

18 | 19 |
    20 |
  • 1 <= n <= 19
  • 21 |
22 |
-------------------------------------------------------------------------------- /unique-binary-search-trees/unique-binary-search-trees.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numTrees(int n) { 4 | 5 | vector dp(n+1, 0); 6 | 7 | dp[0] = 1; 8 | dp[1] = 1; 9 | 10 | for(int i=2; i<=n; i++){ 11 | for(int j=1; j<=i; j++){ 12 | dp[i] += dp[j-1]*dp[i-j]; 13 | } 14 | } 15 | return dp[n]; 16 | } 17 | }; -------------------------------------------------------------------------------- /unique-paths-ii/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int uniquePathsWithObstacles(vector>& obstacleGrid) { 4 | if (obstacleGrid[0][0] == 1) { 5 | return 0; 6 | } 7 | 8 | int m = obstacleGrid.size(); 9 | int n = obstacleGrid[0].size(); 10 | 11 | int dp[m][n]; 12 | 13 | dp[0][0] = 1; 14 | 15 | for(int i=1; i parent; 5 | for (char& c : s) { 6 | switch (c) { 7 | case '(': 8 | case '{': 9 | case '[': parent.push(c); break; 10 | case ')': 11 | if (parent.empty() || parent.top()!='(') return false; 12 | else parent.pop(); break; 13 | case '}': 14 | if (parent.empty() || parent.top()!='{') return false; 15 | else parent.pop(); break; 16 | case ']': 17 | if (parent.empty() || parent.top()!='[') return false; 18 | else parent.pop(); break; 19 | default: ; // pass 20 | } 21 | } 22 | return parent.empty() ; 23 | } 24 | }; -------------------------------------------------------------------------------- /valid-sudoku/valid-sudoku.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isValidSudoku(vector>& board) { 4 | 5 | unordered_set rows[9], cols[9], boxs[9]; 6 | 7 | for(int i=0; i<9; i++){ 8 | for(int j=0; j<9; j++){ 9 | 10 | char val = board[i][j]; 11 | 12 | if(board[i][j] == '.') continue; 13 | 14 | if(rows[i].find(val) != rows[i].end()){ 15 | return false; 16 | } 17 | 18 | if(cols[j].find(val) != cols[j].end()){ 19 | return false; 20 | } 21 | 22 | int k = (i / 3) * 3 + j / 3; 23 | 24 | if(boxs[k].find(val) != boxs[k].end()){ 25 | return false; 26 | } 27 | 28 | rows[i].insert(val); 29 | cols[j].insert(val); 30 | boxs[k].insert(val); 31 | 32 | } 33 | } 34 | return true; 35 | } 36 | }; -------------------------------------------------------------------------------- /verify-preorder-serialization-of-a-binary-tree/verify-preorder-serialization-of-a-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | public: 4 | 5 | bool isValidSerialization(string preorder){ 6 | if (preorder.empty()) return true; 7 | istringstream in(preorder); 8 | string root = isValidSerialization(in); 9 | return !root.empty() && in.eof(); 10 | } 11 | 12 | private: 13 | 14 | string isValidSerialization(istringstream &in){ 15 | string node; 16 | getline(in, node, ','); 17 | if (node == "#" || node.empty()) return node; 18 | string left = isValidSerialization(in); 19 | string right = isValidSerialization(in); 20 | if (left.empty() || right.empty()) return ""; 21 | return node; 22 | } 23 | }; -------------------------------------------------------------------------------- /wiggle-subsequence/wiggle-subsequence.cpp: -------------------------------------------------------------------------------- 1 | int wiggleMaxLength(vector& nums) { 2 | int p=1,n=1; 3 | for(int i=1;i0){ 5 | p=n+1; 6 | }else if((nums[i]-nums[i-1])<0){ 7 | n=p+1; 8 | 9 | }else{ 10 | continue; 11 | } 12 | } 13 | return max(n,p); 14 | } 15 | -------------------------------------------------------------------------------- /wildcard-matching/wildcard-matching.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isMatch(string s, string p) { 4 | int m = s.length(), n = p.length(); 5 | bool f[m + 1][n + 1]; 6 | memset(f, 0, sizeof(f)); 7 | f[0][0] = 1; 8 | 9 | for(int i = 1; i <= n; i ++) { 10 | f[0][i] = p[i - 1] == '*' && f[0][i - 1]; 11 | } 12 | 13 | for(int i = 1; i <= m; i ++) { 14 | for(int j = 1; j <= n; j ++) { 15 | if(p[j - 1] != '*') { 16 | if(p[j - 1] == '?' || s[i - 1] == p[j - 1]) { 17 | f[i][j] = f[i - 1][j - 1]; 18 | } 19 | } 20 | else { 21 | f[i][j] = (f[i][j - 1] || f[i - 1][j]); 22 | } 23 | } 24 | } 25 | return f[m][n]; 26 | 27 | 28 | } 29 | }; -------------------------------------------------------------------------------- /word-break/word-break.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool wordBreak(string s, vector& wordDict) { 4 | 5 | unordered_set st(wordDict.begin(), wordDict.end()); 6 | 7 | int n = s.length(); 8 | 9 | if(n == 0) return false; 10 | 11 | vector dp(n+1, false); 12 | 13 | dp[0] = true; 14 | 15 | for(int i=1; i<=n; i++){ 16 | 17 | for(int j=i-1; j>=0; j--){ 18 | 19 | if(dp[j]){ 20 | string word = s.substr(j,i-j); 21 | if(st.find(word) != st.end()){ 22 | dp[i] = true; 23 | break; 24 | } 25 | } 26 | 27 | } 28 | 29 | } 30 | return dp[n]; 31 | } 32 | }; -------------------------------------------------------------------------------- /word-search/word-search.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | bool dfs(int i, int j, vector>& board, string &word){ 5 | 6 | int n = word.length(); 7 | 8 | if(n == 0){ 9 | return true; 10 | } 11 | 12 | if(i<0 || i>= board.size() || j<0 || j>=board[0].size() || board[i][j] != word[0]){ 13 | return false; 14 | } 15 | 16 | char c = board[i][j]; 17 | board[i][j] = '*'; 18 | string temp = word.substr(1); 19 | 20 | bool ans = dfs(i-1,j,board,temp) || dfs(i+1,j,board,temp) || dfs(i,j+1,board,temp) || dfs(i,j-1,board,temp); 21 | 22 | board[i][j] = c; 23 | return ans; 24 | 25 | } 26 | 27 | bool exist(vector>& board, string word) { 28 | 29 | for(int i=0; i temp(numRows, ""); 6 | int row = 0, direction = 1; 7 | string ans = ""; 8 | 9 | if(numRows == 1) 10 | return s; 11 | 12 | for(int i = 0; i < s.size(); i++) 13 | { 14 | temp[row] += s[i]; 15 | 16 | if(row == numRows - 1) 17 | direction = -1; 18 | if(row == 0) 19 | direction = 1; 20 | 21 | row += direction; 22 | 23 | } 24 | 25 | for(int i = 0; i < numRows; i++) 26 | { 27 | ans += temp[i]; 28 | } 29 | 30 | return ans; 31 | } 32 | }; --------------------------------------------------------------------------------