├── day-1.cpp ├── day-10.cpp ├── day-100.cpp ├── day-101.cpp ├── day-102.cpp ├── day-103.cpp ├── day-104.cpp ├── day-105.cpp ├── day-106.cpp ├── day-107.cpp ├── day-108.cpp ├── day-109.cpp ├── day-11.cpp ├── day-110.cpp ├── day-111.cpp ├── day-112.cpp ├── day-113.cpp ├── day-114.cpp ├── day-115.cpp ├── day-116.cpp ├── day-117.cpp ├── day-118.cpp ├── day-119.cpp ├── day-12.cpp ├── day-120.cpp ├── day-121.cpp ├── day-122.cpp ├── day-123.cpp ├── day-124.cpp ├── day-125.cpp ├── day-126.cpp ├── day-127.cpp ├── day-128.cpp ├── day-129.cpp ├── day-13.cpp ├── day-130.cpp ├── day-131.cpp ├── day-132.cpp ├── day-133.cpp ├── day-134.cpp ├── day-135.cpp ├── day-136.cpp ├── day-137.cpp ├── day-138.cpp ├── day-139.cpp ├── day-14.cpp ├── day-140.cpp ├── day-141.cpp ├── day-142.cpp ├── day-143.cpp ├── day-144.cpp ├── day-145.cpp ├── day-146.cpp ├── day-147.cpp ├── day-148.cpp ├── day-149.cpp ├── day-15.cpp ├── day-150.cpp ├── day-151.cpp ├── day-152.cpp ├── day-153.cpp ├── day-154.cpp ├── day-155.cpp ├── day-156.cpp ├── day-157.cpp ├── day-158.cpp ├── day-159.cpp ├── day-16.cpp ├── day-160.cpp ├── day-161.cpp ├── day-162.cpp ├── day-163.cpp ├── day-164.cpp ├── day-165.cpp ├── day-166.cpp ├── day-167.cpp ├── day-168.cpp ├── day-169.cpp ├── day-17.cpp ├── day-170.cpp ├── day-171.cpp ├── day-172.cpp ├── day-173.cpp ├── day-174.cpp ├── day-175.cpp ├── day-176.cpp ├── day-177.cpp ├── day-178.cpp ├── day-179.cpp ├── day-18.cpp ├── day-180.cpp ├── day-181.cpp ├── day-182.cpp ├── day-183.cpp ├── day-184.cpp ├── day-185.cpp ├── day-186.cpp ├── day-187.cpp ├── day-188.cpp ├── day-189.cpp ├── day-19.cpp ├── day-190.cpp ├── day-191.cpp ├── day-192.cpp ├── day-193.cpp ├── day-194.cpp ├── day-195.cpp ├── day-196.cpp ├── day-197.cpp ├── day-198.cpp ├── day-199.cpp ├── day-2.cpp ├── day-20.cpp ├── day-200.cpp ├── day-201.cpp ├── day-202.cpp ├── day-203.cpp ├── day-204.cpp ├── day-205.cpp ├── day-206.cpp ├── day-207.cpp ├── day-208.cpp ├── day-209.cpp ├── day-21.cpp ├── day-210.cpp ├── day-211.cpp ├── day-212.cpp ├── day-213.cpp ├── day-214.cpp ├── day-215.cpp ├── day-216.cpp ├── day-217.cpp ├── day-218.cpp ├── day-219.cpp ├── day-22.cpp ├── day-220.cpp ├── day-221.cpp ├── day-222.cpp ├── day-223.cpp ├── day-224.cpp ├── day-225.cpp ├── day-226.cpp ├── day-227.cpp ├── day-228.cpp ├── day-229.cpp ├── day-23.cpp ├── day-230.cpp ├── day-231.cpp ├── day-232.cpp ├── day-233.cpp ├── day-234.cpp ├── day-235.cpp ├── day-236.cpp ├── day-237.cpp ├── day-238.cpp ├── day-239.cpp ├── day-24.cpp ├── day-240.cpp ├── day-241.cpp ├── day-242.cpp ├── day-243.cpp ├── day-244.cpp ├── day-245.cpp ├── day-246.cpp ├── day-247.cpp ├── day-248.cpp ├── day-249.cpp ├── day-25.cpp ├── day-250.cpp ├── day-251.cpp ├── day-252.cpp ├── day-253.cpp ├── day-254.cpp ├── day-255.cpp ├── day-256.cpp ├── day-257.cpp ├── day-258.cpp ├── day-259.cpp ├── day-26.cpp ├── day-260.cpp ├── day-261.cpp ├── day-262.cpp ├── day-263.cpp ├── day-264.cpp ├── day-265.cpp ├── day-266.cpp ├── day-267.cpp ├── day-268.cpp ├── day-269.cpp ├── day-27.cpp ├── day-28.cpp ├── day-280.cpp ├── day-282.cpp ├── day-283.cpp ├── day-284.cpp ├── day-285.cpp ├── day-286.cpp ├── day-287.cpp ├── day-288.cpp ├── day-289.cpp ├── day-29.cpp ├── day-290.cpp ├── day-291.cpp ├── day-292.cpp ├── day-293.cpp ├── day-294.cpp ├── day-299.cpp ├── day-3.cpp ├── day-30.cpp ├── day-31.cpp ├── day-313.cpp ├── day-32.cpp ├── day-33.cpp ├── day-34.cpp ├── day-35.cpp ├── day-36.cpp ├── day-37.cpp ├── day-38.cpp ├── day-39.cpp ├── day-4.cpp ├── day-40.cpp ├── day-41.cpp ├── day-42.cpp ├── day-43.cpp ├── day-44.cpp ├── day-45.cpp ├── day-46.cpp ├── day-47.cpp ├── day-48.cpp ├── day-49.cpp ├── day-5.cpp ├── day-50.cpp ├── day-51.cpp ├── day-52.cpp ├── day-53.cpp ├── day-54.cpp ├── day-55.cpp ├── day-56.cpp ├── day-57.cpp ├── day-58.cpp ├── day-59.cpp ├── day-6.cpp ├── day-60.cpp ├── day-61.cpp ├── day-62.cpp ├── day-63.cpp ├── day-64.cpp ├── day-65.cpp ├── day-66.cpp ├── day-67.cpp ├── day-68.cpp ├── day-69.cpp ├── day-7.cpp ├── day-70.cpp ├── day-71.cpp ├── day-72.cpp ├── day-73.cpp ├── day-74.cpp ├── day-75.cpp ├── day-76.cpp ├── day-77.cpp ├── day-78.cpp ├── day-79.cpp ├── day-8.cpp ├── day-80.cpp ├── day-81.cpp ├── day-82.cpp ├── day-83.cpp ├── day-84.cpp ├── day-85.cpp ├── day-86.cpp ├── day-87.cpp ├── day-88.cpp ├── day-89.cpp ├── day-9.cpp ├── day-90.cpp ├── day-91.cpp ├── day-92.cpp ├── day-93.cpp ├── day-94.cpp ├── day-95.cpp ├── day-96.cpp ├── day-97.cpp ├── day-98.cpp ├── day-99.cpp └── readme.md /day-1.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a non-empty array of integers, every element appears twice except for one. Find that single one. 3 | 4 | */ 5 | 6 | /* 7 | Idea: Use XOR 8 | If odd times: A^A^A = A 9 | If even times: A^A = 0 10 | If done with zero: A^0 = A 11 | */ 12 | 13 | // O(N) & O(1) 14 | class Solution { 15 | public: 16 | int singleNumber(vector& nums) { 17 | int res = 0; 18 | for (int i = 0; i < nums.size(); i++) { 19 | res = res ^ nums[i]; 20 | } 21 | 22 | return res; 23 | } 24 | }; -------------------------------------------------------------------------------- /day-10.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Question: Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. 3 | 4 | push(x) -- Push element x onto stack. 5 | pop() -- Removes the element on top of the stack. 6 | top() -- Get the top element. 7 | getMin() -- Retrieve the minimum element in the stack. 8 | */ 9 | 10 | class MinStack { 11 | public: 12 | stack> tinyStack; 13 | int min; 14 | MinStack() { 15 | min = INT_MAX; 16 | } 17 | 18 | void push(int x) { 19 | if (x < min) min = x; 20 | tinyStack.push(make_pair(x, min)); 21 | } 22 | 23 | void pop() { 24 | tinyStack.pop(); 25 | if (tinyStack.size() == 0) 26 | min = INT_MAX; 27 | else 28 | min = tinyStack.top().second; 29 | } 30 | 31 | int top() { 32 | return tinyStack.top().first; 33 | } 34 | 35 | int getMin() { 36 | return tinyStack.top().second; 37 | } 38 | }; -------------------------------------------------------------------------------- /day-102.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Subsets 3 | 4 | Given a set of distinct integers, nums, return all possible subsets (the power set). 5 | 6 | Note: The solution set must not contain duplicate subsets. 7 | 8 | Example: 9 | 10 | Input: nums = [1,2,3] 11 | Output: 12 | [ 13 | [3], 14 | [1], 15 | [2], 16 | [1,2,3], 17 | [1,3], 18 | [2,3], 19 | [1,2], 20 | [] 21 | ] 22 | */ 23 | 24 | // Recursive solution to make subsets 25 | class Solution { 26 | public: 27 | void subsetsHelper(vector& nums, int idx, vector>& answer) { 28 | if (idx == nums.size() - 1) { 29 | answer.push_back({nums[idx]}); 30 | answer.push_back({}); 31 | } else { 32 | subsetsHelper(nums, idx + 1, answer); 33 | int N = answer.size(); 34 | for (int i = 0; i < N; i++) { 35 | vector curr = answer[i]; 36 | curr.push_back(nums[idx]); 37 | answer.push_back(curr); 38 | } 39 | } 40 | } 41 | 42 | vector> subsets(vector& nums) { 43 | if (!nums.size()) return {{}}; 44 | 45 | vector> answer; 46 | 47 | subsetsHelper(nums, 0, answer); 48 | 49 | return answer; 50 | } 51 | }; -------------------------------------------------------------------------------- /day-104.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Same Tree 3 | 4 | 5 | Given two binary trees, write a function to check if they are the same or not. 6 | 7 | Two binary trees are considered the same if they are structurally identical and the nodes have the same value. 8 | 9 | Example 1: 10 | 11 | Input: 1 1 12 | / \ / \ 13 | 2 3 2 3 14 | 15 | [1,2,3], [1,2,3] 16 | 17 | Output: true 18 | Example 2: 19 | 20 | Input: 1 1 21 | / \ 22 | 2 2 23 | 24 | [1,2], [1,null,2] 25 | 26 | Output: false 27 | Example 3: 28 | 29 | Input: 1 1 30 | / \ / \ 31 | 2 1 1 2 32 | 33 | [1,2,1], [1,1,2] 34 | 35 | Output: false 36 | */ 37 | 38 | // Simple recursive solution to tell is the given trees are same. 39 | class Solution { 40 | public: 41 | bool isSameTree(TreeNode* p, TreeNode* q) { 42 | if (p == NULL && q == NULL) return true; 43 | if (p == NULL || q == NULL) return false; 44 | 45 | if (p->val != q->val) return false; 46 | 47 | return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); 48 | } 49 | }; -------------------------------------------------------------------------------- /day-105.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Angle Between Hands of a Clock 3 | 4 | Given two numbers, hour and minutes. Return the smaller angle (in degrees) formed between the hour and the minute hand. 5 | 6 | Example 1: 7 | Input: hour = 12, minutes = 30 8 | Output: 165 9 | 10 | Example 2: 11 | Input: hour = 12, minutes = 30 12 | Output: 165 13 | 14 | Example 3: 15 | Input: hour = 3, minutes = 15 16 | Output: 7.5 17 | 18 | Example 4: 19 | Input: hour = 3, minutes = 15 20 | Output: 7.5 21 | 22 | Example 5: 23 | Input: hour = 12, minutes = 0 24 | Output: 0 25 | */ 26 | 27 | class Solution { 28 | public: 29 | double angleClock(int hour, int minutes) { 30 | double hourAngle = (hour * 30 + minutes * 0.5); 31 | double minutesAngle = minutes * 6; 32 | double angleOne = fabs(hourAngle - minutesAngle); 33 | double angleTwo = 360 - angleOne; 34 | 35 | return min(angleOne, angleTwo); 36 | } 37 | }; -------------------------------------------------------------------------------- /day-107.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Pow(x, n) 3 | 4 | 5 | Implement pow(x, n), which calculates x raised to the power n (xn). 6 | 7 | Example 1: 8 | 9 | Input: 2.00000, 10 10 | Output: 1024.00000 11 | Example 2: 12 | 13 | Input: 2.10000, 3 14 | Output: 9.26100 15 | Example 3: 16 | 17 | Input: 2.00000, -2 18 | Output: 0.25000 19 | Explanation: 2-2 = 1/22 = 1/4 = 0.25 20 | Note: 21 | 22 | -100.0 < x < 100.0 23 | n is a 32-bit signed integer, within the range [−231, 231 − 1] 24 | 25 | */ 26 | 27 | // Calculate half of the result and multiply accordingly if its odd or even. 28 | class Solution { 29 | public: 30 | double fastPow(double x, long long n) { 31 | if (n == 0) return 1; 32 | 33 | double half = fastPow(x, n / 2); 34 | 35 | if (n % 2 == 0) { 36 | return half * half; 37 | } else { 38 | return half * half * x; 39 | } 40 | } 41 | double myPow(double x, int n) { 42 | long long N = n; 43 | if (N < 0) { 44 | x = 1 / x; 45 | N = abs(N); 46 | } 47 | 48 | return fastPow(x, N); 49 | } 50 | }; -------------------------------------------------------------------------------- /day-108.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Top K Frequent Elements 3 | 4 | Given a non-empty array of integers, return the k most frequent elements. 5 | 6 | Example 1: 7 | 8 | Input: nums = [1,1,1,2,2,3], k = 2 9 | Output: [1,2] 10 | Example 2: 11 | 12 | Input: nums = [1], k = 1 13 | Output: [1] 14 | Note: 15 | 16 | You may assume k is always valid, 1 ≤ k ≤ number of unique elements. 17 | Your algorithm's time complexity must be better than O(n log n), where n is the array's size. 18 | It's guaranteed that the answer is unique, in other words the set of the top k frequent elements is unique. 19 | You can return the answer in any order. 20 | 21 | */ 22 | 23 | // Used unordered_map + max-heap to solve the problem 24 | class Solution { 25 | public: 26 | vector topKFrequent(vector& nums, int k) { 27 | unordered_map hashMap; 28 | 29 | for (int elt : nums) { 30 | hashMap[elt] += 1; 31 | } 32 | 33 | priority_queue> que; 34 | 35 | vector answer(k); 36 | 37 | for (auto& map : hashMap) { 38 | que.push({map.second, map.first}); 39 | } 40 | 41 | for (int i = 0; i < k; i++) { 42 | answer[i] = que.top().second; 43 | que.pop(); 44 | } 45 | 46 | return answer; 47 | } 48 | }; -------------------------------------------------------------------------------- /day-11.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Question: Given a binary tree, you need to compute the length of the diameter of the tree. 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. 3 | 4 | Example: 5 | Given a binary tree 6 | 1 7 | / \ 8 | 2 3 9 | / \ 10 | 4 5 11 | 12 | Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3]. 13 | 14 | Note: The length of path between two nodes is represented by the number of edges between them. 15 | */ 16 | 17 | // O(N) & O(N)(recursion stack internally used.) 18 | class Solution { 19 | public: 20 | int height(TreeNode* root, int& ans) { 21 | if (root == NULL) return 0; 22 | 23 | int leftH = height(root->left, ans); 24 | int rightH = height(root->right, ans); 25 | 26 | ans = max(ans, 1 + leftH + rightH); 27 | return 1 + max(leftH, rightH); 28 | } 29 | 30 | int diameterOfBinaryTree(TreeNode* root) { 31 | if (root == NULL) return 0; 32 | int ans = INT_MIN; 33 | int treeHeight = height(root, ans); 34 | return ans - 1; 35 | } 36 | }; -------------------------------------------------------------------------------- /day-111.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Remove Linked List Elements 3 | 4 | 5 | Remove all elements from a linked list of integers that have value val. 6 | 7 | Example: 8 | 9 | Input: 1->2->6->3->4->5->6, val = 6 10 | Output: 1->2->3->4->5 11 | */ 12 | 13 | // Simple solution manipulating linked list in place O(N) & O(1) 14 | class Solution { 15 | public: 16 | ListNode* removeElements(ListNode* head, int val) { 17 | while (head != NULL && head->val == val) { 18 | head = head->next; 19 | } 20 | 21 | ListNode* customHead = head; 22 | ListNode* prev = NULL; 23 | 24 | while (customHead != NULL && customHead->next != NULL) { 25 | if (customHead->next->val == val) { 26 | customHead->next = customHead->next->next; 27 | } else { 28 | customHead = customHead->next; 29 | } 30 | } 31 | 32 | return head; 33 | } 34 | }; -------------------------------------------------------------------------------- /day-114.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Single Number III 3 | 4 | 5 | Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. 6 | 7 | Example: 8 | 9 | Input: [1,2,1,3,2,5] 10 | Output: [3,5] 11 | Note: 12 | 13 | The order of the result is not important. So in the above example, [5, 3] is also correct. 14 | Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity? 15 | */ 16 | 17 | // Simple O(N) & O(N) solution using hashmap 18 | class Solution { 19 | public: 20 | vector singleNumber(vector& nums) { 21 | unordered_map frequencyTable; 22 | 23 | for (int elt : nums) { 24 | frequencyTable[elt] += 1; 25 | } 26 | 27 | vector answer(2, 0); 28 | int idx = 0; 29 | for (auto& map : frequencyTable) { 30 | if (map.second == 1) { 31 | answer[idx] = map.first; 32 | idx += 1; 33 | } 34 | 35 | if (idx == 2) break; 36 | } 37 | 38 | return answer; 39 | } 40 | }; -------------------------------------------------------------------------------- /day-115.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | All Paths From Source to Target 3 | 4 | 5 | Given a directed, acyclic graph of N nodes. Find all possible paths from node 0 to node N-1, and return them in any order. 6 | 7 | The graph is given as follows: the nodes are 0, 1, ..., graph.length - 1. graph[i] is a list of all nodes j for which the edge (i, j) exists. 8 | 9 | Example: 10 | Input: [[1,2], [3], [3], []] 11 | Output: [[0,1,3],[0,2,3]] 12 | Explanation: The graph looks like this: 13 | 0--->1 14 | | | 15 | v v 16 | 2--->3 17 | There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3. 18 | Note: 19 | 20 | The number of nodes in the graph will be in the range [2, 15]. 21 | You can print different paths in any order, but you should keep the order of nodes inside one path. 22 | 23 | */ 24 | 25 | // Simple DFS solution to calculate all the paths in the graph 26 | class Solution { 27 | public: 28 | void findPathDFS(vector>& graph, vector>& answer, vector& current, int currNode) { 29 | current.push_back(currNode); 30 | if (currNode == graph.size() - 1) 31 | answer.push_back(current); 32 | else { 33 | for (int neighbourNode : graph[currNode]) findPathDFS(graph, answer, current, neighbourNode); 34 | } 35 | current.pop_back(); 36 | } 37 | 38 | vector> allPathsSourceTarget(vector>& graph) { 39 | if (graph.size() == 0) return {}; 40 | vector> answer; 41 | 42 | vector current; 43 | 44 | findPathDFS(graph, answer, current, 0); 45 | 46 | return answer; 47 | } 48 | }; -------------------------------------------------------------------------------- /day-116.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Find Minimum in Rotated Sorted Array II 3 | 4 | 5 | Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. 6 | 7 | (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). 8 | 9 | Find the minimum element. 10 | 11 | The array may contain duplicates. 12 | 13 | Example 1: 14 | 15 | Input: [1,3,5] 16 | Output: 1 17 | Example 2: 18 | 19 | Input: [2,2,2,0,1] 20 | Output: 0 21 | Note: 22 | 23 | This is a follow up problem to Find Minimum in Rotated Sorted Array. 24 | Would allow duplicates affect the run-time complexity? How and why? 25 | */ 26 | 27 | // Binary search approach beats 94% cpp solution 28 | class Solution { 29 | public: 30 | int findMin(vector& nums) { 31 | int low = 0; 32 | int high = nums.size() - 1; 33 | 34 | while (low <= high) { 35 | int mid = low + (high - low) / 2; 36 | 37 | if (nums[high] < nums[mid]) { 38 | low = mid + 1; 39 | } else if (nums[high] > nums[mid]) { 40 | high = mid; 41 | } else { 42 | high -= 1; 43 | } 44 | } 45 | 46 | return nums[low]; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /day-117.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Add Digits 3 | 4 | 5 | Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. 6 | 7 | Example: 8 | 9 | Input: 38 10 | Output: 2 11 | Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2. 12 | Since 2 has only one digit, return it. 13 | Follow up: 14 | Could you do it without any loop/recursion in O(1) runtime? 15 | */ 16 | 17 | // Simple while loop implementation in cpp 18 | 19 | class Solution { 20 | public: 21 | int addDigits(int num) { 22 | int temp = num; 23 | while (temp > 9) { 24 | int answer = 0; 25 | while (temp != 0) { 26 | answer += (temp % 10); 27 | temp /= 10; 28 | } 29 | 30 | temp = answer; 31 | } 32 | 33 | return temp; 34 | } 35 | }; -------------------------------------------------------------------------------- /day-118.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Construct Binary Tree from Inorder and Postorder Traversal 3 | 4 | 5 | 6 | Given inorder and postorder traversal of a tree, construct the binary tree. 7 | 8 | Note: 9 | You may assume that duplicates do not exist in the tree. 10 | 11 | For example, given 12 | 13 | inorder = [9,3,15,20,7] 14 | postorder = [9,15,7,20,3] 15 | Return the following binary tree: 16 | 17 | 3 18 | / \ 19 | 9 20 20 | / \ 21 | 15 7 22 | */ 23 | 24 | // Simple recursive solution to build the tree 25 | class Solution { 26 | public: 27 | TreeNode* buildTreeHelper(vector& inorder, vector& postorder, int inStart, int inEnd, int postEnd) { 28 | if (postEnd < 0 || inStart > inEnd) return NULL; 29 | TreeNode* root = new TreeNode(postorder[postEnd]); 30 | int idx = inStart; 31 | for (; idx < inEnd; idx++) { 32 | if (inorder[idx] == root->val) break; 33 | } 34 | 35 | root->left = buildTreeHelper(inorder, postorder, inStart, idx - 1, postEnd - 1 + idx - inEnd); 36 | root->right = buildTreeHelper(inorder, postorder, idx + 1, inEnd, postEnd - 1); 37 | return root; 38 | } 39 | 40 | TreeNode* buildTree(vector& inorder, vector& postorder) { 41 | return buildTreeHelper(inorder, postorder, 0, inorder.size() - 1, postorder.size() - 1); 42 | } 43 | }; -------------------------------------------------------------------------------- /day-12.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Question: We have a collection of stones, each stone has a positive integer weight. 3 | 4 | Each turn, we choose the two heaviest stones and smash them together. Suppose the stones have weights x and y with x <= y. The result of this smash is: 5 | 6 | If x == y, both stones are totally destroyed; 7 | If x != y, the stone of weight x is totally destroyed, and the stone of weight y has new weight y-x. 8 | At the end, there is at most 1 stone left. Return the weight of this stone (or 0 if there are no stones left.) 9 | 10 | Example 1: 11 | Input: [2,7,4,1,8,1] 12 | Output: 1 13 | */ 14 | 15 | class Solution { 16 | public: 17 | int lastStoneWeight(vector& stones) { 18 | int start = stones.size() - 1; 19 | int stonesCrushed = 0; 20 | sort(stones.begin(), stones.end()); 21 | while (stonesCrushed < (stones.size() - 1)) { 22 | int lar = stones[start]; 23 | int sLar = stones[start - 1]; 24 | int diff = lar - sLar; 25 | if (lar == sLar) { 26 | stonesCrushed += 2; 27 | diff = -1; 28 | } else { 29 | stonesCrushed += 1; 30 | } 31 | 32 | stones[start] = diff; 33 | stones[start - 1] = -1; 34 | sort(stones.begin(), stones.end()); 35 | } 36 | 37 | return stones[start] > 0 ? stones[start] : 0; 38 | } 39 | }; -------------------------------------------------------------------------------- /day-122.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You are climbing a stair case. It takes n steps to reach to the top. 3 | 4 | Each time you can either climb 1 or 2 steps. In how many distinct ways can you 5 | climb to the top? 6 | 7 | Example 1: 8 | 9 | Input: 2 10 | Output: 2 11 | Explanation: There are two ways to climb to the top. 12 | 1. 1 step + 1 step 13 | 2. 2 steps 14 | Example 2: 15 | 16 | Input: 3 17 | Output: 3 18 | Explanation: There are three ways to climb to the top. 19 | 1. 1 step + 1 step + 1 step 20 | 2. 1 step + 2 steps 21 | 3. 2 steps + 1 step 22 | 23 | 24 | Constraints: 25 | 26 | 1 <= n <= 45 27 | 28 | */ 29 | 30 | // Easy dp solution 31 | class Solution { 32 | public: 33 | int climbStairs(int n) { 34 | vector dp(n + 1); 35 | 36 | dp[0] = 1; 37 | dp[1] = 1; 38 | 39 | for (int steps = 2; steps <= n; steps++) { 40 | dp[steps] = dp[steps - 1] + dp[steps - 2]; 41 | } 42 | 43 | return dp[n]; 44 | } 45 | }; -------------------------------------------------------------------------------- /day-123.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Detect Capital 4 | 5 | Given a word, you need to judge whether the usage of capitals in it is right or 6 | not. 7 | 8 | We define the usage of capitals in a word to be right when one of the following 9 | cases holds: 10 | 11 | All letters in this word are capitals, like "USA". 12 | All letters in this word are not capitals, like "leetcode". 13 | Only the first letter in this word is capital, like "Google". 14 | Otherwise, we define that this word doesn't use capitals in a right way. 15 | 16 | 17 | Example 1: 18 | 19 | Input: "USA" 20 | Output: True 21 | 22 | 23 | Example 2: 24 | 25 | Input: "FlaG" 26 | Output: False 27 | 28 | 29 | Note: The input will be a non-empty word consisting of uppercase and lowercase 30 | latin letters. 31 | 32 | 33 | */ 34 | 35 | // Simple O(N) & O(1) solution 36 | class Solution { 37 | public: 38 | bool detectCapitalUse(string word) { 39 | int N = word.length(); 40 | 41 | int numCapitalLetters = 0; 42 | bool firstLetterCapital = false; 43 | 44 | for (int idx = N - 1; idx >= 0; idx--) { 45 | char current = word[idx]; 46 | if (current >= 'A' && current <= 'Z') { 47 | if (idx == 0 && numCapitalLetters == 0) 48 | firstLetterCapital = true; 49 | numCapitalLetters += 1; 50 | } 51 | } 52 | 53 | if (numCapitalLetters == N || numCapitalLetters == 0 || 54 | firstLetterCapital) 55 | return true; 56 | return false; 57 | } 58 | }; -------------------------------------------------------------------------------- /day-124.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Design HashSet 3 | 4 | Design a HashSet without using any built-in hash table libraries. 5 | 6 | To be specific, your design should include these functions: 7 | 8 | add(value): Insert a value into the HashSet. 9 | contains(value) : Return whether the value exists in the HashSet or not. 10 | remove(value): Remove a value in the HashSet. If the value does not exist in the 11 | HashSet, do nothing. 12 | 13 | Example: 14 | 15 | MyHashSet hashSet = new MyHashSet(); 16 | hashSet.add(1); 17 | hashSet.add(2); 18 | hashSet.contains(1); // returns true 19 | hashSet.contains(3); // returns false (not found) 20 | hashSet.add(2); 21 | hashSet.contains(2); // returns true 22 | hashSet.remove(2); 23 | hashSet.contains(2); // returns false (already removed) 24 | 25 | Note: 26 | 27 | All values will be in the range of [0, 1000000]. 28 | The number of operations will be in the range of [1, 10000]. 29 | Please do not use the built-in HashSet library. 30 | */ 31 | 32 | // Easy solution using vector with 1e6 items in it 33 | class MyHashSet { 34 | public: 35 | vector hashSet; 36 | MyHashSet() { hashSet = vector(int(1e6), 0); } 37 | 38 | void add(int key) { 39 | if (hashSet[key]) return; 40 | hashSet[key] = 1; 41 | } 42 | 43 | void remove(int key) { 44 | if (hashSet[key] == 0) return; 45 | hashSet[key] = 0; 46 | } 47 | 48 | /** Returns true if this set contains the specified element */ 49 | bool contains(int key) { 50 | if (hashSet[key]) return true; 51 | return false; 52 | } 53 | }; 54 | -------------------------------------------------------------------------------- /day-125.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Valid Palindrome 3 | 4 | 5 | Given a string, determine if it is a palindrome, considering only alphanumeric 6 | characters and ignoring cases. 7 | 8 | Note: For the purpose of this problem, we define empty string as valid 9 | palindrome. 10 | 11 | Example 1: 12 | 13 | Input: "A man, a plan, a canal: Panama" 14 | Output: true 15 | Example 2: 16 | 17 | Input: "race a car" 18 | Output: false 19 | 20 | 21 | Constraints: 22 | 23 | s consists only of printable ASCII characters. 24 | 25 | */ 26 | 27 | // Solved using O(N) & O(1) approach, beats 89.40% cpp submissions 28 | class Solution { 29 | public: 30 | bool isValidCharacter(char ch) { 31 | if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || 32 | (ch >= '0' && ch <= '9')) { 33 | return true; 34 | } 35 | 36 | return false; 37 | } 38 | 39 | bool isCharacterEqual(char a, char b) { 40 | char aLower = tolower(a); 41 | char bLower = tolower(b); 42 | 43 | if (aLower == bLower) return true; 44 | return false; 45 | } 46 | 47 | bool isPalindrome(string s) { 48 | int start = 0; 49 | int end = s.length() - 1; 50 | int N = end; 51 | while (start < end) { 52 | while ((start <= N) && !isValidCharacter(s[start])) start += 1; 53 | while ((end >= 0) && !isValidCharacter(s[end])) end -= 1; 54 | 55 | if (!(start <= N && end >= 0)) return true; 56 | if (!isCharacterEqual(s[start], s[end])) return false; 57 | start += 1; 58 | end -= 1; 59 | } 60 | 61 | return true; 62 | } 63 | }; -------------------------------------------------------------------------------- /day-126.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Power of Four 3 | 4 | 5 | Given an integer (signed 32 bits), write a function to check whether it is a 6 | power of 4. 7 | 8 | Example 1: 9 | 10 | Input: 16 11 | Output: true 12 | Example 2: 13 | 14 | Input: 5 15 | Output: false 16 | Follow up: Could you solve it without loops/recursion? 17 | 18 | 19 | */ 20 | 21 | // O(1) & O(1) solution beats 100% of cpp solutions 22 | class Solution { 23 | public: 24 | bool isPowerOfFour(int num) { 25 | if (num == 0) return false; 26 | double expo = log(num) / log(4); 27 | if (ceil(expo) == floor(expo)) return true; 28 | return false; 29 | } 30 | }; -------------------------------------------------------------------------------- /day-128.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Find All Duplicates in an Array 3 | 4 | 5 | Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements 6 | appear twice and others appear once. 7 | 8 | Find all the elements that appear twice in this array. 9 | 10 | Could you do it without extra space and in O(n) runtime? 11 | 12 | Example: 13 | Input: 14 | [4,3,2,7,8,2,3,1] 15 | 16 | Output: 17 | [2,3] 18 | */ 19 | 20 | // Solved using O(N) & O(1) approach 21 | class Solution { 22 | public: 23 | vector findDuplicates(vector& nums) { 24 | vector answers; 25 | for (int idx = 0; idx < nums.size(); idx++) { 26 | int currIdx = abs(nums[idx]) - 1; 27 | int currElt = nums[currIdx]; 28 | if (currElt < 0) answers.push_back(abs(nums[idx])); 29 | nums[currIdx] *= -1; 30 | } 31 | 32 | return answers; 33 | } 34 | }; -------------------------------------------------------------------------------- /day-13.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Question: Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1. 3 | 4 | Example 1: 5 | Input: [0,1] 6 | Output: 2 7 | Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1. 8 | Example 2: 9 | Input: [0,1,0] 10 | Output: 2 11 | Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1. 12 | Note: The length of the given binary array will not exceed 50,000. 13 | */ 14 | 15 | class Solution { 16 | public: 17 | int findMaxLength(vector& nums) { 18 | unordered_map hashMap; 19 | hashMap[0] = -1; 20 | int ans = 0; 21 | int curr = 0; 22 | for (int i = 0; i < nums.size(); i++) { 23 | if (nums[i] == 0) { 24 | curr -= 1; 25 | } else { 26 | curr += 1; 27 | } 28 | 29 | if (hashMap.find(curr) != hashMap.end()) { 30 | ans = max(ans, i - hashMap[curr]); 31 | } else { 32 | hashMap[curr] = i; 33 | } 34 | } 35 | 36 | return ans; 37 | } 38 | }; -------------------------------------------------------------------------------- /day-130.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Path Sum III 3 | 4 | 5 | You are given a binary tree in which each node contains an integer value. 6 | 7 | Find the number of paths that sum to a given value. 8 | 9 | The path does not need to start or end at the root or a leaf, but it must go 10 | downwards (traveling only from parent nodes to child nodes). 11 | 12 | The tree has no more than 1,000 nodes and the values are in the range -1,000,000 13 | to 1,000,000. 14 | 15 | Example: 16 | 17 | root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8 18 | 19 | 10 20 | / \ 21 | 5 -3 22 | / \ \ 23 | 3 2 11 24 | / \ \ 25 | 3 -2 1 26 | 27 | Return 3. The paths that sum to 8 are: 28 | 29 | 1. 5 -> 3 30 | 2. 5 -> 2 -> 1 31 | 3. -3 -> 11 32 | */ 33 | 34 | // Simple recursion approach to solve the problem. 35 | // Calling pathSumUtils for each node in the tree 36 | // So we can continue the search for targetSum from each node to bottom of the 37 | // tree 38 | class Solution { 39 | public: 40 | int pathSumUtils(TreeNode* root, int sum) { 41 | if (root == NULL) return 0; 42 | int result = 0; 43 | if (sum == root->val) result += 1; 44 | result += pathSumUtils(root->left, sum - root->val); 45 | result += pathSumUtils(root->right, sum - root->val); 46 | return result; 47 | } 48 | 49 | int pathSum(TreeNode* root, int sum) { 50 | if (root == NULL) return 0; 51 | return pathSum(root->left, sum) + pathSumUtils(root, sum) + 52 | pathSum(root->right, sum); 53 | } 54 | }; -------------------------------------------------------------------------------- /day-132.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Excel Sheet Column Number 3 | 4 | 5 | Given a column title as appear in an Excel sheet, return its corresponding 6 | column number. 7 | 8 | For example: 9 | 10 | A -> 1 11 | B -> 2 12 | C -> 3 13 | ... 14 | Z -> 26 15 | AA -> 27 16 | AB -> 28 17 | ... 18 | Example 1: 19 | 20 | Input: "A" 21 | Output: 1 22 | Example 2: 23 | 24 | Input: "AB" 25 | Output: 28 26 | Example 3: 27 | 28 | Input: "ZY" 29 | Output: 701 30 | 31 | 32 | Constraints: 33 | 34 | 1 <= s.length <= 7 35 | s consists only of uppercase English letters. 36 | s is between "A" and "FXSHRXW". 37 | 38 | */ 39 | 40 | // Simple O(N) brute force solution 41 | class Solution { 42 | public: 43 | int titleToNumber(string s) { 44 | int N = s.length(); 45 | 46 | int multiplier = N - 1; 47 | int answer = 0; 48 | for (int idx = 0; idx < N; idx++) { 49 | int code = s[idx] & 31; 50 | int curr = pow(26, multiplier) * code; 51 | answer += curr; 52 | multiplier -= 1; 53 | } 54 | return answer; 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /day-133.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | H-Index 3 | 4 | 5 | Given an array of citations (each citation is a non-negative integer) of a 6 | researcher, write a function to compute the researcher's h-index. 7 | 8 | According to the definition of h-index on Wikipedia: "A scientist has index h if 9 | h of his/her N papers have at least h citations each, and the other N − h papers 10 | have no more than h citations each." 11 | 12 | Example: 13 | 14 | Input: citations = [3,0,6,1,5] 15 | Output: 3 16 | Explanation: [3,0,6,1,5] means the researcher has 5 papers in total and each of 17 | them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 18 | 3 papers with at least 3 citations each and the remaining two with no more than 19 | 3 citations each, her h-index is 3. Note: If there are several possible values 20 | for h, the maximum one is taken as the h-index. 21 | */ 22 | 23 | // Sorted + Binary Search to solve the problem 24 | class Solution { 25 | public: 26 | int hIndex(vector& citations) { 27 | sort(citations.begin(), citations.end()); 28 | int N = citations.size(); 29 | int start = 0; 30 | int end = N - 1; 31 | 32 | while (start <= end) { 33 | int mid = start + (end - start) / 2; 34 | if (citations[mid] < (N - mid)) { 35 | start = mid + 1; 36 | } else { 37 | end = mid - 1; 38 | } 39 | } 40 | 41 | return N - start; 42 | } 43 | }; -------------------------------------------------------------------------------- /day-134.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Pascal's Triangle II 3 | 4 | 5 | Given a non-negative index k where k ≤ 33, return the kth index row of the 6 | Pascal's triangle. 7 | 8 | Note that the row index starts from 0. 9 | 10 | Example: 11 | 12 | Input: 3 13 | Output: [1,3,3,1] 14 | */ 15 | 16 | // Simple O(row * col) approach 17 | class Solution { 18 | public: 19 | vector getRow(int rowIndex) { 20 | vector answer(rowIndex + 1, 1); 21 | for (int row = 1; row < rowIndex; row++) { 22 | for (int col = row; col > 0; col--) { 23 | answer[col] += answer[col - 1]; 24 | } 25 | } 26 | 27 | return answer; 28 | } 29 | }; -------------------------------------------------------------------------------- /day-136.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Longest Palindrome 3 | 4 | 5 | Given a string which consists of lowercase or uppercase letters, find the length 6 | of the longest palindromes that can be built with those letters. 7 | 8 | This is case sensitive, for example "Aa" is not considered a palindrome here. 9 | 10 | Note: 11 | Assume the length of given string will not exceed 1,010. 12 | 13 | Example: 14 | 15 | Input: 16 | "abccccdd" 17 | 18 | Output: 19 | 7 20 | 21 | Explanation: 22 | One longest palindrome that can be built is "dccaccd", whose length is 7. 23 | 24 | */ 25 | 26 | // Simple O(N) solution. Maintaning a map to store characters, 27 | // then computing length of longest string based on it 28 | 29 | class Solution { 30 | public: 31 | int longestPalindrome(string s) { 32 | unordered_map freqMap; 33 | for (char ch : s) { 34 | freqMap[ch] += 1; 35 | } 36 | 37 | int answer = 0; 38 | bool isOneSeen = false; 39 | 40 | for (auto& map : freqMap) { 41 | int freq = map.second; 42 | if (freq & 1 == 1) { 43 | isOneSeen = true; 44 | freq -= 1; 45 | } 46 | answer += freq; 47 | } 48 | 49 | if (isOneSeen) answer += 1; 50 | return answer; 51 | } 52 | }; -------------------------------------------------------------------------------- /day-137.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Non-overlapping Intervals 3 | 4 | 5 | Given a collection of intervals, find the minimum number of intervals you need 6 | to remove to make the rest of the intervals non-overlapping. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: [[1,2],[2,3],[3,4],[1,3]] 13 | Output: 1 14 | Explanation: [1,3] can be removed and the rest of intervals are non-overlapping. 15 | Example 2: 16 | 17 | Input: [[1,2],[1,2],[1,2]] 18 | Output: 2 19 | Explanation: You need to remove two [1,2] to make the rest of intervals 20 | non-overlapping. Example 3: 21 | 22 | Input: [[1,2],[2,3]] 23 | Output: 0 24 | Explanation: You don't need to remove any of the intervals since they're already 25 | non-overlapping. 26 | 27 | */ 28 | 29 | // Simple sorting based solution O(N * logN) 30 | class Solution { 31 | struct Comp { 32 | bool operator()(const vector& first, const vector& second) { 33 | return (first[0] < second[0]); 34 | } 35 | }; 36 | 37 | public: 38 | int eraseOverlapIntervals(vector>& intervals) { 39 | if (intervals.size() < 2) return 0; 40 | sort(intervals.begin(), intervals.end(), Comp()); 41 | 42 | int count = 0; 43 | int lastIncluded = 0; 44 | 45 | for (int idx = 1; idx < intervals.size(); idx++) { 46 | if (intervals[idx][0] < intervals[lastIncluded][1]) { 47 | count += 1; 48 | if (intervals[idx][1] < intervals[lastIncluded][1]) 49 | lastIncluded = idx; 50 | } else { 51 | lastIncluded = idx; 52 | } 53 | } 54 | 55 | return count; 56 | } 57 | }; -------------------------------------------------------------------------------- /day-142.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Reorder List 3 | 4 | 5 | Given a singly linked list L: L0→L1→…→Ln-1→Ln, 6 | reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… 7 | 8 | You may not modify the values in the list's nodes, only nodes itself may be 9 | changed. 10 | 11 | Example 1: 12 | 13 | Given 1->2->3->4, reorder it to 1->4->2->3. 14 | Example 2: 15 | 16 | Given 1->2->3->4->5, reorder it to 1->5->2->4->3. 17 | 18 | */ 19 | 20 | // Simple O(N) solution. Updated values in list 21 | class Solution { 22 | public: 23 | void reorderList(ListNode* head) { 24 | vector nodeVals; 25 | ListNode* temp = head; 26 | 27 | while (temp != NULL) { 28 | nodeVals.push_back(temp->val); 29 | temp = temp->next; 30 | } 31 | 32 | temp = head; 33 | 34 | int start = 0; 35 | int end = nodeVals.size() - 1; 36 | bool isFront = true; 37 | 38 | while (temp != NULL) { 39 | temp->val = nodeVals[isFront ? start : end]; 40 | temp = temp->next; 41 | if (isFront) 42 | start += 1; 43 | else 44 | end -= 1; 45 | isFront = !isFront; 46 | } 47 | } 48 | }; -------------------------------------------------------------------------------- /day-143.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Sort Array By Parity 3 | 4 | 5 | Given an array A of non-negative integers, return an array consisting of all the 6 | even elements of A, followed by all the odd elements of A. 7 | 8 | You may return any answer array that satisfies this condition. 9 | 10 | 11 | 12 | Example 1: 13 | 14 | Input: [3,1,2,4] 15 | Output: [2,4,3,1] 16 | The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted. 17 | 18 | 19 | Note: 20 | 21 | 1 <= A.length <= 5000 22 | 0 <= A[i] <= 5000 23 | 24 | */ 25 | 26 | // Used two pointer approach to solve this. Beats 88.19 % of cpp submissions. 27 | class Solution { 28 | public: 29 | vector sortArrayByParity(vector& A) { 30 | int evenIndex = 0; 31 | int oddIndex = A.size() - 1; 32 | 33 | while ((evenIndex < oddIndex) && oddIndex >= 0) { 34 | int currentElt = A[evenIndex]; 35 | if ((currentElt & 1) == 1) { 36 | int lastElt = A[oddIndex]; 37 | while ((lastElt & 1) == 1) { 38 | oddIndex -= 1; 39 | if (oddIndex < 0 || oddIndex < evenIndex) break; 40 | lastElt = A[oddIndex]; 41 | } 42 | 43 | if (oddIndex >= 0 && evenIndex < oddIndex) { 44 | A[evenIndex] = lastElt; 45 | A[oddIndex] = currentElt; 46 | oddIndex -= 1; 47 | } 48 | } 49 | 50 | evenIndex += 1; 51 | } 52 | 53 | return A; 54 | } 55 | }; -------------------------------------------------------------------------------- /day-146.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Sum of Left Leaves 3 | 4 | 5 | Find the sum of all left leaves in a given binary tree. 6 | 7 | Example: 8 | 9 | 3 10 | / \ 11 | 9 20 12 | / \ 13 | 15 7 14 | 15 | There are two left leaves in the binary tree, with values 9 and 15 respectively. 16 | Return 24. 17 | 18 | */ 19 | 20 | // Solved using recursion, O(N) time & O(1) memory usage 21 | class Solution { 22 | public: 23 | void leftLeavesHelper(TreeNode* root, int& sum, int flag) { 24 | if (root == NULL) return; 25 | 26 | if (flag == 1 && root->left == NULL && root->right == NULL) 27 | sum += root->val; 28 | 29 | leftLeavesHelper(root->left, sum, 1); 30 | leftLeavesHelper(root->right, sum, 2); 31 | } 32 | 33 | int sumOfLeftLeaves(TreeNode* root) { 34 | int sum = 0; 35 | leftLeavesHelper(root, sum, 0); 36 | return sum; 37 | } 38 | }; -------------------------------------------------------------------------------- /day-148.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Fizz Buzz 3 | 4 | 5 | Write a program that outputs the string representation of numbers from 1 to n. 6 | 7 | But for multiples of three it should output “Fizz” instead of the number and for 8 | the multiples of five output “Buzz”. For numbers which are multiples of both 9 | three and five output “FizzBuzz”. 10 | 11 | 12 | Example: 13 | 14 | n = 15, 15 | 16 | Return: 17 | [ 18 | "1", 19 | "2", 20 | "Fizz", 21 | "4", 22 | "Buzz", 23 | "Fizz", 24 | "7", 25 | "8", 26 | "Fizz", 27 | "Buzz", 28 | "11", 29 | "Fizz", 30 | "13", 31 | "14", 32 | "FizzBuzz" 33 | ] 34 | */ 35 | 36 | // Simple O(N) time & memory solution 37 | class Solution { 38 | public: 39 | vector fizzBuzz(int n) { 40 | vector answers(n); 41 | 42 | for (int num = 1; num <= n; num++) { 43 | if (num % 3 == 0 && num % 5 == 0) 44 | answers[num - 1] = "FizzBuzz"; 45 | else if (num % 3 == 0) 46 | answers[num - 1] = "Fizz"; 47 | else if (num % 5 == 0) 48 | answers[num - 1] = "Buzz"; 49 | else 50 | answers[num - 1] = to_string(num); 51 | } 52 | 53 | return answers; 54 | } 55 | }; -------------------------------------------------------------------------------- /day-15.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Question: Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. 3 | 4 | Example: 5 | 6 | Input: [1,2,3,4] 7 | Output: [24,12,8,6] 8 | Constraint: It's guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer. 9 | 10 | Note: Please solve it without division and in O(n). 11 | */ 12 | 13 | // O(N) & O(1) 14 | class Solution { 15 | public: 16 | vector productExceptSelf(vector& nums) { 17 | int prod = 1; 18 | int zeroes = 0; 19 | for (int i = 0; i < nums.size(); i++) { 20 | if (nums[i] != 0) 21 | prod *= nums[i]; 22 | else 23 | zeroes += 1; 24 | } 25 | 26 | vector ans(nums.size(), 0); 27 | 28 | if (zeroes > 1) return ans; 29 | for (int i = 0; i < nums.size(); i++) { 30 | if (zeroes == 0) { 31 | ans[i] = prod / nums[i]; 32 | } else { 33 | if (nums[i] != 0) 34 | ans[i] = 0; 35 | else 36 | ans[i] = prod; 37 | } 38 | } 39 | 40 | return ans; 41 | } 42 | }; -------------------------------------------------------------------------------- /day-150.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Implement Rand10() Using Rand7() 3 | 4 | 5 | Given a function rand7 which generates a uniform random integer in the range 1 6 | to 7, write a function rand10 which generates a uniform random integer in the 7 | range 1 to 10. 8 | 9 | Do NOT use system's Math.random(). 10 | 11 | 12 | 13 | Example 1: 14 | 15 | Input: 1 16 | Output: [7] 17 | Example 2: 18 | 19 | Input: 2 20 | Output: [8,4] 21 | Example 3: 22 | 23 | Input: 3 24 | Output: [8,1,10] 25 | 26 | 27 | Note: 28 | 29 | rand7 is predefined. 30 | Each testcase has one argument: n, the number of times that rand10 is called. 31 | 32 | 33 | Follow up: 34 | 35 | What is the expected value for the number of calls to rand7() function? 36 | Could you minimize the number of calls to rand7()? 37 | 38 | 39 | */ 40 | 41 | // Used a hack solution using rand() function 42 | class Solution { 43 | public: 44 | int rand10() { return 1 + (rand7() % 10); } 45 | }; -------------------------------------------------------------------------------- /day-154.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Largest Time for Given Digits 3 | 4 | 5 | Given an array of 4 digits, return the largest 24 hour time that can be made. 6 | 7 | The smallest 24 hour time is 00:00, and the largest is 23:59. Starting from 8 | 00:00, a time is larger if more time has elapsed since midnight. 9 | 10 | Return the answer as a string of length 5. If no valid time can be made, return 11 | an empty string. 12 | 13 | 14 | 15 | Example 1: 16 | 17 | Input: [1,2,3,4] 18 | Output: "23:41" 19 | Example 2: 20 | 21 | Input: [5,5,5,5] 22 | Output: "" 23 | 24 | 25 | Note: 26 | 27 | A.length == 4 28 | 0 <= A[i] <= 9 29 | */ 30 | 31 | // Simple O(64) solution, using bruteforce to generate all the possible 32 | // solutions and returning thr largest one 33 | class Solution { 34 | public: 35 | string largestTimeFromDigits(vector& A) { 36 | string answer = ""; 37 | for (int idx = 0; idx < A.size(); idx++) { 38 | for (int jdx = 0; jdx < A.size(); jdx++) { 39 | for (int kdx = 0; kdx < A.size(); kdx++) { 40 | if (idx == jdx || jdx == kdx || kdx == idx) continue; 41 | string hours = to_string(A[idx]) + to_string(A[jdx]); 42 | string minutes = 43 | to_string(A[kdx]) + to_string(A[6 - idx - jdx - kdx]); 44 | string currTime = hours + ":" + minutes; 45 | if (hours < "24" && minutes < "60" && currTime > answer) 46 | answer = currTime; 47 | } 48 | } 49 | } 50 | 51 | return answer; 52 | } 53 | }; -------------------------------------------------------------------------------- /day-156.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Repeated Substring Pattern 3 | 4 | 5 | Given a non-empty string check if it can be constructed by taking a substring of 6 | it and appending multiple copies of the substring together. You may assume the 7 | given string consists of lowercase English letters only and its length will not 8 | exceed 10000. 9 | 10 | 11 | 12 | Example 1: 13 | 14 | Input: "abab" 15 | Output: True 16 | Explanation: It's the substring "ab" twice. 17 | Example 2: 18 | 19 | Input: "aba" 20 | Output: False 21 | Example 3: 22 | 23 | Input: "abcabcabcabc" 24 | Output: True 25 | Explanation: It's the substring "abc" four times. (And the substring "abcabc" 26 | twice.) 27 | 28 | */ 29 | 30 | // Simple approach having time complexity of O(N * K) where K is number of times 31 | // we append the same string 32 | class Solution { 33 | public: 34 | bool repeatedSubstringPattern(string s) { 35 | int N = s.size(); 36 | if (N == 1) return false; 37 | int half = N / 2; 38 | if (N % 2 == 0) half -= 1; 39 | for (int idx = 0; idx <= half; idx++) { 40 | string current = s.substr(0, half - idx + 1); 41 | int times = N / current.size(); 42 | string result = ""; 43 | while (times-- > 0) { 44 | result += current; 45 | } 46 | 47 | if (s == result) return true; 48 | } 49 | 50 | return false; 51 | } 52 | }; -------------------------------------------------------------------------------- /day-16.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Question: Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules: 3 | 4 | Any left parenthesis '(' must have a corresponding right parenthesis ')'. 5 | Any right parenthesis ')' must have a corresponding left parenthesis '('. 6 | Left parenthesis '(' must go before the corresponding right parenthesis ')'. 7 | '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string. 8 | An empty string is also valid. 9 | 10 | 11 | 12 | Example 1: 13 | Input: "()" 14 | Output: True 15 | Example 2: 16 | Input: "(*)" 17 | Output: True 18 | Example 3: 19 | Input: "(*))" 20 | Output: True 21 | Note: 22 | The string size will be in the range [1, 100]. 23 | */ 24 | 25 | // O(N) & O(1) beats 100% cpp solution 26 | class Solution { 27 | public: 28 | bool checkValidString(string s) { 29 | int balance = 0; 30 | for (int i = 0; i < s.length(); i++) { 31 | if (s[i] == ')') 32 | balance -= 1; 33 | else 34 | balance += 1; 35 | 36 | if (balance < 0) return false; 37 | } 38 | 39 | if (balance == 0) return true; 40 | 41 | balance = 0; 42 | for (int i = s.length() - 1; i >= 0; i--) { 43 | if (s[i] == '(') 44 | balance -= 1; 45 | else 46 | balance += 1; 47 | 48 | if (balance < 0) return false; 49 | } 50 | 51 | return true; 52 | } 53 | }; -------------------------------------------------------------------------------- /day-161.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Sum of Root To Leaf Binary Numbers 3 | 4 | 5 | Given a binary tree, each node has value 0 or 1. Each root-to-leaf path 6 | represents a binary number starting with the most significant bit. For example, 7 | if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, 8 | which is 13. 9 | 10 | For all leaves in the tree, consider the numbers represented by the path from 11 | the root to that leaf. 12 | 13 | Return the sum of these numbers. 14 | 15 | 16 | 17 | Example 1: 18 | 19 | 20 | 21 | Input: [1,0,1,0,1,0,1] 22 | Output: 22 23 | Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22 24 | 25 | 26 | Note: 27 | 28 | The number of nodes in the tree is between 1 and 1000. 29 | node.val is 0 or 1. 30 | The answer will not exceed 2^31 - 1. 31 | 32 | 33 | */ 34 | 35 | // Simple recursive solution, to solve the problem 36 | // Beats 84.68 % of cpp submissions. 37 | 38 | class Solution { 39 | public: 40 | int sumRootToLeafHelper(TreeNode* root, int sum) { 41 | if (root == NULL) return 0; 42 | sum = (sum << 1) + root->val; 43 | 44 | if (root->left == NULL && root->right == NULL) return sum; 45 | 46 | return sumRootToLeafHelper(root->left, sum) + 47 | sumRootToLeafHelper(root->right, sum); 48 | } 49 | 50 | int sumRootToLeaf(TreeNode* root) { return sumRootToLeafHelper(root, 0); } 51 | }; -------------------------------------------------------------------------------- /day-164.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Maximum Product Subarray 3 | 4 | 5 | Given an integer array nums, find the contiguous subarray within an array 6 | (containing at least one number) which has the largest product. 7 | 8 | Example 1: 9 | 10 | Input: [2,3,-2,4] 11 | Output: 6 12 | Explanation: [2,3] has the largest product 6. 13 | Example 2: 14 | 15 | Input: [-2,0,-1] 16 | Output: 0 17 | Explanation: The result cannot be 2, because [-2,-1] is not a subarray. 18 | */ 19 | 20 | // Simple O(N) solution, to find the maximum subarray 21 | class Solution { 22 | public: 23 | int maxProduct(vector& nums) { 24 | int currentMax = nums[0]; 25 | int currentMin = nums[0]; 26 | 27 | int finalMaxProd = nums[0]; 28 | for (int idx = 1; idx < nums.size(); idx++) { 29 | if (nums[idx] < 0) swap(currentMax, currentMin); 30 | 31 | currentMax = max(nums[idx], currentMax * nums[idx]); 32 | currentMin = min(nums[idx], currentMin * nums[idx]); 33 | finalMaxProd = max(currentMax, finalMaxProd); 34 | } 35 | 36 | return finalMaxProd; 37 | } 38 | }; -------------------------------------------------------------------------------- /day-165.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Combination Sum III 3 | 4 | 5 | Find all possible combinations of k numbers that add up to a number n, given 6 | that only numbers from 1 to 9 can be used and each combination should be a 7 | unique set of numbers. 8 | 9 | Note: 10 | 11 | All numbers will be positive integers. 12 | The solution set must not contain duplicate combinations. 13 | Example 1: 14 | 15 | Input: k = 3, n = 7 16 | Output: [[1,2,4]] 17 | Example 2: 18 | 19 | Input: k = 3, n = 9 20 | Output: [[1,2,6], [1,3,5], [2,3,4]] 21 | 22 | */ 23 | 24 | // Solved using back tracking and recursion 25 | class Solution { 26 | public: 27 | vector> answer; 28 | void computeAllCombinations(vector& combination, int k, int n, 29 | int start) { 30 | if (k == combination.size()) { 31 | if (n == 0) answer.push_back(combination); 32 | return; 33 | } 34 | 35 | for (int idx = start; idx <= 9; idx++) { 36 | combination.push_back(idx); 37 | computeAllCombinations(combination, k, n - idx, idx + 1); 38 | combination.pop_back(); 39 | } 40 | } 41 | 42 | vector> combinationSum3(int k, int n) { 43 | vector combination; 44 | computeAllCombinations(combination, k, n, 1); 45 | return answer; 46 | } 47 | }; -------------------------------------------------------------------------------- /day-166.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Insert Interval 3 | 4 | 5 | Given a set of non-overlapping intervals, insert a new interval into the 6 | intervals (merge if necessary). 7 | 8 | You may assume that the intervals were initially sorted according to their start 9 | times. 10 | 11 | Example 1: 12 | 13 | Input: intervals = [[1,3],[6,9]], newInterval = [2,5] 14 | Output: [[1,5],[6,9]] 15 | Example 2: 16 | 17 | Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] 18 | Output: [[1,2],[3,10],[12,16]] 19 | Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10]. 20 | NOTE: input types have been changed on April 15, 2019. Please reset to default 21 | code definition to get new method signature. 22 | 23 | */ 24 | 25 | // Simple greedy solution, O(N) approach 26 | class Solution { 27 | public: 28 | vector> insert(vector>& intervals, 29 | vector& newInterval) { 30 | vector> result; 31 | int idx = 0, N = intervals.size(); 32 | while (idx < N && intervals[idx][1] < newInterval[0]) 33 | result.push_back(intervals[idx++]); 34 | 35 | vector inter = newInterval; 36 | while (idx < N && intervals[idx][0] <= newInterval[1]) { 37 | inter[0] = min(inter[0], intervals[idx][0]); 38 | inter[1] = max(inter[1], intervals[idx][1]); 39 | idx += 1; 40 | } 41 | 42 | result.push_back(inter); 43 | 44 | while (idx < N) result.push_back(intervals[idx++]); 45 | 46 | return result; 47 | } 48 | }; -------------------------------------------------------------------------------- /day-167.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | House Robber 3 | 4 | 5 | You are a professional robber planning to rob houses along a street. Each house 6 | has a certain amount of money stashed, the only constraint stopping you from 7 | robbing each of them is that adjacent houses have security system connected and 8 | it will automatically contact the police if two adjacent houses were broken into 9 | on the same night. 10 | 11 | Given a list of non-negative integers representing the amount of money of each 12 | house, determine the maximum amount of money you can rob tonight without 13 | alerting the police. 14 | 15 | 16 | 17 | Example 1: 18 | 19 | Input: nums = [1,2,3,1] 20 | Output: 4 21 | Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). 22 | Total amount you can rob = 1 + 3 = 4. 23 | Example 2: 24 | 25 | Input: nums = [2,7,9,3,1] 26 | Output: 12 27 | Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 28 | (money = 1). Total amount you can rob = 2 + 9 + 1 = 12. 29 | 30 | 31 | Constraints: 32 | 33 | 0 <= nums.length <= 100 34 | 0 <= nums[i] <= 400 35 | 36 | 37 | */ 38 | 39 | // Simple DP problem. O(N) time & memory 40 | class Solution { 41 | public: 42 | int rob(vector& nums) { 43 | int N = nums.size(); 44 | if (N == 0) return 0; 45 | if (N == 1) return nums[0]; 46 | vector dp(N, 0); 47 | dp[0] = nums[0]; 48 | dp[1] = max(dp[0], nums[1]); 49 | 50 | for (int idx = 2; idx < N; idx++) { 51 | dp[idx] = max(dp[idx - 1], nums[idx] + dp[idx - 2]); 52 | } 53 | 54 | return dp[N - 1]; 55 | } 56 | }; -------------------------------------------------------------------------------- /day-168.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Length of Last Word 3 | 4 | 5 | Given a string s consists of upper/lower-case alphabets and empty space 6 | characters ' ', return the length of last word (last word means the last 7 | appearing word if we loop from left to right) in the string. 8 | 9 | If the last word does not exist, return 0. 10 | 11 | Note: A word is defined as a maximal substring consisting of non-space 12 | characters only. 13 | 14 | Example: 15 | 16 | Input: "Hello World" 17 | Output: 5 18 | 19 | */ 20 | 21 | // Simple O(N) time & O(1) memory solution 22 | // Beats 92.11 % of cpp submissions. 23 | 24 | class Solution { 25 | public: 26 | int lengthOfLastWord(string s) { 27 | int N = s.length(); 28 | int start = N - 1; 29 | int answer = 0; 30 | while (start >= 0 && s[start] == ' ') start -= 1; 31 | if (start < 0) return answer; 32 | while (start >= 0 && s[start] != ' ') { 33 | answer += 1; 34 | start -= 1; 35 | } 36 | 37 | return answer; 38 | } 39 | }; -------------------------------------------------------------------------------- /day-17.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Question: Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. 3 | 4 | Example 1: 5 | 6 | Input: 7 | 11110 8 | 11010 9 | 11000 10 | 00000 11 | 12 | Output: 1 13 | Example 2: 14 | 15 | Input: 16 | 11000 17 | 11000 18 | 00100 19 | 00011 20 | 21 | Output: 3 22 | */ 23 | 24 | // O(N*N) & O(1) solution Beats 90.99 % of cpp submissions. 25 | class Solution { 26 | public: 27 | int dfs(vector>& grid, int i, int j) { 28 | if (i < 0 || i >= grid.size() || j < 0 || j >= grid[i].size() || grid[i][j] == '0') return 0; 29 | 30 | grid[i][j] = '0'; 31 | dfs(grid, i + 1, j); 32 | dfs(grid, i - 1, j); 33 | dfs(grid, i, j + 1); 34 | dfs(grid, i, j - 1); 35 | return 1; 36 | } 37 | 38 | int numIslands(vector>& grid) { 39 | if (grid.size() == 0) return 0; 40 | 41 | int ans = 0; 42 | for (int i = 0; i < grid.size(); i++) { 43 | for (int j = 0; j < grid[i].size(); j++) { 44 | if (grid[i][j] == '1') { 45 | ans += dfs(grid, i, j); 46 | } 47 | } 48 | } 49 | return ans; 50 | } 51 | }; -------------------------------------------------------------------------------- /day-171.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Best Time to Buy and Sell Stock 3 | 4 | 5 | Say you have an array for which the ith element is the price of a given stock on 6 | day i. 7 | 8 | If you were only permitted to complete at most one transaction (i.e., buy one 9 | and sell one share of the stock), design an algorithm to find the maximum 10 | profit. 11 | 12 | Note that you cannot sell a stock before you buy one. 13 | 14 | Example 1: 15 | 16 | Input: [7,1,5,3,6,4] 17 | Output: 5 18 | Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 19 | 6-1 = 5. Not 7-1 = 6, as selling price needs to be larger than buying price. 20 | Example 2: 21 | 22 | Input: [7,6,4,3,1] 23 | Output: 0 24 | Explanation: In this case, no transaction is done, i.e. max profit = 0. 25 | 26 | */ 27 | 28 | // Simple O(N) approach, keeping track of minPrice and totalMaxPrice we got 29 | class Solution { 30 | public: 31 | int maxProfit(vector& prices) { 32 | int N = prices.size(); 33 | if (N < 2) return 0; 34 | int maxProfit = 0; 35 | int minPrice = prices[0]; 36 | 37 | for (int idx = 1; idx < N; idx++) { 38 | maxProfit = max(maxProfit, prices[idx] - minPrice); 39 | minPrice = min(minPrice, prices[idx]); 40 | } 41 | 42 | return maxProfit; 43 | } 44 | }; -------------------------------------------------------------------------------- /day-172.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Sequential Digits 3 | 4 | 5 | An integer has sequential digits if and only if each digit in the number is one 6 | more than the previous digit. 7 | 8 | Return a sorted list of all the integers in the range [low, high] inclusive that 9 | have sequential digits. 10 | 11 | 12 | 13 | Example 1: 14 | 15 | Input: low = 100, high = 300 16 | Output: [123,234] 17 | Example 2: 18 | 19 | Input: low = 1000, high = 13000 20 | Output: [1234,2345,3456,4567,5678,6789,12345] 21 | 22 | 23 | Constraints: 24 | 25 | 10 <= low <= high <= 10^9 26 | 27 | */ 28 | 29 | // O(N) solution, based on length of low number and high number 30 | class Solution { 31 | public: 32 | vector sequentialDigits(int low, int high) { 33 | vector answer; 34 | string sequentialDigits = "123456789"; 35 | int lowLen = to_string(low).length(); 36 | int highLen = to_string(high).length(); 37 | 38 | for (int len = lowLen; len <= highLen; len++) { 39 | for (int idx = 0; idx <= 9 - len; idx++) { 40 | string currentNum = sequentialDigits.substr(idx, len); 41 | int num = stoi(currentNum); 42 | if (num < low) continue; 43 | if (num > high) break; 44 | answer.push_back(num); 45 | } 46 | } 47 | 48 | return answer; 49 | } 50 | }; -------------------------------------------------------------------------------- /day-175.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Majority Element II 3 | 4 | 5 | Given an integer array of size n, find all elements that appear more than ⌊ n/3 6 | ⌋ times. 7 | 8 | Note: The algorithm should run in linear time and in O(1) space. 9 | 10 | Example 1: 11 | 12 | Input: [3,2,3] 13 | Output: [3] 14 | Example 2: 15 | 16 | Input: [1,1,1,3,3,2,2,2] 17 | Output: [1,2] 18 | */ 19 | 20 | // Simple O(N) & O(N) solution 21 | class Solution { 22 | public: 23 | vector majorityElement(vector& nums) { 24 | unordered_map hashMap; 25 | 26 | int N = nums.size(); 27 | int threshold = N / 3; 28 | 29 | vector answer; 30 | for (int idx = 0; idx < nums.size(); idx++) { 31 | hashMap[nums[idx]] += 1; 32 | } 33 | 34 | for (auto& map : hashMap) { 35 | if (map.second > threshold) answer.push_back(map.first); 36 | } 37 | 38 | return answer; 39 | } 40 | }; -------------------------------------------------------------------------------- /day-177.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Find the Difference 3 | 4 | 5 | Given two strings s and t which consist of only lowercase letters. 6 | 7 | String t is generated by random shuffling string s and then add one more letter 8 | at a random position. 9 | 10 | Find the letter that was added in t. 11 | 12 | Example: 13 | 14 | Input: 15 | s = "abcd" 16 | t = "abcde" 17 | 18 | Output: 19 | e 20 | 21 | Explanation: 22 | 'e' is the letter that was added. 23 | */ 24 | 25 | // Simple hashMap solution, beats 96.78 % of cpp submissions. 26 | 27 | class Solution { 28 | public: 29 | char findTheDifference(string s, string t) { 30 | ios_base::sync_with_stdio(false); 31 | cin.tie(NULL); 32 | 33 | unordered_map hashMap; 34 | int sLen = s.length(); 35 | int tLen = t.length(); 36 | 37 | for (int idx = 0; idx < tLen; idx++) { 38 | hashMap[t[idx]] += 1; 39 | if (idx < sLen) hashMap[s[idx]] -= 1; 40 | } 41 | 42 | for (auto& map : hashMap) { 43 | if (map.second == 1) return map.first; 44 | } 45 | 46 | return 'z'; 47 | } 48 | }; -------------------------------------------------------------------------------- /day-178.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Largest Number 4 | 5 | Given a list of non negative integers, arrange them such that they form the 6 | largest number. 7 | 8 | Example 1: 9 | 10 | Input: [10,2] 11 | Output: "210" 12 | Example 2: 13 | 14 | Input: [3,30,34,5,9] 15 | Output: "9534330" 16 | Note: The result may be very large, so you need to return a string instead of an 17 | integer. 18 | 19 | */ 20 | 21 | bool compare(string numA, string numB) { return (numA + numB) > (numB + numA); } 22 | 23 | // Solved using comparator function 24 | // Beats 92.19 % of cpp submissions. 25 | 26 | class Solution { 27 | public: 28 | string largestNumber(vector& nums) { 29 | int N = nums.size(); 30 | vector numsStr(N); 31 | 32 | for (int idx = 0; idx < N; idx++) { 33 | numsStr[idx] = to_string(nums[idx]); 34 | } 35 | 36 | sort(numsStr.begin(), numsStr.end(), compare); 37 | 38 | string answer = ""; 39 | for (int idx = 0; idx < N; idx++) answer += numsStr[idx]; 40 | 41 | if (answer[0] == '0') return "0"; 42 | return answer; 43 | } 44 | }; -------------------------------------------------------------------------------- /day-18.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Question: 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. 3 | 4 | Note: You can only move either down or right at any point in time. 5 | 6 | Example: 7 | 8 | Input: 9 | [ 10 | [1,3,1], 11 | [1,5,1], 12 | [4,2,1] 13 | ] 14 | Output: 7 15 | Explanation: Because the path 1→3→1→1→1 minimizes the sum. 16 | */ 17 | 18 | // O(N) & O(1) beats 85% of cpp solutions 19 | 20 | class Solution { 21 | public: 22 | int minPathSum(vector>& grid) { 23 | for (int i = 1; i < grid.size(); ++i) { 24 | grid[i][0] += grid[i - 1][0]; 25 | } 26 | 27 | for (int i = 1; i < grid[0].size(); ++i) { 28 | grid[0][i] += grid[0][i - 1]; 29 | } 30 | 31 | for (int i = 1; i < grid.size(); ++i) { 32 | for (int j = 1; j < grid[i].size(); ++j) { 33 | grid[i][j] += min(grid[i - 1][j], grid[i][j - 1]); 34 | } 35 | } 36 | 37 | return grid[grid.size() - 1][grid[0].size() - 1]; 38 | } 39 | }; -------------------------------------------------------------------------------- /day-181.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Subarray Product Less Than K 3 | 4 | 5 | Your are given an array of positive integers nums. 6 | 7 | Count and print the number of (contiguous) subarrays where the product of all 8 | the elements in the subarray is less than k. 9 | 10 | Example 1: 11 | Input: nums = [10, 5, 2, 6], k = 100 12 | Output: 8 13 | Explanation: The 8 subarrays that have product less than 100 are: [10], [5], 14 | [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]. Note that [10, 5, 2] is not 15 | included as the product of 100 is not strictly less than k. Note: 16 | 17 | 0 < nums.length <= 50000. 18 | 0 < nums[i] < 1000. 19 | 0 <= k < 10^6. 20 | 21 | */ 22 | 23 | // Solved using sliding window approach 24 | class Solution { 25 | public: 26 | int numSubarrayProductLessThanK(vector& nums, int k) { 27 | if (k == 0) return 0; 28 | int end = nums.size(); 29 | int product = 1; 30 | int answer = 0; 31 | 32 | int left = 0; 33 | int right = 0; 34 | 35 | while (right < end) { 36 | product *= nums[right]; 37 | 38 | while (left <= right && product >= k) { 39 | product /= nums[left]; 40 | left += 1; 41 | } 42 | 43 | answer += right - left + 1; 44 | right += 1; 45 | } 46 | 47 | return answer; 48 | } 49 | }; -------------------------------------------------------------------------------- /day-182.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Word Break 4 | 5 | Given a non-empty string s and a dictionary wordDict containing a list of 6 | non-empty words, determine if s can be segmented into a space-separated sequence 7 | of one or more dictionary words. 8 | 9 | Note: 10 | 11 | The same word in the dictionary may be reused multiple times in the 12 | segmentation. You may assume the dictionary does not contain duplicate words. 13 | Example 1: 14 | 15 | Input: s = "leetcode", wordDict = ["leet", "code"] 16 | Output: true 17 | Explanation: Return true because "leetcode" can be segmented as "leet code". 18 | Example 2: 19 | 20 | Input: s = "applepenapple", wordDict = ["apple", "pen"] 21 | Output: true 22 | Explanation: Return true because "applepenapple" can be segmented as "apple pen 23 | apple". Note that you are allowed to reuse a dictionary word. Example 3: 24 | 25 | Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"] 26 | Output: false 27 | 28 | */ 29 | 30 | // Solved using hash map 31 | 32 | class Solution { 33 | public: 34 | bool wordBreak(string s, vector& wordDict) { 35 | int len = s.size(); 36 | 37 | vector dp(len + 1, false); 38 | 39 | dp[0] = true; 40 | 41 | for (int i = 1; i <= len; i++) { 42 | for (int j = 0; j < i; j++) { 43 | if ((dp[j]) && (find(wordDict.begin(), wordDict.end(), 44 | s.substr(j, i - j)) != wordDict.end())) { 45 | dp[i] = true; 46 | break; 47 | } 48 | } 49 | } 50 | 51 | return dp.back(); 52 | } 53 | }; -------------------------------------------------------------------------------- /day-183.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | First Missing Positive 3 | 4 | Solution 5 | Given an unsorted integer array, find the smallest missing positive integer. 6 | 7 | Example 1: 8 | 9 | Input: [1,2,0] 10 | Output: 3 11 | Example 2: 12 | 13 | Input: [3,4,-1,1] 14 | Output: 2 15 | Example 3: 16 | 17 | Input: [7,8,9,11,12] 18 | Output: 1 19 | Follow up: 20 | 21 | Your algorithm should run in O(n) time and uses constant extra space. 22 | */ 23 | 24 | // Solved using hashMap and single iteration 25 | // beats 83% cpp solution 26 | 27 | class Solution { 28 | public: 29 | int firstMissingPositive(vector& nums) { 30 | ios_base::sync_with_stdio(false); 31 | cin.tie(NULL); 32 | 33 | int N = nums.size(); 34 | unordered_map hashMap; 35 | 36 | int minVal = INT_MAX; 37 | int maxVal = INT_MIN; 38 | 39 | for (int idx = 0; idx < N; idx++) { 40 | hashMap[nums[idx]] += 1; 41 | 42 | minVal = min(minVal, nums[idx]); 43 | maxVal = max(maxVal, nums[idx]); 44 | } 45 | 46 | if (minVal <= 0) minVal = 1; 47 | if (minVal > 1) return 1; 48 | 49 | for (int num = minVal; num <= maxVal; num++) { 50 | if (num > 0 && hashMap[num] == 0) return num; 51 | } 52 | 53 | return (maxVal < 0 ? 1 : maxVal + 1); 54 | } 55 | }; -------------------------------------------------------------------------------- /day-188.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Complement of Base 10 Integer 3 | 4 | 5 | Every non-negative integer N has a binary representation. For example, 5 can be 6 | represented as "101" in binary, 11 as "1011" in binary, and so on. Note that 7 | except for N = 0, there are no leading zeroes in any binary representation. 8 | 9 | The complement of a binary representation is the number in binary you get when 10 | changing every 1 to a 0 and 0 to a 1. For example, the complement of "101" in 11 | binary is "010" in binary. 12 | 13 | For a given number N in base-10, return the complement of it's binary 14 | representation as a base-10 integer. 15 | 16 | 17 | 18 | Example 1: 19 | 20 | Input: 5 21 | Output: 2 22 | Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 23 | in base-10. Example 2: 24 | 25 | Input: 7 26 | Output: 0 27 | Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 28 | in base-10. Example 3: 29 | 30 | Input: 10 31 | Output: 5 32 | Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 33 | 5 in base-10. 34 | 35 | 36 | */ 37 | 38 | class Solution { 39 | public: 40 | int bitwiseComplement(int N) { 41 | if (N == 0) return 1; 42 | int numBits = floor(log2(N) + 1); 43 | return ((1 << numBits) - 1) ^ N; 44 | } 45 | }; -------------------------------------------------------------------------------- /day-189.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Insert into a Binary Search Tree 3 | 4 | 5 | You are given the root node of a binary search tree (BST) and a value to insert 6 | into the tree. Return the root node of the BST after the insertion. It is 7 | guaranteed that the new value does not exist in the original BST. 8 | 9 | Notice that there may exist multiple valid ways for the insertion, as long as 10 | the tree remains a BST after insertion. You can return any of them. 11 | 12 | 13 | 14 | Example 1: 15 | 16 | 17 | Input: root = [4,2,7,1,3], val = 5 18 | Output: [4,2,7,1,3,5] 19 | Explanation: Another accepted tree is: 20 | 21 | Example 2: 22 | 23 | Input: root = [40,20,60,10,30,50,70], val = 25 24 | Output: [40,20,60,10,30,50,70,null,null,25] 25 | Example 3: 26 | 27 | Input: root = [4,2,7,1,3,null,null,null,null,null,null], val = 5 28 | Output: [4,2,7,1,3,5] 29 | 30 | */ 31 | 32 | // Simple solution using recursion 33 | class Solution { 34 | public: 35 | TreeNode* insertIntoBST(TreeNode* root, int val) { 36 | if (!root) return new TreeNode(val); 37 | 38 | if (val > root->val) { 39 | root->right = insertIntoBST(root->right, val); 40 | } else { 41 | root->left = insertIntoBST(root->left, val); 42 | } 43 | return root; 44 | } 45 | }; -------------------------------------------------------------------------------- /day-190.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Rotate List 3 | 4 | 5 | Given a linked list, rotate the list to the right by k places, where k is 6 | non-negative. 7 | 8 | Example 1: 9 | 10 | Input: 1->2->3->4->5->NULL, k = 2 11 | Output: 4->5->1->2->3->NULL 12 | Explanation: 13 | rotate 1 steps to the right: 5->1->2->3->4->NULL 14 | rotate 2 steps to the right: 4->5->1->2->3->NULL 15 | Example 2: 16 | 17 | Input: 0->1->2->NULL, k = 4 18 | Output: 2->0->1->NULL 19 | Explanation: 20 | rotate 1 steps to the right: 2->0->1->NULL 21 | rotate 2 steps to the right: 1->2->0->NULL 22 | rotate 3 steps to the right: 0->1->2->NULL 23 | rotate 4 steps to the right: 2->0->1->NULL 24 | */ 25 | 26 | // Simple O(N) solution updating values not reference 27 | class Solution { 28 | public: 29 | ListNode* rotateRight(ListNode* head, int k) { 30 | vector elements; 31 | 32 | ListNode* temp = head; 33 | 34 | while (temp != NULL) { 35 | elements.push_back(temp->val); 36 | temp = temp->next; 37 | } 38 | 39 | int N = elements.size(); 40 | vector rotatedElements(N); 41 | 42 | for (int idx = 0; idx < N; idx++) { 43 | int pos = (idx + k) % N; 44 | rotatedElements[pos] = elements[idx]; 45 | } 46 | 47 | temp = head; 48 | int idx = 0; 49 | while (temp != NULL) { 50 | temp->val = rotatedElements[idx]; 51 | idx += 1; 52 | temp = temp->next; 53 | } 54 | 55 | return head; 56 | } 57 | }; -------------------------------------------------------------------------------- /day-191.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Binary Search 4 | 5 | 6 | Given a sorted (in ascending order) integer array nums of n elements and a 7 | target value, write a function to search target in nums. If target exists, then 8 | return its index, otherwise return -1. 9 | 10 | 11 | Example 1: 12 | 13 | Input: nums = [-1,0,3,5,9,12], target = 9 14 | Output: 4 15 | Explanation: 9 exists in nums and its index is 4 16 | 17 | Example 2: 18 | 19 | Input: nums = [-1,0,3,5,9,12], target = 2 20 | Output: -1 21 | Explanation: 2 does not exist in nums so return -1 22 | 23 | 24 | Note: 25 | 26 | You may assume that all elements in nums are unique. 27 | n will be in the range [1, 10000]. 28 | The value of each element in nums will be in the range [-9999, 9999]. 29 | 30 | */ 31 | 32 | // Simple O(log N) binary search 33 | 34 | class Solution { 35 | public: 36 | int search(vector& nums, int target) { 37 | int N = nums.size(); 38 | int low = 0; 39 | int high = N; 40 | 41 | while (low <= high) { 42 | int mid = low + (high - low) / 2; 43 | if (target > nums[mid]) { 44 | low = mid + 1; 45 | } else if (target == nums[mid]) { 46 | return mid; 47 | } else { 48 | high = mid - 1; 49 | } 50 | } 51 | 52 | return -1; 53 | } 54 | }; -------------------------------------------------------------------------------- /day-194.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Remove Duplicate Letters 3 | 4 | Given a string s, remove duplicate letters so that every letter appears once and 5 | only once. You must make sure your result is the smallest in lexicographical 6 | order among all possible results. 7 | 8 | 9 | Example 1: 10 | 11 | Input: s = "bcabc" 12 | Output: "abc" 13 | Example 2: 14 | 15 | Input: s = "cbacdcbc" 16 | Output: "acdb" 17 | 18 | 19 | Constraints: 20 | 21 | 1 <= s.length <= 104 22 | s consists of lowercase English letters. 23 | 24 | */ 25 | 26 | // O(N) stack based solution 27 | class Solution { 28 | public: 29 | string removeDuplicateLetters(string s) { 30 | string result = ""; 31 | unordered_set letters; 32 | vector freq(26, 0); 33 | for (char ch : s) { 34 | freq[ch - 97]++; 35 | } 36 | for (int idx = 0; idx < s.size(); idx++) { 37 | freq[s[idx] - 97]--; 38 | if (letters.count(s[idx])) { 39 | continue; 40 | } 41 | while (result.size() > 0 && s[idx] < result.back() && 42 | freq[result.back() - 97] > 0) { 43 | letters.erase(result.back()); 44 | result.pop_back(); 45 | } 46 | result.push_back(s[idx]); 47 | letters.insert(s[idx]); 48 | } 49 | return result; 50 | } 51 | }; -------------------------------------------------------------------------------- /day-196.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Sort List 3 | 4 | 5 | Given the head of a linked list, return the list after sorting it in ascending 6 | order. 7 | 8 | Follow up: Can you sort the linked list in O(n logn) time and O(1) memory (i.e. 9 | constant space)? 10 | 11 | 12 | 13 | Example 1: 14 | 15 | 16 | Input: head = [4,2,1,3] 17 | Output: [1,2,3,4] 18 | Example 2: 19 | 20 | 21 | Input: head = [-1,5,3,4,0] 22 | Output: [-1,0,3,4,5] 23 | Example 3: 24 | 25 | Input: head = [] 26 | Output: [] 27 | 28 | 29 | Constraints: 30 | 31 | The number of nodes in the list is in the range [0, 5 * 104]. 32 | -105 <= Node.val <= 105 33 | 34 | */ 35 | 36 | // Simple O(NlogN) and O(N) solution 37 | class Solution { 38 | public: 39 | ListNode* sortList(ListNode* head) { 40 | vector vals; 41 | ListNode* temp = head; 42 | 43 | while (temp != NULL) { 44 | vals.push_back(temp->val); 45 | temp = temp->next; 46 | } 47 | 48 | temp = head; 49 | sort(vals.begin(), vals.end()); 50 | int idx = 0; 51 | while (temp != NULL) { 52 | temp->val = vals[idx]; 53 | temp = temp->next; 54 | idx += 1; 55 | } 56 | 57 | return head; 58 | } 59 | }; -------------------------------------------------------------------------------- /day-198.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Rotate Array 3 | 4 | 5 | Given an array, rotate the array to the right by k steps, where k is 6 | non-negative. 7 | 8 | Follow up: 9 | 10 | Try to come up as many solutions as you can, there are at least 3 different ways 11 | to solve this problem. Could you do it in-place with O(1) extra space? 12 | 13 | 14 | Example 1: 15 | 16 | Input: nums = [1,2,3,4,5,6,7], k = 3 17 | Output: [5,6,7,1,2,3,4] 18 | Explanation: 19 | rotate 1 steps to the right: [7,1,2,3,4,5,6] 20 | rotate 2 steps to the right: [6,7,1,2,3,4,5] 21 | rotate 3 steps to the right: [5,6,7,1,2,3,4] 22 | Example 2: 23 | 24 | Input: nums = [-1,-100,3,99], k = 2 25 | Output: [3,99,-1,-100] 26 | Explanation: 27 | rotate 1 steps to the right: [99,-1,-100,3] 28 | rotate 2 steps to the right: [3,99,-1,-100] 29 | 30 | 31 | Constraints: 32 | 33 | 1 <= nums.length <= 2 * 104 34 | -231 <= nums[i] <= 231 - 1 35 | 0 <= k <= 105 36 | 37 | */ 38 | 39 | // Simple extra memory solution and O(N) time 40 | class Solution { 41 | public: 42 | void rotate(vector& nums, int k) { 43 | int N = nums.size(); 44 | 45 | vector answers(N); 46 | 47 | for (int idx = 0; idx < N; idx++) { 48 | int tarPos = (idx + k) % N; 49 | answers[tarPos] = nums[idx]; 50 | } 51 | 52 | nums = answers; 53 | } 54 | }; -------------------------------------------------------------------------------- /day-199.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Search a 2D Matrix 3 | 4 | 5 | Write an efficient algorithm that searches for a value in an m x n matrix. This 6 | matrix has the following properties: 7 | 8 | Integers in each row are sorted from left to right. 9 | The first integer of each row is greater than the last integer of the previous 10 | row. 11 | 12 | 13 | Example 1: 14 | 15 | 16 | Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,50]], target = 3 17 | Output: true 18 | Example 2: 19 | 20 | 21 | Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,50]], target = 13 22 | Output: false 23 | Example 3: 24 | 25 | Input: matrix = [], target = 0 26 | Output: false 27 | 28 | 29 | Constraints: 30 | 31 | m == matrix.length 32 | n == matrix[i].length 33 | 0 <= m, n <= 100 34 | -104 <= matrix[i][j], target <= 104 35 | 36 | */ 37 | 38 | // Simple approach using binary search on both rows and cols 39 | // Time Complexity O(rows + cols) 40 | 41 | class Solution { 42 | public: 43 | bool searchMatrix(vector>& matrix, int target) { 44 | int rows = matrix.size(); 45 | if (rows == 0) return false; 46 | 47 | int row = 0; 48 | int cols = matrix[0].size() - 1; 49 | 50 | while (row < rows && cols >= 0) { 51 | if (matrix[row][cols] == target) 52 | return true; 53 | else if (target < matrix[row][cols]) 54 | cols -= 1; 55 | else 56 | row += 1; 57 | } 58 | 59 | return false; 60 | } 61 | }; -------------------------------------------------------------------------------- /day-2.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | Question: Write an algorithm to determine if a number is "happy". 3 | 4 | A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. 5 | **/ 6 | 7 | // O(N) & O(N) 8 | class Solution { 9 | public: 10 | bool isHappy(int n) { 11 | map hashMap; 12 | hashMap[n] = 1; 13 | int result = 0; 14 | 15 | while (result != 1 && n != 1) { 16 | result = 0; 17 | while (n != 0) { 18 | int digit = n % 10; 19 | result += (digit * digit); 20 | n /= 10; 21 | } 22 | n = result; 23 | if (hashMap[n] == 1) { 24 | result = -1; 25 | break; 26 | } 27 | hashMap[n] = 1; 28 | } 29 | 30 | if (result == -1) return false; 31 | return true; 32 | } 33 | }; -------------------------------------------------------------------------------- /day-20.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Question: Return the root node of a binary search tree that matches the given preorder traversal. 3 | 4 | (Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val. Also recall that a preorder traversal displays the value of the node first, then traverses node.left, then traverses node.right.) 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: [8,5,1,7,10,12] 11 | Output: [8,5,10,1,7,null,12] 12 | 13 | */ 14 | class Solution { 15 | public: 16 | TreeNode* buildTree(vector& preorder, int low, int high) { 17 | if (low > high) return nullptr; 18 | TreeNode* root = new TreeNode(preorder[low]); 19 | if (low == high) return root; 20 | int idx = low + 1; 21 | while (idx <= high && preorder[idx] < preorder[low]) idx += 1; 22 | root->left = buildTree(preorder, low + 1, idx - 1); 23 | root->right = buildTree(preorder, idx, high); 24 | return root; 25 | } 26 | 27 | TreeNode* bstFromPreorder(vector& preorder) { 28 | return buildTree(preorder, 0, preorder.size() - 1); 29 | } 30 | }; -------------------------------------------------------------------------------- /day-200.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Repeated DNA Sequences 3 | 4 | 5 | All DNA is composed of a series of nucleotides abbreviated as 'A', 'C', 'G', and 6 | 'T', for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to 7 | identify repeated sequences within the DNA. 8 | 9 | Write a function to find all the 10-letter-long sequences (substrings) that 10 | occur more than once in a DNA molecule. 11 | 12 | 13 | 14 | Example 1: 15 | 16 | Input: s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" 17 | Output: ["AAAAACCCCC","CCCCCAAAAA"] 18 | Example 2: 19 | 20 | Input: s = "AAAAAAAAAAAAA" 21 | Output: ["AAAAAAAAAA"] 22 | 23 | 24 | Constraints: 25 | 26 | 0 <= s.length <= 105 27 | s[i] is 'A', 'C', 'G', or 'T'. 28 | */ 29 | 30 | // Simple hash map solution, by generating substrings of length 10 31 | class Solution { 32 | public: 33 | vector findRepeatedDnaSequences(string s) { 34 | int N = s.size(); 35 | 36 | if (N < 10) return {}; 37 | 38 | vector answer; 39 | unordered_map hashMap; 40 | int idx = 0; 41 | 42 | while ((idx + 10) <= N) { 43 | string currStr = s.substr(idx, 10); 44 | hashMap[currStr] += 1; 45 | idx += 1; 46 | 47 | if (hashMap[currStr] == 2) answer.push_back(currStr); 48 | } 49 | 50 | return answer; 51 | } 52 | }; -------------------------------------------------------------------------------- /day-201.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Best Time to Buy and Sell Stock IV 3 | 4 | 5 | You are given an integer array prices where prices[i] is the price of a given 6 | stock on the ith day. 7 | 8 | Design an algorithm to find the maximum profit. You may complete at most k 9 | transactions. 10 | 11 | Notice that you may not engage in multiple transactions simultaneously (i.e., 12 | you must sell the stock before you buy again). 13 | 14 | 15 | 16 | Example 1: 17 | 18 | Input: k = 2, prices = [2,4,1] 19 | Output: 2 20 | Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 21 | 4-2 = 2. Example 2: 22 | 23 | Input: k = 2, prices = [3,2,6,5,0,3] 24 | Output: 7 25 | Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 26 | 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 27 | 3-0 = 3. 28 | 29 | 30 | Constraints: 31 | 32 | 0 <= k <= 109 33 | 0 <= prices.length <= 104 34 | 0 <= prices[i] <= 1000 35 | 36 | */ 37 | 38 | // Solved using DP 39 | class Solution { 40 | public: 41 | int maxProfit(int k, vector& prices) { 42 | int len = prices.size(); 43 | if (!k || len < 2) return 0; 44 | k = min(k * 2, len - len % 2); 45 | int dp[k]; 46 | for (int i = 0; i < k; i++) dp[i] = i % 2 ? 0 : INT_MAX; 47 | for (int currPrice : prices) { 48 | dp[0] = min(dp[0], currPrice); 49 | for (int i = 1; i < k; i++) { 50 | dp[i] = i % 2 ? max(dp[i], currPrice - dp[i - 1]) 51 | : min(dp[i], currPrice - dp[i - 1]); 52 | } 53 | } 54 | return dp[k - 1]; 55 | } 56 | }; -------------------------------------------------------------------------------- /day-205.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Minimum Depth of Binary Tree 3 | 4 | Given a binary tree, find its minimum depth. 5 | 6 | The minimum depth is the number of nodes along the shortest path from the root 7 | node down to the nearest leaf node. 8 | 9 | Note: A leaf is a node with no children. 10 | 11 | 12 | Input: root = [3,9,20,null,null,15,7] 13 | Output: 2 14 | Example 2: 15 | 16 | Input: root = [2,null,3,null,4,null,5,null,6] 17 | Output: 5 18 | 19 | 20 | Constraints: 21 | 22 | The number of nodes in the tree is in the range [0, 105]. 23 | -1000 <= Node.val <= 1000 24 | 25 | */ 26 | 27 | // Simple recursive solution 28 | class Solution { 29 | public: 30 | void minDepthHelper(TreeNode* root, int& minDepthCount, 31 | int currDepthCount) { 32 | if (!root) return; 33 | 34 | currDepthCount += 1; 35 | if (root->left == NULL && root->right == NULL) { 36 | minDepthCount = min(currDepthCount, minDepthCount); 37 | currDepthCount = 0; 38 | } 39 | 40 | minDepthHelper(root->left, minDepthCount, currDepthCount); 41 | minDepthHelper(root->right, minDepthCount, currDepthCount); 42 | } 43 | 44 | int minDepth(TreeNode* root) { 45 | int minDepthCount = INT_MAX; 46 | minDepthHelper(root, minDepthCount, 0); 47 | return minDepthCount == INT_MAX ? 0 : minDepthCount; 48 | } 49 | }; -------------------------------------------------------------------------------- /day-206.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 132 Pattern 3 | 4 | 5 | Given an array of n integers nums, a 132 pattern is a subsequence of three 6 | integers nums[i], nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] 7 | < nums[j]. 8 | 9 | Return true if there is a 132 pattern in nums, otherwise, return false. 10 | 11 | Follow up: The O(n^2) is trivial, could you come up with the O(n logn) or the 12 | O(n) solution? 13 | 14 | 15 | 16 | Example 1: 17 | 18 | Input: nums = [1,2,3,4] 19 | Output: false 20 | Explanation: There is no 132 pattern in the sequence. 21 | Example 2: 22 | 23 | Input: nums = [3,1,4,2] 24 | Output: true 25 | Explanation: There is a 132 pattern in the sequence: [1, 4, 2]. 26 | Example 3: 27 | 28 | Input: nums = [-1,3,2,0] 29 | Output: true 30 | Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 31 | 0] and [-1, 2, 0]. 32 | 33 | 34 | Constraints: 35 | 36 | n == nums.length 37 | 1 <= n <= 104 38 | -109 <= nums[i] <= 109 39 | 40 | 41 | */ 42 | 43 | // O(N) solution based on stacks 44 | class Solution { 45 | public: 46 | bool find132pattern(vector& nums) { 47 | stack stack; 48 | int second = -2147483648; 49 | for (int i = nums.size() - 1; i >= 0; i--) { 50 | if (nums[i] < second) return true; 51 | while (stack.size() > 0 && nums[i] > stack.top()) { 52 | second = stack.top(); 53 | stack.pop(); 54 | } 55 | 56 | stack.push(nums[i]); 57 | } 58 | return false; 59 | } 60 | }; -------------------------------------------------------------------------------- /day-211.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Summary Ranges 3 | 4 | 5 | You are given a sorted unique integer array nums. 6 | 7 | Return the smallest sorted list of ranges that cover all the numbers in the 8 | array exactly. That is, each element of nums is covered by exactly one of the 9 | ranges, and there is no integer x such that x is in one of the ranges but not in 10 | nums. 11 | 12 | Each range [a,b] in the list should be output as: 13 | 14 | "a->b" if a != b 15 | "a" if a == b 16 | 17 | 18 | Example 1: 19 | 20 | Input: nums = [0,1,2,4,5,7] 21 | Output: ["0->2","4->5","7"] 22 | Explanation: The ranges are: 23 | [0,2] --> "0->2" 24 | [4,5] --> "4->5" 25 | [7,7] --> "7" 26 | Example 2: 27 | 28 | Input: nums = [0,2,3,4,6,8,9] 29 | Output: ["0","2->4","6","8->9"] 30 | Explanation: The ranges are: 31 | [0,0] --> "0" 32 | [2,4] --> "2->4" 33 | [6,6] --> "6" 34 | [8,9] --> "8->9" 35 | Example 3: 36 | 37 | Input: nums = [] 38 | Output: [] 39 | Example 4: 40 | 41 | Input: nums = [-1] 42 | Output: ["-1"] 43 | Example 5: 44 | 45 | Input: nums = [0] 46 | Output: ["0"] 47 | 48 | 49 | */ 50 | 51 | // Simple O(N) solution 52 | class Solution { 53 | public: 54 | vector summaryRanges(vector& nums) { 55 | vector answer; 56 | 57 | int num, i = 0; 58 | 59 | while (i < nums.size()) { 60 | num = nums[i++]; 61 | int p = num; 62 | string ans = to_string(num); 63 | while (i < nums.size() && num + 1 == nums[i]) num = nums[i++]; 64 | answer.push_back(p != num ? ans + "->" + to_string(num) : ans); 65 | } 66 | return answer; 67 | } 68 | }; -------------------------------------------------------------------------------- /day-213.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Number of Longest Increasing Subsequence 3 | 4 | 5 | Given an integer array nums, return the number of longest increasing 6 | subsequences. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: nums = [1,3,5,4,7] 13 | Output: 2 14 | Explanation: The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 15 | 5, 7]. Example 2: 16 | 17 | Input: nums = [2,2,2,2,2] 18 | Output: 5 19 | Explanation: The length of longest continuous increasing subsequence is 1, and 20 | there are 5 subsequences' length is 1, so output 5. 21 | 22 | 23 | 24 | */ 25 | 26 | // DP solution to calculate maximum 27 | class Solution { 28 | public: 29 | int findNumberOfLIS(vector& nums) { 30 | int N = nums.size(), lis_len = 1, res = 0; 31 | vector len(N, 1), dp(N, 1); 32 | for (int i = 1; i < N; i++) 33 | for (int j = 0; j < i; j++) { 34 | if (nums[i] > nums[j]) { 35 | if (len[j] + 1 > len[i]) { 36 | len[i] = len[j] + 1; 37 | dp[i] = dp[j]; 38 | } else if (len[j] + 1 == len[i]) 39 | dp[i] += dp[j]; 40 | } 41 | lis_len = max(lis_len, len[i]); 42 | } 43 | for (int i = 0; i < N; i++) { 44 | if (len[i] == lis_len) res += dp[i]; 45 | } 46 | 47 | return res; 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /day-214.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Recover Binary Search Tree 3 | 4 | 5 | You are given the root of a binary search tree (BST), where exactly two nodes of 6 | the tree were swapped by mistake. Recover the tree without changing its 7 | structure. 8 | 9 | Follow up: A solution using O(n) space is pretty straight forward. Could you 10 | devise a constant space solution? 11 | 12 | Input: root = [1,3,null,null,2] 13 | Output: [3,1,null,null,2] 14 | Explanation: 3 cannot be a left child of 1 because 3 > 1. Swapping 1 and 3 makes 15 | the BST valid. 16 | 17 | Input: root = [3,1,4,null,null,2] 18 | Output: [2,1,4,null,null,3] 19 | Explanation: 2 cannot be in the right subtree of 3 because 2 < 3. Swapping 2 and 20 | 3 makes the BST valid. 21 | 22 | */ 23 | 24 | // Simple O(N) & O(1) solution using inorder traversal 25 | 26 | class Solution { 27 | public: 28 | vector> vec; 29 | TreeNode* prev = NULL; 30 | void inorder(TreeNode* root) { 31 | if (!root) return; 32 | inorder(root->left); 33 | if (prev && prev->val > root->val) vec.push_back({prev, root}); 34 | prev = root; 35 | inorder(root->right); 36 | } 37 | void recoverTree(TreeNode* root) { 38 | inorder(root); 39 | if (vec.size() == 1) swap(vec[0].first->val, vec[0].second->val); 40 | if (vec.size() == 2) swap(vec[0].first->val, vec[1].second->val); 41 | } 42 | }; -------------------------------------------------------------------------------- /day-215.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Convert Binary Number in a Linked List to Integer 3 | 4 | 5 | Given head which is a reference node to a singly-linked list. The value of each 6 | node in the linked list is either 0 or 1. The linked list holds the binary 7 | representation of a number. 8 | 9 | Return the decimal value of the number in the linked list. 10 | 11 | 12 | 13 | Example 1: 14 | 15 | 16 | Input: head = [1,0,1] 17 | Output: 5 18 | Explanation: (101) in base 2 = (5) in base 10 19 | Example 2: 20 | 21 | Input: head = [0] 22 | Output: 0 23 | Example 3: 24 | 25 | Input: head = [1] 26 | Output: 1 27 | Example 4: 28 | 29 | Input: head = [1,0,0,1,0,0,1,1,1,0,0,0,0,0,0] 30 | Output: 18880 31 | Example 5: 32 | 33 | Input: head = [0,0] 34 | Output: 0 35 | 36 | 37 | Constraints: 38 | 39 | The Linked List is not empty. 40 | Number of nodes will not exceed 30. 41 | Each node's value is either 0 or 1. 42 | 43 | */ 44 | 45 | // Simple linear time solution using vectors and maths 46 | class Solution { 47 | public: 48 | int getDecimalValue(ListNode* head) { 49 | vector digits; 50 | while (head != NULL) { 51 | digits.push_back(head->val); 52 | head = head->next; 53 | } 54 | 55 | int len = digits.size(); 56 | int pos = 0; 57 | int answer = 0; 58 | for (int idx = len - 1; idx >= 0; idx--, pos++) { 59 | answer += digits[idx] * pow(2, pos); 60 | } 61 | 62 | return answer; 63 | } 64 | }; -------------------------------------------------------------------------------- /day-216.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Insertion Sort List 3 | 4 | 5 | Sort a linked list using insertion sort. 6 | 7 | 8 | A graphical example of insertion sort. The partial sorted list (black) initially 9 | contains only the first element in the list. With each iteration one element 10 | (red) is removed from the input data and inserted in-place into the sorted list 11 | 12 | 13 | Algorithm of Insertion Sort: 14 | 15 | Insertion sort iterates, consuming one input element each repetition, and 16 | growing a sorted output list. At each iteration, insertion sort removes one 17 | element from the input data, finds the location it belongs within the sorted 18 | list, and inserts it there. It repeats until no input elements remain. 19 | 20 | Example 1: 21 | 22 | Input: 4->2->1->3 23 | Output: 1->2->3->4 24 | Example 2: 25 | 26 | Input: -1->5->3->4->0 27 | Output: -1->0->3->4->5 28 | 29 | */ 30 | 31 | // Simple linked list sorting 32 | class Solution { 33 | public: 34 | ListNode* insertionSortList(ListNode* head) { 35 | vector nums; 36 | ListNode* temp = head; 37 | while (temp != NULL) { 38 | nums.push_back(temp->val); 39 | temp = temp->next; 40 | } 41 | 42 | sort(nums.begin(), nums.end()); 43 | 44 | temp = head; 45 | int idx = 0; 46 | while (temp != NULL) { 47 | temp->val = nums[idx]; 48 | temp = temp->next; 49 | idx += 1; 50 | } 51 | 52 | return head; 53 | } 54 | }; -------------------------------------------------------------------------------- /day-217.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Consecutive Characters 3 | 4 | 5 | Given a string s, the power of the string is the maximum length of a non-empty 6 | substring that contains only one unique character. 7 | 8 | Return the power of the string. 9 | 10 | 11 | 12 | Example 1: 13 | 14 | Input: s = "leetcode" 15 | Output: 2 16 | Explanation: The substring "ee" is of length 2 with the character 'e' only. 17 | Example 2: 18 | 19 | Input: s = "abbcccddddeeeeedcba" 20 | Output: 5 21 | Explanation: The substring "eeeee" is of length 5 with the character 'e' only. 22 | Example 3: 23 | 24 | Input: s = "triplepillooooow" 25 | Output: 5 26 | Example 4: 27 | 28 | Input: s = "hooraaaaaaaaaaay" 29 | Output: 11 30 | Example 5: 31 | 32 | Input: s = "tourist" 33 | Output: 1 34 | 35 | 36 | Constraints: 37 | 38 | 1 <= s.length <= 500 39 | s contains only lowercase English letters. 40 | */ 41 | 42 | // Simple O(N) solution beats 86.98 % of cpp submissions. 43 | class Solution { 44 | public: 45 | int maxPower(string s) { 46 | int N = s.size(); 47 | int currMax = 0; 48 | int ansMax = 1; 49 | bool isStart = true; 50 | for (int idx = 1; idx < N; idx++) { 51 | if (s[idx] == s[idx - 1]) { 52 | if (isStart) { 53 | currMax += 1; 54 | isStart = false; 55 | } 56 | 57 | currMax += 1; 58 | } else { 59 | ansMax = max(ansMax, currMax); 60 | currMax = 0; 61 | isStart = true; 62 | } 63 | } 64 | 65 | ansMax = max(ansMax, currMax); 66 | 67 | return ansMax; 68 | } 69 | }; -------------------------------------------------------------------------------- /day-219.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Minimum Cost to Move Chips to The Same Position 3 | 4 | 5 | We have n chips, where the position of the ith chip is position[i]. 6 | 7 | We need to move all the chips to the same position. In one step, we can change 8 | the position of the ith chip from position[i] to: 9 | 10 | position[i] + 2 or position[i] - 2 with cost = 0. 11 | position[i] + 1 or position[i] - 1 with cost = 1. 12 | Return the minimum cost needed to move all the chips to the same position. 13 | 14 | 15 | 16 | Example 1: 17 | 18 | 19 | Input: position = [1,2,3] 20 | Output: 1 21 | Explanation: First step: Move the chip at position 3 to position 1 with cost = 22 | 0. Second step: Move the chip at position 2 to position 1 with cost = 1. Total 23 | cost is 1. Example 2: 24 | 25 | 26 | Input: position = [2,2,2,3,3] 27 | Output: 2 28 | Explanation: We can move the two chips at poistion 3 to position 2. Each move 29 | has cost = 1. The total cost = 2. Example 3: 30 | 31 | Input: position = [1,1000000000] 32 | Output: 1 33 | 34 | 35 | Constraints: 36 | 37 | 1 <= position.length <= 100 38 | 1 <= position[i] <= 10^9 39 | 40 | 41 | */ 42 | 43 | // Simple O(N) solution 44 | class Solution { 45 | public: 46 | int minCostToMoveChips(vector& position) { 47 | int N = position.size(); 48 | int even = 0; 49 | for (int idx = 0; idx < N; idx++) { 50 | if (position[idx] % 2 == 0) even += 1; 51 | } 52 | 53 | int odd = N - even; 54 | return even < odd ? even : odd; 55 | } 56 | }; -------------------------------------------------------------------------------- /day-22.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Question: Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. 3 | 4 | Example 1: 5 | Input:nums = [1,1,1], k = 2 6 | Output: 2 7 | Note: 8 | The length of the array is in range [1, 20,000]. 9 | The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7]. 10 | */ 11 | 12 | class Solution { 13 | public: 14 | int subarraySum(vector& nums, int k) { 15 | int size = nums.size(); 16 | int sum = 0; 17 | unordered_map freq; 18 | freq[0] = 1; 19 | int ans = 0; 20 | for (int i = 0; i < size; ++i) { 21 | sum = sum + nums[i]; 22 | ans = ans + freq[sum - k]; 23 | freq[sum] += 1; 24 | } 25 | 26 | return ans; 27 | } 28 | }; -------------------------------------------------------------------------------- /day-221.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Add Two Numbers II 3 | 4 | 5 | You are given two non-empty linked lists representing two non-negative integers. 6 | The most significant digit comes first and each of their nodes contain a single 7 | digit. Add the two numbers and return it as a linked list. 8 | 9 | You may assume the two numbers do not contain any leading zero, except the 10 | number 0 itself. 11 | 12 | Follow up: 13 | What if you cannot modify the input lists? In other words, reversing the lists 14 | is not allowed. 15 | 16 | Example: 17 | 18 | Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) 19 | Output: 7 -> 8 -> 0 -> 7 20 | 21 | */ 22 | 23 | // Solution using strings to add list reverse order 24 | class Solution { 25 | public: 26 | ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 27 | string a, b; 28 | ListNode* result = nullptr; 29 | while (l1) { 30 | a.push_back(l1->val + '0'); 31 | l1 = l1->next; 32 | } 33 | 34 | while (l2) { 35 | b.push_back(l2->val + '0'); 36 | l2 = l2->next; 37 | } 38 | 39 | int l = a.size() - 1, r = b.size() - 1, carry = 0; 40 | 41 | while (l >= 0 || r >= 0 || carry == 1) { 42 | int c = (l >= 0 ? a[l--] - '0' : 0) + (r >= 0 ? b[r--] - '0' : 0) + 43 | carry; 44 | ListNode* temp = new ListNode(c % 10); 45 | temp->next = result; 46 | result = temp; 47 | carry = c / 10; 48 | } 49 | return result; 50 | } 51 | }; -------------------------------------------------------------------------------- /day-223.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Maximum Difference Between Node and Ancestor 3 | 4 | Given the root of a binary tree, find the maximum value V for which there exist 5 | different nodes A and B where V = |A.val - B.val| and A is an ancestor of B. 6 | 7 | A node A is an ancestor of B if either: any child of A is equal to B, or any 8 | child of A is an ancestor of B. 9 | 10 | 11 | 12 | Example 1: 13 | 14 | 15 | Input: root = [8,3,10,1,6,null,14,null,null,4,7,13] 16 | Output: 7 17 | Explanation: We have various ancestor-node differences, some of which are given 18 | below : |8 - 3| = 5 |3 - 7| = 4 |8 - 1| = 7 |10 - 13| = 3 Among all possible 19 | differences, the maximum value of 7 is obtained by |8 - 1| = 7. Example 2: 20 | 21 | 22 | Input: root = [1,null,2,null,0,3] 23 | Output: 3 24 | 25 | 26 | Constraints: 27 | 28 | The number of nodes in the tree is in the range [2, 5000]. 29 | 0 <= Node.val <= 105 30 | 31 | */ 32 | 33 | // Recursivw solution 34 | class Solution { 35 | public: 36 | int rec(TreeNode* root, int minval, int maxval) { 37 | if (!root) { 38 | return maxval - minval; 39 | } 40 | 41 | minval = min(minval, root->val); 42 | maxval = max(maxval, root->val); 43 | 44 | int left = rec(root->left, minval, maxval); 45 | int right = rec(root->right, minval, maxval); 46 | 47 | return max(left, right); 48 | } 49 | 50 | // constraints: Tree has at least 2 nodes 51 | int maxAncestorDiff(TreeNode* root) { 52 | return rec(root, root->val, root->val); 53 | } 54 | }; -------------------------------------------------------------------------------- /day-224.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Flipping an Image 3 | 4 | 5 | Given a binary matrix A, we want to flip the image horizontally, then invert it, 6 | and return the resulting image. 7 | 8 | To flip an image horizontally means that each row of the image is reversed. For 9 | example, flipping [1, 1, 0] horizontally results in [0, 1, 1]. 10 | 11 | To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 12 | 0. For example, inverting [0, 1, 1] results in [1, 0, 0]. 13 | 14 | Example 1: 15 | 16 | Input: [[1,1,0],[1,0,1],[0,0,0]] 17 | Output: [[1,0,0],[0,1,0],[1,1,1]] 18 | Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]]. 19 | Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]] 20 | Example 2: 21 | 22 | Input: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]] 23 | Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] 24 | Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]]. 25 | Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] 26 | Notes: 27 | 28 | 1 <= A.length = A[0].length <= 20 29 | 0 <= A[i][j] <= 1 30 | 31 | 32 | */ 33 | 34 | // Beats 98.93 % of cpp submissions. 35 | class Solution { 36 | public: 37 | vector> flipAndInvertImage(vector>& A) { 38 | int rows = A.size(); 39 | int cols = A[0].size(); 40 | 41 | vector> flipped(rows, vector(cols)); 42 | 43 | for (int row = 0; row < rows; row++) { 44 | for (int col = 0; col < cols; col++) { 45 | int targetVal = A[row][cols - col - 1]; 46 | flipped[row][col] = (targetVal == 1) ? 0 : 1; 47 | } 48 | } 49 | 50 | return flipped; 51 | } 52 | }; -------------------------------------------------------------------------------- /day-225.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Valid Square 3 | 4 | 5 | Given the coordinates of four points in 2D space, return whether the four points 6 | could construct a square. 7 | 8 | The coordinate (x,y) of a point is represented by an integer array with two 9 | integers. 10 | 11 | Example: 12 | 13 | Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1] 14 | Output: True 15 | 16 | 17 | Note: 18 | 19 | All the input integers are in the range [-10000, 10000]. 20 | A valid square has four equal sides with positive length and four equal angles 21 | (90-degree angles). Input points have no order. 22 | 23 | 24 | */ 25 | 26 | // Simple math based solution 27 | class Solution { 28 | public: 29 | long long int dist(vector& p1, vector& p2) { 30 | return pow(p1[0] - p2[0], 2) + pow(p1[1] - p2[1], 2); 31 | } 32 | 33 | bool check(vector& p1, vector& p2, vector& p3, 34 | vector& p4) { 35 | return dist(p1, p2) > 0 and dist(p1, p2) == dist(p2, p3) and 36 | dist(p2, p3) == dist(p3, p4) and dist(p3, p4) == dist(p4, p1) and 37 | dist(p1, p3) == dist(p2, p4); 38 | } 39 | 40 | bool validSquare(vector& p1, vector& p2, vector& p3, 41 | vector& p4) { 42 | return check(p1, p2, p3, p4) or check(p1, p3, p2, p4) or 43 | check(p1, p2, p4, p3); 44 | } 45 | }; -------------------------------------------------------------------------------- /day-226.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Permutations II 3 | 4 | 5 | Given a collection of numbers, nums, that might contain duplicates, return all 6 | possible unique permutations in any order. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: nums = [1,1,2] 13 | Output: 14 | [[1,1,2], 15 | [1,2,1], 16 | [2,1,1]] 17 | Example 2: 18 | 19 | Input: nums = [1,2,3] 20 | Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] 21 | 22 | 23 | Constraints: 24 | 25 | 1 <= nums.length <= 8 26 | -10 <= nums[i] <= 10 27 | */ 28 | 29 | class Solution { 30 | public: 31 | vector> permuteUnique(vector& nums) { 32 | vector> output; 33 | vector curr; 34 | unordered_map counter; 35 | for (auto x : nums) ++counter[x]; 36 | generatePermutations(counter, curr, output, size(nums)); 37 | return output; 38 | } 39 | 40 | private: 41 | void generatePermutations(unordered_map& counter, 42 | vector& curr, vector>& output, 43 | int n) { 44 | if (size(curr) == n) { 45 | output.emplace_back(curr); 46 | return; 47 | } 48 | for (auto [key, value] : counter) { 49 | if (value == 0) continue; 50 | curr.emplace_back(key); 51 | --counter[key]; 52 | generatePermutations(counter, curr, output, n); 53 | curr.pop_back(); 54 | ++counter[key]; 55 | } 56 | } 57 | }; -------------------------------------------------------------------------------- /day-228.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Poor Pigs 3 | 4 | 5 | There are 1000 buckets, one and only one of them is poisonous, while the rest 6 | are filled with water. They all look identical. If a pig drinks the poison it 7 | will die within 15 minutes. What is the minimum amount of pigs you need to 8 | figure out which bucket is poisonous within one hour? 9 | 10 | Answer this question, and write an algorithm for the general case. 11 | 12 | 13 | 14 | General case: 15 | 16 | If there are n buckets and a pig drinking poison will die within m minutes, how 17 | many pigs (x) you need to figure out the poisonous bucket within p minutes? 18 | There is exactly one bucket with poison. 19 | 20 | 21 | 22 | Note: 23 | 24 | A pig can be allowed to drink simultaneously on as many buckets as one would 25 | like, and the feeding takes no time. After a pig has instantly finished drinking 26 | buckets, there has to be a cool down time of m minutes. During this time, only 27 | observation is allowed and no feedings at all. Any given bucket can be sampled 28 | an infinite number of times (by an unlimited number of pigs). 29 | 30 | */ 31 | 32 | // Simple O(N) solution 33 | class Solution { 34 | public: 35 | int poorPigs(int buckets, int minutesToDie, int minutesToTest) { 36 | int T = (minutesToTest / minutesToDie) + 1; 37 | int cnt = 0; 38 | int total = 1; 39 | while (total < buckets) { 40 | total *= T; 41 | cnt++; 42 | } 43 | return cnt; 44 | } 45 | }; -------------------------------------------------------------------------------- /day-229.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Range Sum of BST 3 | 4 | 5 | Given the root node of a binary search tree, return the sum of values of all 6 | nodes with a value in the range [low, high]. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | 13 | Input: root = [10,5,15,3,7,null,18], low = 7, high = 15 14 | Output: 32 15 | Example 2: 16 | 17 | 18 | Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10 19 | Output: 23 20 | 21 | 22 | Constraints: 23 | 24 | The number of nodes in the tree is in the range [1, 2 * 104]. 25 | 1 <= Node.val <= 105 26 | 1 <= low <= high <= 105 27 | All Node.val are unique. 28 | */ 29 | 30 | // Simple recursive solution, iterating in the tree and comparing the values if 31 | // it falls between the range 32 | class Solution { 33 | public: 34 | void rangeSumBSTHelper(TreeNode* root, int low, int high, int& sum) { 35 | if (root == NULL) return; 36 | if (root->val >= low && root->val <= high) sum += root->val; 37 | rangeSumBSTHelper(root->left, low, high, sum); 38 | rangeSumBSTHelper(root->right, low, high, sum); 39 | } 40 | 41 | int rangeSumBST(TreeNode* root, int low, int high) { 42 | int sum = 0; 43 | rangeSumBSTHelper(root, low, high, sum); 44 | return sum; 45 | } 46 | }; -------------------------------------------------------------------------------- /day-23.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Question: Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. 3 | 4 | Example 1: 5 | 6 | Input: [5,7] 7 | Output: 4 8 | Example 2: 9 | 10 | Input: [0,1] 11 | Output: 0 12 | */ 13 | 14 | class Solution { 15 | public: 16 | int rangeBitwiseAnd(int m, int n) { 17 | int count = 0; 18 | 19 | while (m < n) { 20 | m = m >> 1; 21 | n = n >> 1; 22 | count += 1; 23 | } 24 | 25 | return m << count; 26 | } 27 | }; -------------------------------------------------------------------------------- /day-230.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Longest Mountain in Array 3 | 4 | 5 | Let's call any (contiguous) subarray B (of A) a mountain if the following 6 | properties hold: 7 | 8 | B.length >= 3 9 | There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] 10 | > B[i+1] > ... > B[B.length - 1] (Note that B could be any subarray of A, 11 | including the entire array A.) 12 | 13 | Given an array A of integers, return the length of the longest mountain. 14 | 15 | Return 0 if there is no mountain. 16 | 17 | Example 1: 18 | 19 | Input: [2,1,4,7,3,2,5] 20 | Output: 5 21 | Explanation: The largest mountain is [1,4,7,3,2] which has length 5. 22 | Example 2: 23 | 24 | Input: [2,2,2] 25 | Output: 0 26 | Explanation: There is no mountain. 27 | 28 | */ 29 | 30 | // Solved using dynamic programming 2 pass solution 31 | 32 | class Solution { 33 | public: 34 | int longestMountain(vector& A) { 35 | const int N = A.size(); 36 | vector ups(N, 0), downs(N, 0); 37 | for (int i = 1; i < N; i++) 38 | if (A[i] > A[i - 1]) ups[i] = ups[i - 1] + 1; 39 | int ans = 0; 40 | for (int i = N - 1; i >= 0; i--) { 41 | if (i < N - 1 && A[i] > A[i + 1]) downs[i] = downs[i + 1] + 1; 42 | if (ups[i] && downs[i]) ans = max(ans, ups[i] + downs[i] + 1); 43 | } 44 | return ans; 45 | } 46 | }; -------------------------------------------------------------------------------- /day-231.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Mirror Reflection 3 | 4 | 5 | There is a special square room with mirrors on each of the four walls. Except 6 | for the southwest corner, there are receptors on each of the remaining corners, 7 | numbered 0, 1, and 2. 8 | 9 | The square room has walls of length p, and a laser ray from the southwest corner 10 | first meets the east wall at a distance q from the 0th receptor. 11 | 12 | Return the number of the receptor that the ray meets first. (It is guaranteed 13 | that the ray will meet a receptor eventually.) 14 | 15 | 16 | 17 | Example 1: 18 | 19 | Input: p = 2, q = 1 20 | Output: 2 21 | Explanation: The ray meets receptor 2 the first time it gets reflected back to 22 | the left wall. 23 | 24 | Note: 25 | 26 | 1 <= p <= 1000 27 | 0 <= q <= p 28 | 29 | */ 30 | 31 | // Geometry based solution 32 | class Solution { 33 | public: 34 | int mirrorReflection(int p, int q) { 35 | int m = 1; 36 | int n = 1; 37 | while (m * p != n * q) { 38 | n++; 39 | m = n * q / p; 40 | } 41 | if (m % 2 == 0 && n % 2 == 1) return 0; 42 | if (m % 2 == 1 && n % 2 == 1) return 1; 43 | if (m % 2 == 1 && n % 2 == 0) return 2; 44 | return -1; 45 | } 46 | }; -------------------------------------------------------------------------------- /day-232.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Merge Intervals 3 | 4 | 5 | Given an array of intervals where intervals[i] = [starti, endi], merge all 6 | overlapping intervals, and return an array of the non-overlapping intervals that 7 | cover all the intervals in the input. 8 | 9 | 10 | 11 | Example 1: 12 | 13 | Input: intervals = [[1,3],[2,6],[8,10],[15,18]] 14 | Output: [[1,6],[8,10],[15,18]] 15 | Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. 16 | Example 2: 17 | 18 | Input: intervals = [[1,4],[4,5]] 19 | Output: [[1,5]] 20 | Explanation: Intervals [1,4] and [4,5] are considered overlapping. 21 | 22 | 23 | Constraints: 24 | 25 | 1 <= intervals.length <= 104 26 | intervals[i].length == 2 27 | 0 <= starti <= endi <= 104 28 | 29 | 30 | */ 31 | 32 | // Linear scan solution + sorting 33 | // Time complexity = O(N * logN) 34 | 35 | class Solution { 36 | public: 37 | vector> merge(vector>& intervals) { 38 | sort(intervals.begin(), intervals.end()); 39 | int N = intervals.size(); 40 | vector> answer; 41 | for (int idx = 0; idx < N; idx++) { 42 | vector interval = intervals[idx]; 43 | if (answer.empty() || interval[0] > answer.back()[1]) 44 | answer.push_back(interval); 45 | else 46 | answer.back()[1] = max(answer.back()[1], interval[1]); 47 | } 48 | 49 | return answer; 50 | } 51 | }; -------------------------------------------------------------------------------- /day-234.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Search in Rotated Sorted Array II 3 | 4 | 5 | Suppose an array sorted in ascending order is rotated at some pivot unknown to 6 | you beforehand. 7 | 8 | (i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]). 9 | 10 | You are given a target value to search. If found in the array return true, 11 | otherwise return false. 12 | 13 | Example 1: 14 | 15 | Input: nums = [2,5,6,0,0,1,2], target = 0 16 | Output: true 17 | Example 2: 18 | 19 | Input: nums = [2,5,6,0,0,1,2], target = 3 20 | Output: false 21 | Follow up: 22 | 23 | This is a follow up problem to Search in Rotated Sorted Array, where nums may 24 | contain duplicates. Would this affect the run-time complexity? How and why? 25 | 26 | */ 27 | 28 | // Binary search solution 29 | class Solution { 30 | public: 31 | bool search(vector& nums, int target) { 32 | int left = 0, right = nums.size() - 1; 33 | while (left <= right) { 34 | int mid = left + (right - left) / 2; 35 | if (nums[mid] == target) 36 | return true; 37 | else if (nums[mid] < nums[right]) { 38 | if (nums[mid] < target && target <= nums[right]) 39 | left = mid + 1; 40 | else 41 | right = mid - 1; 42 | } else if (nums[mid] > nums[right]) { 43 | if (nums[left] <= target && target < nums[mid]) 44 | right = mid - 1; 45 | else 46 | left = mid + 1; 47 | } else { 48 | right--; 49 | } 50 | } 51 | return false; 52 | } 53 | }; -------------------------------------------------------------------------------- /day-238.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Basic Calculator II 3 | 4 | 5 | Implement a basic calculator to evaluate a simple expression string. 6 | 7 | The expression string contains only non-negative integers, +, -, *, / operators 8 | and empty spaces . The integer division should truncate toward zero. 9 | 10 | Example 1: 11 | 12 | Input: "3+2*2" 13 | Output: 7 14 | Example 2: 15 | 16 | Input: " 3/2 " 17 | Output: 1 18 | Example 3: 19 | 20 | Input: " 3+5 / 2 " 21 | Output: 5 22 | Note: 23 | 24 | You may assume that the given expression is always valid. 25 | Do not use the eval built-in library function. 26 | 27 | 28 | */ 29 | 30 | // String scan solution 31 | class Solution { 32 | public: 33 | int calculate(string s) { 34 | istringstream iss('+' + s + '+'); 35 | int total = 0; 36 | int leftOperand = 0; 37 | int rightOperand = 0; 38 | char op; 39 | while (iss >> op) { 40 | if (op == '+' || op == '-') { 41 | total += leftOperand; 42 | iss >> leftOperand; 43 | leftOperand *= (op == '+' ? 1 : -1); 44 | } else { 45 | iss >> rightOperand; 46 | if (op == '*') 47 | leftOperand *= rightOperand; 48 | else 49 | leftOperand /= rightOperand; 50 | } 51 | } 52 | return total; 53 | } 54 | }; -------------------------------------------------------------------------------- /day-239.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Smallest Integer Divisible by K 3 | 4 | 5 | Given a positive integer K, you need to find the length of the smallest positive 6 | integer N such that N is divisible by K, and N only contains the digit 1. 7 | 8 | Return the length of N. If there is no such N, return -1. 9 | 10 | Note: N may not fit in a 64-bit signed integer. 11 | 12 | 13 | 14 | Example 1: 15 | 16 | Input: K = 1 17 | Output: 1 18 | Explanation: The smallest answer is N = 1, which has length 1. 19 | Example 2: 20 | 21 | Input: K = 2 22 | Output: -1 23 | Explanation: There is no such positive integer N divisible by 2. 24 | Example 3: 25 | 26 | Input: K = 3 27 | Output: 3 28 | Explanation: The smallest answer is N = 111, which has length 3. 29 | 30 | 31 | Constraints: 32 | 33 | 1 <= K <= 105 34 | 35 | */ 36 | 37 | // Solved using hash set and modulo property 38 | class Solution { 39 | public: 40 | int smallestRepunitDivByK(int K) { 41 | unordered_set st; 42 | int rem = 1 % K; 43 | while (rem != 0 && st.find(rem) == st.end()) { 44 | st.insert(rem); 45 | rem = (rem * 10 + 1) % K; 46 | } 47 | 48 | if (rem == 0) return st.size() + 1; 49 | 50 | return -1; 51 | } 52 | }; -------------------------------------------------------------------------------- /day-241.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Partition Equal Subset Sum 3 | 4 | 5 | Given a non-empty array nums containing only positive integers, find if the 6 | array can be partitioned into two subsets such that the sum of elements in both 7 | subsets is equal. 8 | 9 | 10 | 11 | Example 1: 12 | 13 | Input: nums = [1,5,11,5] 14 | Output: true 15 | Explanation: The array can be partitioned as [1, 5, 5] and [11]. 16 | Example 2: 17 | 18 | Input: nums = [1,2,3,5] 19 | Output: false 20 | Explanation: The array cannot be partitioned into equal sum subsets. 21 | 22 | 23 | Constraints: 24 | 25 | 1 <= nums.length <= 200 26 | 1 <= nums[i] <= 100 27 | 28 | */ 29 | 30 | // Solved using dynamic programming 31 | class Solution { 32 | public: 33 | bool canPartition(vector& nums) { 34 | int sum = 0; 35 | for (auto a : nums) sum += a; 36 | 37 | if (sum % 2) return false; 38 | sum /= 2; 39 | vector dp(sum + 1, false); 40 | dp[0] = true; 41 | 42 | for (auto a : nums) { 43 | for (int i = sum; i >= a; i--) { 44 | dp[i] = dp[i] || dp[i - a]; 45 | } 46 | } 47 | return dp[sum]; 48 | } 49 | }; -------------------------------------------------------------------------------- /day-243.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Jump Game III 3 | 4 | 5 | Given an array of non-negative integers arr, you are initially positioned at 6 | start index of the array. When you are at index i, you can jump to i + arr[i] or 7 | i - arr[i], check if you can reach to any index with value 0. 8 | 9 | Notice that you can not jump outside of the array at any time. 10 | 11 | 12 | 13 | Example 1: 14 | 15 | Input: arr = [4,2,3,0,3,1,2], start = 5 16 | Output: true 17 | Explanation: 18 | All possible ways to reach at index 3 with value 0 are: 19 | index 5 -> index 4 -> index 1 -> index 3 20 | index 5 -> index 6 -> index 4 -> index 1 -> index 3 21 | Example 2: 22 | 23 | Input: arr = [4,2,3,0,3,1,2], start = 0 24 | Output: true 25 | Explanation: 26 | One possible way to reach at index 3 with value 0 is: 27 | index 0 -> index 4 -> index 1 -> index 3 28 | Example 3: 29 | 30 | Input: arr = [3,0,2,1,2], start = 2 31 | Output: false 32 | Explanation: There is no way to reach at index 1 with value 0. 33 | 34 | 35 | Constraints: 36 | 37 | 1 <= arr.length <= 5 * 10^4 38 | 0 <= arr[i] < arr.length 39 | 0 <= start < arr.length 40 | */ 41 | 42 | // Solved using BFS 43 | 44 | class Solution { 45 | public: 46 | bool rec(vector& arr, int curr, vector& v) { 47 | if ((curr < 0) || (curr >= arr.size()) || v[curr]) return false; 48 | if (arr[curr] == 0) return true; 49 | v[curr] = true; 50 | return rec(arr, curr + arr[curr], v) || rec(arr, curr - arr[curr], v); 51 | } 52 | 53 | bool canReach(vector& arr, int start) { 54 | vector visited(arr.size(), false); 55 | return rec(arr, start, visited); 56 | } 57 | }; -------------------------------------------------------------------------------- /day-245.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Maximum Depth of Binary Tree 3 | 4 | 5 | Given the root of a binary tree, return its maximum depth. 6 | 7 | A binary tree's maximum depth is the number of nodes along the longest path from 8 | the root node down to the farthest leaf node. 9 | 10 | 11 | 12 | Example 1: 13 | 14 | 15 | Input: root = [3,9,20,null,null,15,7] 16 | Output: 3 17 | Example 2: 18 | 19 | Input: root = [1,null,2] 20 | Output: 2 21 | Example 3: 22 | 23 | Input: root = [] 24 | Output: 0 25 | Example 4: 26 | 27 | Input: root = [0] 28 | Output: 1 29 | 30 | 31 | Constraints: 32 | 33 | The number of nodes in the tree is in the range [0, 104]. 34 | -100 <= Node.val <= 100 35 | */ 36 | 37 | // Simple recursive solution 38 | class Solution { 39 | public: 40 | void maxDepthHelper(TreeNode* root, int current, int& maxDepth) { 41 | if (root == NULL) return; 42 | maxDepth = max(maxDepth, current); 43 | if (root->left) maxDepthHelper(root->left, current + 1, maxDepth); 44 | if (root->right) maxDepthHelper(root->right, current + 1, maxDepth); 45 | } 46 | 47 | int maxDepth(TreeNode* root) { 48 | int maxDepth = 0; 49 | int current = 1; 50 | maxDepthHelper(root, current, maxDepth); 51 | return maxDepth; 52 | } 53 | }; -------------------------------------------------------------------------------- /day-246.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Linked List Random Node 3 | 4 | Solution 5 | Given a singly linked list, return a random node's value from the linked list. 6 | Each node must have the same probability of being chosen. 7 | 8 | Follow up: 9 | What if the linked list is extremely large and its length is unknown to you? 10 | Could you solve this efficiently without using extra space? 11 | 12 | Example: 13 | 14 | // Init a singly linked list [1,2,3]. 15 | ListNode head = new ListNode(1); 16 | head.next = new ListNode(2); 17 | head.next.next = new ListNode(3); 18 | Solution solution = new Solution(head); 19 | 20 | // getRandom() should return either 1, 2, or 3 randomly. Each element should 21 | have equal probability of returning. solution.getRandom(); 22 | 23 | */ 24 | 25 | // Simple vector + rand() solution 26 | class Solution { 27 | public: 28 | vector elements; 29 | Solution(ListNode* head) { 30 | elements = vector(); 31 | ListNode* temp = head; 32 | while (temp != NULL) { 33 | elements.push_back(temp->val); 34 | temp = temp->next; 35 | } 36 | } 37 | 38 | int getRandom() { 39 | int N = elements.size(); 40 | int idx = (rand() % N); 41 | return elements[idx]; 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /day-247.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Increasing Order Search Tree 3 | 4 | Given the root of a binary search tree, rearrange the tree in in-order so that 5 | the leftmost node in the tree is now the root of the tree, and every node has no 6 | left child and only one right child. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | 13 | Input: root = [5,3,6,2,4,null,8,1,null,null,null,7,9] 14 | Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9] 15 | Example 2: 16 | 17 | 18 | Input: root = [5,1,7] 19 | Output: [1,null,5,null,7] 20 | 21 | 22 | Constraints: 23 | 24 | The number of nodes in the given tree will be in the range [1, 100]. 25 | 0 <= Node.val <= 1000 26 | 27 | */ 28 | 29 | // Solved using simple inorder solution 30 | class Solution { 31 | public: 32 | void inorder(TreeNode* ans, TreeNode* root) { 33 | if (!root) return; 34 | inorder(ans, root->left); 35 | ans->right = new TreeNode(root->val); 36 | ans = ans->right; 37 | inorder(ans, ans->right); 38 | } 39 | 40 | TreeNode* increasingBST(TreeNode* root) { 41 | TreeNode* temp; 42 | TreeNode* ans = new TreeNode(); 43 | temp = ans; 44 | inorder(ans, root); 45 | return temp->right; 46 | } 47 | }; -------------------------------------------------------------------------------- /day-248.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | The kth Factor of n 3 | 4 | 5 | Given two positive integers n and k 6 | 7 | A factor of an integer n is defined as an integer i where n % i == 0. 8 | 9 | Consider a list of all factors of n sorted in ascending order, return the kth 10 | factor in this list or return -1 if n has less than k factors. 11 | 12 | 13 | 14 | Example 1: 15 | 16 | Input: n = 12, k = 3 17 | Output: 3 18 | Explanation: Factors list is [1, 2, 3, 4, 6, 12], the 3rd factor is 3. 19 | Example 2: 20 | 21 | Input: n = 7, k = 2 22 | Output: 7 23 | Explanation: Factors list is [1, 7], the 2nd factor is 7. 24 | Example 3: 25 | 26 | Input: n = 4, k = 4 27 | Output: -1 28 | Explanation: Factors list is [1, 2, 4], there is only 3 factors. We should 29 | return -1. Example 4: 30 | 31 | Input: n = 1, k = 1 32 | Output: 1 33 | Explanation: Factors list is [1], the 1st factor is 1. 34 | Example 5: 35 | 36 | Input: n = 1000, k = 3 37 | Output: 4 38 | Explanation: Factors list is [1, 2, 4, 5, 8, 10, 20, 25, 40, 50, 100, 125, 200, 39 | 250, 500, 1000]. 40 | 41 | 42 | Constraints: 43 | 44 | 1 <= k <= n <= 1000 45 | */ 46 | 47 | // Simple O(N) based solution 48 | class Solution { 49 | public: 50 | int kthFactor(int n, int k) { 51 | int currentFactorIdx = 0; 52 | for (int idx = 1; idx <= n; idx++) { 53 | if (n % idx == 0) { 54 | currentFactorIdx += 1; 55 | } 56 | 57 | if (currentFactorIdx == k) return idx; 58 | } 59 | 60 | return -1; 61 | } 62 | }; -------------------------------------------------------------------------------- /day-249.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Can Place Flowers 3 | 4 | Solution 5 | You have a long flowerbed in which some of the plots are planted, and some are 6 | not. However, flowers cannot be planted in adjacent plots. 7 | 8 | Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 9 | 1 means not empty, and an integer n, return if n new flowers can be planted in 10 | the flowerbed without violating the no-adjacent-flowers rule. 11 | 12 | 13 | 14 | Example 1: 15 | 16 | Input: flowerbed = [1,0,0,0,1], n = 1 17 | Output: true 18 | Example 2: 19 | 20 | Input: flowerbed = [1,0,0,0,1], n = 2 21 | Output: false 22 | 23 | 24 | Constraints: 25 | 26 | 1 <= flowerbed.length <= 2 * 104 27 | flowerbed[i] is 0 or 1. 28 | There are no two adjacent flowers in flowerbed. 29 | 0 <= n <= flowerbed.length 30 | */ 31 | 32 | // Simple elegant for loop solution 33 | class Solution { 34 | public: 35 | bool canPlaceFlowers(vector& flowerbed, int n) { 36 | int N = flowerbed.size(); 37 | for (int idx = 0; idx < N; idx++) { 38 | if (flowerbed[idx] == 1) continue; 39 | if ((idx == 0 || flowerbed[idx - 1] == 0) && 40 | (idx == N - 1 || flowerbed[idx + 1] == 0)) { 41 | flowerbed[idx] = 1; 42 | n -= 1; 43 | } 44 | } 45 | 46 | return n <= 0; 47 | } 48 | }; -------------------------------------------------------------------------------- /day-25.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Question: Given an array of non-negative integers, you are initially positioned at the first index of the array. 3 | 4 | Each element in the array represents your maximum jump length at that position. 5 | 6 | Determine if you are able to reach the last index. 7 | 8 | Example 1: 9 | 10 | Input: [2,3,1,1,4] 11 | Output: true 12 | Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. 13 | Example 2: 14 | 15 | Input: [3,2,1,0,4] 16 | Output: false 17 | Explanation: You will always arrive at index 3 no matter what. Its maximum 18 | jump length is 0, which makes it impossible to reach the last index. 19 | */ 20 | 21 | // O(N) & O(1) beats 99.81 % of cpp submissions. 22 | class Solution { 23 | public: 24 | bool canJump(vector& nums) { 25 | int lastGoodIndex = nums.size() - 1; 26 | 27 | for (int i = nums.size() - 1; i >= 0; --i) { 28 | if (i + nums[i] >= lastGoodIndex) { 29 | lastGoodIndex = i; 30 | } 31 | } 32 | 33 | return lastGoodIndex == 0; 34 | } 35 | }; -------------------------------------------------------------------------------- /day-251.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Spiral Matrix II 3 | 4 | Solution 5 | Given a positive integer n, generate an n x n matrix filled with elements from 1 6 | to n2 in spiral order. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | 13 | Input: n = 3 14 | Output: [[1,2,3],[8,9,4],[7,6,5]] 15 | Example 2: 16 | 17 | Input: n = 1 18 | Output: [[1]] 19 | 20 | 21 | Constraints: 22 | 23 | 1 <= n <= 20 24 | */ 25 | 26 | // Simple O(N * N) solution 27 | class Solution { 28 | public: 29 | vector> generateMatrix(int n) { 30 | vector> result(n, vector(n)); 31 | 32 | int level = ceil(n / 2), count = 1; 33 | 34 | for (int l = 0; l <= level; ++l) { 35 | for (int a = l; a < n - l; ++a) result[l][a] = count++; 36 | 37 | for (int b = l + 1; b < n - l; ++b) result[b][n - l - 1] = count++; 38 | 39 | for (int c = l + 1; c < n - l; ++c) 40 | result[n - l - 1][n - c - 1] = count++; 41 | 42 | for (int d = l + 1; d < n - l - 1; ++d) 43 | result[n - d - 1][l] = count++; 44 | } 45 | 46 | return result; 47 | } 48 | }; -------------------------------------------------------------------------------- /day-252.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Pairs of Songs With Total Durations Divisible by 60 3 | 4 | Solution 5 | You are given a list of songs where the ith song has a duration of time[i] 6 | seconds. 7 | 8 | Return the number of pairs of songs for which their total duration in seconds is 9 | divisible by 60. Formally, we want the number of indices i, j such that i < j 10 | with (time[i] + time[j]) % 60 == 0. 11 | 12 | 13 | 14 | Example 1: 15 | 16 | Input: time = [30,20,150,100,40] 17 | Output: 3 18 | Explanation: Three pairs have a total duration divisible by 60: 19 | (time[0] = 30, time[2] = 150): total duration 180 20 | (time[1] = 20, time[3] = 100): total duration 120 21 | (time[1] = 20, time[4] = 40): total duration 60 22 | Example 2: 23 | 24 | Input: time = [60,60,60] 25 | Output: 3 26 | Explanation: All three pairs have a total duration of 120, which is divisible 27 | by 60. 28 | 29 | 30 | Constraints: 31 | 32 | 1 <= time.length <= 6 * 104 33 | 1 <= time[i] <= 500 34 | */ 35 | 36 | // Simple linear based solution 37 | class Solution { 38 | public: 39 | int numPairsDivisibleBy60(vector& time) { 40 | int freqs[60] = {}, res = 0; 41 | for (int t : time) freqs[t % 60]++; 42 | for (int i = 1; i < 30; i++) res += freqs[i] * freqs[60 - i]; 43 | res += freqs[0] * (freqs[0] - 1) / 2 + freqs[30] * (freqs[30] - 1) / 2; 44 | return res; 45 | } 46 | }; -------------------------------------------------------------------------------- /day-254.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Valid Mountain Array 3 | 4 | Solution 5 | Given an array of integers arr, return true if and only if it is a valid 6 | mountain array. 7 | 8 | Recall that arr is a mountain array if and only if: 9 | 10 | arr.length >= 3 11 | There exists some i with 0 < i < arr.length - 1 such that: 12 | arr[0] < arr[1] < ... < arr[i - 1] < A[i] 13 | arr[i] > arr[i + 1] > ... > arr[arr.length - 1] 14 | 15 | 16 | 17 | Example 1: 18 | 19 | Input: arr = [2,1] 20 | Output: false 21 | Example 2: 22 | 23 | Input: arr = [3,5,5] 24 | Output: false 25 | Example 3: 26 | 27 | Input: arr = [0,3,2,1] 28 | Output: true 29 | 30 | 31 | Constraints: 32 | 33 | 1 <= arr.length <= 104 34 | 0 <= arr[i] <= 104 35 | 36 | */ 37 | 38 | // Simple linear solution 39 | class Solution { 40 | public: 41 | bool validMountainArray(vector& arr) { 42 | int N = arr.size(); 43 | if (N < 3) return false; 44 | int start = 1; 45 | 46 | while ((start < N) && arr[start] > arr[start - 1]) { 47 | start += 1; 48 | } 49 | 50 | if (start == N || start == 1) return false; 51 | 52 | while ((start < N) && arr[start] < arr[start - 1]) { 53 | start += 1; 54 | } 55 | 56 | return start == N; 57 | } 58 | }; 59 | -------------------------------------------------------------------------------- /day-257.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Burst Balloons 3 | 4 | Solution 5 | Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number 6 | on it represented by array nums. You are asked to burst all the balloons. If the 7 | you burst balloon i you will get nums[left] * nums[i] * nums[right] coins. Here 8 | left and right are adjacent indices of i. After the burst, the left and right 9 | then becomes adjacent. 10 | 11 | Find the maximum coins you can collect by bursting the balloons wisely. 12 | 13 | Note: 14 | 15 | You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can not 16 | burst them. 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100 Example: 17 | 18 | Input: [3,1,5,8] 19 | Output: 167 20 | Explanation: nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> [] 21 | coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167 22 | 23 | */ 24 | 25 | // Solved using dynamic programming 26 | // TC: O(N*N*N) 27 | class Solution { 28 | public: 29 | int maxCoins(vector& nums) { 30 | vector num{1}; 31 | num.insert(num.end(), nums.begin(), nums.end()); 32 | num.push_back(1); 33 | int sz = num.size(); 34 | vector> dp(sz, vector(sz)); 35 | for (int i = 2; i < sz; ++i) { 36 | for (int j = i - 1; j >= 1; --j) { 37 | for (int k = j - 1; k >= 0; --k) { 38 | dp[k][i] = max(dp[k][i], num[k] * num[j] * num[i] + 39 | dp[k][j] + dp[j][i]); 40 | } 41 | } 42 | } 43 | return dp[0][sz - 1]; 44 | } 45 | }; -------------------------------------------------------------------------------- /day-258.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Palindrome Partitioning 3 | 4 | Solution 5 | Given a string s, partition s such that every substring of the partition is a 6 | palindrome. Return all possible palindrome partitioning of s. 7 | 8 | A palindrome string is a string that reads the same backward as forward. 9 | 10 | 11 | 12 | Example 1: 13 | 14 | Input: s = "aab" 15 | Output: [["a","a","b"],["aa","b"]] 16 | Example 2: 17 | 18 | Input: s = "a" 19 | Output: [["a"]] 20 | 21 | 22 | Constraints: 23 | 24 | 1 <= s.length <= 16 25 | s contains only lowercase English letters. 26 | */ 27 | 28 | // Solved using backtracking 29 | class Solution { 30 | public: 31 | bool isPalindrome(string s) { 32 | int l = 0; 33 | int r = s.size() - 1; 34 | while (l < r) { 35 | if (s[l++] != s[r--]) { 36 | return false; 37 | } 38 | } 39 | return true; 40 | } 41 | void helper(string s, vector> &result, vector temp) { 42 | if (s.size() == 0) { 43 | result.push_back(temp); 44 | } 45 | for (int i = 0; i < s.size(); i++) { 46 | string leftPar = s.substr(0, i + 1); 47 | if (isPalindrome(leftPar)) { 48 | temp.push_back(leftPar); 49 | helper(s.substr(i + 1), result, temp); 50 | temp.pop_back(); 51 | } 52 | } 53 | } 54 | vector> partition(string s) { 55 | vector> result; 56 | vector temp; 57 | helper(s, result, temp); 58 | return result; 59 | } 60 | }; -------------------------------------------------------------------------------- /day-259.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Squares of a Sorted Array 3 | 4 | Solution 5 | Given an integer array nums sorted in non-decreasing order, return an array of 6 | the squares of each number sorted in non-decreasing order. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: nums = [-4,-1,0,3,10] 13 | Output: [0,1,9,16,100] 14 | Explanation: After squaring, the array becomes [16,1,0,9,100]. 15 | After sorting, it becomes [0,1,9,16,100]. 16 | Example 2: 17 | 18 | Input: nums = [-7,-3,2,3,11] 19 | Output: [4,9,9,49,121] 20 | 21 | 22 | Constraints: 23 | 24 | 1 <= nums.length <= 104 25 | -104 <= nums[i] <= 104 26 | nums is sorted in non-decreasing order. 27 | */ 28 | 29 | // Simple sorting solution 30 | class Solution { 31 | public: 32 | vector sortedSquares(vector& nums) { 33 | int N = nums.size(); 34 | 35 | for (int idx = 0; idx < N; idx++) { 36 | nums[idx] = nums[idx] * nums[idx]; 37 | } 38 | 39 | sort(nums.begin(), nums.end()); 40 | return nums; 41 | } 42 | }; -------------------------------------------------------------------------------- /day-260.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Validate Binary Search Tree 3 | 4 | Given the root of a binary tree, determine if it is a valid binary search tree 5 | (BST). 6 | 7 | A valid BST is defined as follows: 8 | 9 | The left subtree of a node contains only nodes with keys less than the node's 10 | key. The right subtree of a node contains only nodes with keys greater than the 11 | node's key. Both the left and right subtrees must also be binary search trees. 12 | 13 | 14 | Example 1: 15 | 16 | 17 | Input: root = [2,1,3] 18 | Output: true 19 | Example 2: 20 | 21 | 22 | Input: root = [5,1,4,null,null,3,6] 23 | Output: false 24 | Explanation: The root node's value is 5 but its right child's value is 4. 25 | 26 | 27 | Constraints: 28 | 29 | The number of nodes in the tree is in the range [1, 104]. 30 | -231 <= Node.val <= 231 - 1 31 | 32 | */ 33 | 34 | // Simple recursive solution to validate BST 35 | 36 | class Solution { 37 | public: 38 | vector treeList; 39 | bool isValidBST(TreeNode* root) { 40 | inorder(root); 41 | for (int i = 1; i < treeList.size(); i++) { 42 | if (treeList[i] <= treeList[i - 1]) { 43 | return false; 44 | } 45 | } 46 | 47 | return true; 48 | } 49 | 50 | void inorder(TreeNode* root) { 51 | if (root == NULL) return; 52 | inorder(root->left); 53 | treeList.push_back(root->val); 54 | inorder(root->right); 55 | } 56 | }; -------------------------------------------------------------------------------- /day-261.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 4Sum II 3 | 4 | Solution 5 | Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, 6 | l) there are such that A[i] + B[j] + C[k] + D[l] is zero. 7 | 8 | To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 9 | 500. All integers are in the range of -228 to 228 - 1 and the result is 10 | guaranteed to be at most 231 - 1. 11 | 12 | Example: 13 | 14 | Input: 15 | A = [ 1, 2] 16 | B = [-2,-1] 17 | C = [-1, 2] 18 | D = [ 0, 2] 19 | 20 | Output: 21 | 2 22 | 23 | Explanation: 24 | The two tuples are: 25 | 1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0 26 | 2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0 27 | 28 | 29 | */ 30 | 31 | // O(N * N) solution 32 | class Solution { 33 | public: 34 | int fourSumCount(vector& A, vector& B, vector& C, 35 | vector& D) { 36 | int res = 0; 37 | unordered_map m(A.size() * B.size()); 38 | for (int i = 0; i < A.size(); i++) { 39 | for (int j = 0; j < B.size(); j++) { 40 | m[A[i] + B[j]]++; 41 | } 42 | } 43 | for (int i = 0; i < C.size(); i++) { 44 | for (int j = 0; j < D.size(); j++) { 45 | const auto it = m.find(-C[i] - D[j]); 46 | if (it != m.end()) { 47 | res += it->second; 48 | } 49 | } 50 | } 51 | return res; 52 | } 53 | }; -------------------------------------------------------------------------------- /day-262.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Increasing Triplet Subsequence 3 | 4 | Solution 5 | Given an integer array nums, return true if there exists a triple of indices (i, 6 | j, k) such that i < j < k and nums[i] < nums[j] < nums[k]. If no such indices 7 | exists, return false. 8 | 9 | 10 | 11 | Example 1: 12 | 13 | Input: nums = [1,2,3,4,5] 14 | Output: true 15 | Explanation: Any triplet where i < j < k is valid. 16 | Example 2: 17 | 18 | Input: nums = [5,4,3,2,1] 19 | Output: false 20 | Explanation: No triplet exists. 21 | Example 3: 22 | 23 | Input: nums = [2,1,5,0,4,6] 24 | Output: true 25 | Explanation: The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 26 | < nums[5] == 6. 27 | 28 | 29 | Constraints: 30 | 31 | 1 <= nums.length <= 105 32 | -231 <= nums[i] <= 231 - 1 33 | 34 | 35 | Follow up: Could you implement a solution that runs in O(n) time complexity and 36 | O(1) space complexity? 37 | */ 38 | 39 | // Simple O(N) & O(1) solution 40 | class Solution { 41 | public: 42 | bool increasingTriplet(vector& nums) { 43 | int first = INT_MAX; 44 | int second = INT_MAX; 45 | 46 | for (int n : nums) { 47 | if (n <= first) 48 | first = n; 49 | else if (n <= second) 50 | second = n; 51 | else 52 | return true; 53 | } 54 | 55 | return false; 56 | } 57 | }; -------------------------------------------------------------------------------- /day-265.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Smallest Range II 3 | 4 | Solution 5 | Given an array A of integers, for each integer A[i] we need to choose either x = 6 | -K or x = K, and add x to A[i] (only once). 7 | 8 | After this process, we have some array B. 9 | 10 | Return the smallest possible difference between the maximum value of B and the 11 | minimum value of B. 12 | 13 | 14 | 15 | Example 1: 16 | 17 | Input: A = [1], K = 0 18 | Output: 0 19 | Explanation: B = [1] 20 | Example 2: 21 | 22 | Input: A = [0,10], K = 2 23 | Output: 6 24 | Explanation: B = [2,8] 25 | Example 3: 26 | 27 | Input: A = [1,3,6], K = 3 28 | Output: 3 29 | Explanation: B = [4,6,3] 30 | 31 | 32 | Note: 33 | 34 | 1 <= A.length <= 10000 35 | 0 <= A[i] <= 10000 36 | 0 <= K <= 10000 37 | 38 | */ 39 | 40 | // Simple greedy solution 41 | class Solution { 42 | public: 43 | int smallestRangeII(vector& A, int K) { 44 | const int n = A.size(); 45 | sort(A.begin(), A.end()); 46 | int mx = A.back(), mn = A.front(), res = mx - mn; 47 | for (int i = 0; i < n - 1; i++) { 48 | mx = max(mx, A[i] + 2 * K); 49 | mn = min(A[i + 1], A[0] + 2 * K); 50 | res = min(res, mx - mn); 51 | } 52 | return res; 53 | } 54 | }; -------------------------------------------------------------------------------- /day-266.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Balanced Binary Tree 3 | 4 | Given a binary tree, determine if it is height-balanced. 5 | 6 | For this problem, a height-balanced binary tree is defined as: 7 | 8 | a binary tree in which the left and right subtrees of every node differ in 9 | height by no more than 1. 10 | 11 | 12 | 13 | Example 1: 14 | 15 | 16 | Input: root = [3,9,20,null,null,15,7] 17 | Output: true 18 | Example 2: 19 | 20 | 21 | Input: root = [1,2,2,3,3,null,null,4,4] 22 | Output: false 23 | Example 3: 24 | 25 | Input: root = [] 26 | Output: true 27 | 28 | 29 | Constraints: 30 | 31 | The number of nodes in the tree is in the range [0, 5000]. 32 | -104 <= Node.val <= 104 33 | */ 34 | 35 | // Simple O(H) solution 36 | // H = height of the tree 37 | class Solution { 38 | public: 39 | int height(TreeNode* node) { 40 | if (node == NULL) return 0; 41 | int left = height(node->left); 42 | int right = height(node->right); 43 | if (left == -1 || right == -1 || abs(left - right) > 1) return -1; 44 | return max(left, right) + 1; 45 | } 46 | 47 | bool isBalanced(TreeNode* root) { return height(root) != -1; } 48 | }; -------------------------------------------------------------------------------- /day-267.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PranjalAgni/210DaysLeetCode/b900c11bc50a0baa122e6cef302c1b0c8cb09723/day-267.cpp -------------------------------------------------------------------------------- /day-268.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PranjalAgni/210DaysLeetCode/b900c11bc50a0baa122e6cef302c1b0c8cb09723/day-268.cpp -------------------------------------------------------------------------------- /day-269.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Diagonal Traverse 3 | 4 | Solution 5 | Given a matrix of M x N elements (M rows, N columns), return all elements of the 6 | matrix in diagonal order as shown in the below image. 7 | 8 | 9 | 10 | Example: 11 | 12 | Input: 13 | [ 14 | [ 1, 2, 3 ], 15 | [ 4, 5, 6 ], 16 | [ 7, 8, 9 ] 17 | ] 18 | 19 | Output: [1,2,4,7,5,3,6,8,9] 20 | 21 | Explanation: 22 | 23 | 24 | 25 | Note: 26 | 27 | The total number of elements of the given matrix will not exceed 10,000. 28 | */ 29 | 30 | // Simple O(row * col) solution 31 | 32 | class Solution { 33 | public: 34 | vector findDiagonalOrder(vector>& matrix) { 35 | int i = 0, j = 0; 36 | int n = matrix.size(); 37 | int m = n ? matrix[0].size() : 0; 38 | int x = -1, y = 1; 39 | vector res; 40 | while (res.size() < n * m) { 41 | if (i == n || j == m || j < 0 || i < 0) { 42 | swap(x, y); 43 | 44 | if (j == m) 45 | 46 | i += 2, j--; 47 | else if (i == n) 48 | j += 2, i--; 49 | else { 50 | i += i < 0; 51 | j += j < 0; 52 | } 53 | } 54 | res.push_back(matrix[i][j]); 55 | i += x; 56 | j += y; 57 | } 58 | return res; 59 | } 60 | }; -------------------------------------------------------------------------------- /day-27.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Question: Maximal Square 3 | Solution 4 | Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. 5 | 6 | Example: 7 | 8 | Input: 9 | 10 | 1 0 1 0 0 11 | 1 0 1 1 1 12 | 1 1 1 1 1 13 | 1 0 0 1 0 14 | 15 | Output: 4 16 | */ 17 | 18 | class Solution { 19 | public: 20 | int maximalSquare(vector>& matrix) { 21 | int rows = matrix.size(); 22 | if (rows == 0) return 0; 23 | int cols = matrix[0].size(); 24 | 25 | if (cols == 0) return 0; 26 | 27 | vector> dp(rows, vector(cols, 0)); 28 | int height = 0; 29 | 30 | for (int i = 0; i < rows; ++i) { 31 | for (int j = 0; j < cols; j++) { 32 | if (i == 0 || j == 0) { 33 | if (matrix[i][j] == '1') { 34 | dp[i][j] = 1; 35 | height = max(height, dp[i][j]); 36 | } 37 | } else { 38 | if (matrix[i][j] == '1') { 39 | dp[i][j] = 1 + min({dp[i - 1][j], dp[i - 1][j - 1], dp[i][j - 1]}); 40 | height = max(height, dp[i][j]); 41 | } 42 | } 43 | } 44 | } 45 | 46 | return height * height; 47 | } 48 | }; -------------------------------------------------------------------------------- /day-280.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Remove Duplicates from Sorted List II 3 | 4 | Solution 5 | Given the head of a sorted linked list, delete all nodes that have duplicate 6 | numbers, leaving only distinct numbers from the original list. Return the linked 7 | list sorted as well. 8 | 9 | 10 | 11 | Example 1: 12 | 13 | 14 | Input: head = [1,2,3,3,4,4,5] 15 | Output: [1,2,5] 16 | Example 2: 17 | 18 | 19 | Input: head = [1,1,1,2,3] 20 | Output: [2,3] 21 | 22 | 23 | Constraints: 24 | 25 | The number of nodes in the list is in the range [0, 300]. 26 | -100 <= Node.val <= 100 27 | The list is guaranteed to be sorted in ascending order. 28 | 29 | */ 30 | 31 | // Simple O(N) solution 32 | class Solution { 33 | public: 34 | ListNode* deleteDuplicates(ListNode* head) { 35 | if (!head or !head->next) return head; 36 | if (head->val == head->next->val) { 37 | int val = head->val; 38 | while (head and head->val == val) head = head->next; 39 | return deleteDuplicates(head); 40 | } else { 41 | head->next = deleteDuplicates(head->next); 42 | return head; 43 | } 44 | } 45 | }; -------------------------------------------------------------------------------- /day-282.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Check If Two String Arrays are Equivalent 3 | 4 | Solution 5 | Given two string arrays word1 and word2, return true if the two arrays represent 6 | the same string, and false otherwise. 7 | 8 | A string is represented by an array if the array elements concatenated in order 9 | forms the string. 10 | 11 | 12 | 13 | Example 1: 14 | 15 | Input: word1 = ["ab", "c"], word2 = ["a", "bc"] 16 | Output: true 17 | Explanation: 18 | word1 represents string "ab" + "c" -> "abc" 19 | word2 represents string "a" + "bc" -> "abc" 20 | The strings are the same, so return true. 21 | Example 2: 22 | 23 | Input: word1 = ["a", "cb"], word2 = ["ab", "c"] 24 | Output: false 25 | Example 3: 26 | 27 | Input: word1 = ["abc", "d", "defg"], word2 = ["abcddefg"] 28 | Output: true 29 | 30 | 31 | Constraints: 32 | 33 | 1 <= word1.length, word2.length <= 103 34 | 1 <= word1[i].length, word2[i].length <= 103 35 | 1 <= sum(word1[i].length), sum(word2[i].length) <= 103 36 | word1[i] and word2[i] consist of lowercase letters. 37 | 38 | */ 39 | 40 | // Simple linear time solution 41 | class Solution { 42 | public: 43 | bool arrayStringsAreEqual(vector& word1, vector& word2) { 44 | int N = word1.size(); 45 | int M = word2.size(); 46 | 47 | string str1 = ""; 48 | string str2 = ""; 49 | 50 | for (int idx = 0; idx < N; idx++) str1 += word1[idx]; 51 | for (int idx = 0; idx < M; idx++) str2 += word2[idx]; 52 | 53 | return str1 == str2; 54 | } 55 | }; -------------------------------------------------------------------------------- /day-285.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Merge Sorted Array 3 | 4 | Solution 5 | Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one 6 | sorted array. 7 | 8 | The number of elements initialized in nums1 and nums2 are m and n respectively. 9 | You may assume that nums1 has enough space (size that is equal to m + n) to hold 10 | additional elements from nums2. 11 | 12 | 13 | 14 | Example 1: 15 | 16 | Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 17 | Output: [1,2,2,3,5,6] 18 | Example 2: 19 | 20 | Input: nums1 = [1], m = 1, nums2 = [], n = 0 21 | Output: [1] 22 | 23 | 24 | Constraints: 25 | 26 | 0 <= n, m <= 200 27 | 1 <= n + m <= 200 28 | nums1.length == m + n 29 | nums2.length == n 30 | -109 <= nums1[i], nums2[i] <= 109 31 | */ 32 | 33 | // Simple O(N) solution 34 | class Solution { 35 | public: 36 | void merge(vector& nums1, int m, vector& nums2, int n) { 37 | int i = m - 1; 38 | int j = n - 1; 39 | int k = m + n - 1; 40 | 41 | while (i >= 0 and j >= 0) { 42 | if (nums1[i] > nums2[j]) { 43 | nums1[k--] = nums1[i--]; 44 | } else { 45 | nums1[k--] = nums2[j--]; 46 | } 47 | } 48 | while (j >= 0) { 49 | nums1[k--] = nums2[j--]; 50 | } 51 | } 52 | }; -------------------------------------------------------------------------------- /day-287.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Boats to Save People 3 | 4 | Solution 5 | The i-th person has weight people[i], and each boat can carry a maximum weight 6 | of limit. 7 | 8 | Each boat carries at most 2 people at the same time, provided the sum of the 9 | weight of those people is at most limit. 10 | 11 | Return the minimum number of boats to carry every given person. (It is 12 | guaranteed each person can be carried by a boat.) 13 | 14 | 15 | 16 | Example 1: 17 | 18 | Input: people = [1,2], limit = 3 19 | Output: 1 20 | Explanation: 1 boat (1, 2) 21 | Example 2: 22 | 23 | Input: people = [3,2,2,1], limit = 3 24 | Output: 3 25 | Explanation: 3 boats (1, 2), (2) and (3) 26 | Example 3: 27 | 28 | Input: people = [3,5,3,4], limit = 5 29 | Output: 4 30 | Explanation: 4 boats (3), (3), (4), (5) 31 | Note: 32 | 33 | 1 <= people.length <= 50000 34 | 1 <= people[i] <= limit <= 30000 35 | */ 36 | 37 | // O(N) two pointer solution 38 | class Solution { 39 | public: 40 | int numRescueBoats(vector& people, int limit) { 41 | sort(people.begin(), people.end()); 42 | int n = people.size(); 43 | int l = 0, r = n - 1; 44 | int ans = 0; 45 | 46 | while (l <= r) { 47 | if (people[r] + people[l] <= limit) l++; 48 | 49 | r--; 50 | ans++; 51 | } 52 | 53 | return ans; 54 | } 55 | }; -------------------------------------------------------------------------------- /day-29.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Binary Tree Maximum Path Sum 3 | 4 | Given a non-empty binary tree, find the maximum path sum. 5 | 6 | For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root. 7 | 8 | Example 1: 9 | 10 | Input: [1,2,3] 11 | 12 | 1 13 | / \ 14 | 2 3 15 | 16 | Output: 6 17 | Example 2: 18 | 19 | Input: [-10,9,20,null,null,15,7] 20 | 21 | -10 22 | / \ 23 | 9 20 24 | / \ 25 | 15 7 26 | 27 | Output: 42 28 | */ 29 | class Solution { 30 | int max_path_sum; 31 | 32 | public: 33 | int maxPathSum(TreeNode* root) { 34 | max_path_sum = INT_MIN; 35 | pathSum(root); 36 | return max_path_sum; 37 | } 38 | 39 | int pathSum(TreeNode* node) { 40 | if (node == NULL) return 0; 41 | int left = max(0, pathSum(node->left)); 42 | int right = max(0, pathSum(node->right)); 43 | max_path_sum = max(max_path_sum, left + right + node->val); 44 | return max(left, right) + node->val; 45 | } 46 | }; -------------------------------------------------------------------------------- /day-290.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Kth Largest Element in an Array 3 | 4 | Solution 5 | Find the kth largest element in an unsorted array. Note that it is the kth 6 | largest element in the sorted order, not the kth distinct element. 7 | 8 | Example 1: 9 | 10 | Input: [3,2,1,5,6,4] and k = 2 11 | Output: 5 12 | Example 2: 13 | 14 | Input: [3,2,3,1,2,4,5,5,6] and k = 4 15 | Output: 4 16 | Note: 17 | You may assume k is always valid, 1 ≤ k ≤ array's length. 18 | 19 | 20 | */ 21 | 22 | // Simple O(N) solution 23 | class Solution { 24 | public: 25 | int findKthLargest(vector& nums, int k) { 26 | priority_queue pq; 27 | for (int i = 0; i < nums.size(); i++) { 28 | pq.push(nums[i]); 29 | } 30 | while (pq.empty() == false and k > 1) { 31 | pq.top(); 32 | pq.pop(); 33 | k--; 34 | } 35 | return pq.top(); 36 | } 37 | }; -------------------------------------------------------------------------------- /day-291.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Count Sorted Vowel Strings 3 | 4 | Solution 5 | Given an integer n, return the number of strings of length n that consist only 6 | of vowels (a, e, i, o, u) and are lexicographically sorted. 7 | 8 | A string s is lexicographically sorted if for all valid i, s[i] is the same as 9 | or comes before s[i+1] in the alphabet. 10 | 11 | 12 | 13 | Example 1: 14 | 15 | Input: n = 1 16 | Output: 5 17 | Explanation: The 5 sorted strings that consist of vowels only are 18 | ["a","e","i","o","u"]. Example 2: 19 | 20 | Input: n = 2 21 | Output: 15 22 | Explanation: The 15 sorted strings that consist of vowels only are 23 | ["aa","ae","ai","ao","au","ee","ei","eo","eu","ii","io","iu","oo","ou","uu"]. 24 | Note that "ea" is not a valid string since 'e' comes after 'a' in the alphabet. 25 | Example 3: 26 | 27 | Input: n = 33 28 | Output: 66045 29 | 30 | 31 | Constraints: 32 | 33 | 1 <= n <= 50 34 | */ 35 | 36 | // We can assume that there would be 4 transition states 37 | // i.e. from a->e->i->o->u 38 | // and along with these transitions there would be n vowels in sorted order 39 | // hence we have total n+4 locations and after choosing 4 of them 40 | // (for the transitions to take place) 41 | // the elements at all other positions got fixed 42 | // hence the answer is n+4 C 4. 43 | 44 | class Solution { 45 | public: 46 | int countVowelStrings(int n) { 47 | return (n + 1) * (n + 2) * (n + 3) * (n + 4) / 24; 48 | } 49 | }; -------------------------------------------------------------------------------- /day-292.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Max Number of K-Sum Pairs 3 | 4 | Solution 5 | You are given an integer array nums and an integer k. 6 | 7 | In one operation, you can pick two numbers from the array whose sum equals k and 8 | remove them from the array. 9 | 10 | Return the maximum number of operations you can perform on the array. 11 | 12 | 13 | 14 | Example 1: 15 | 16 | Input: nums = [1,2,3,4], k = 5 17 | Output: 2 18 | Explanation: Starting with nums = [1,2,3,4]: 19 | - Remove numbers 1 and 4, then nums = [2,3] 20 | - Remove numbers 2 and 3, then nums = [] 21 | There are no more pairs that sum up to 5, hence a total of 2 operations. 22 | Example 2: 23 | 24 | Input: nums = [3,1,3,4,3], k = 6 25 | Output: 1 26 | Explanation: Starting with nums = [3,1,3,4,3]: 27 | - Remove the first two 3's, then nums = [1,4,3] 28 | There are no more pairs that sum up to 6, hence a total of 1 operation. 29 | 30 | 31 | Constraints: 32 | 33 | 1 <= nums.length <= 105 34 | 1 <= nums[i] <= 109 35 | 1 <= k <= 109 36 | 37 | */ 38 | 39 | // Simple O(NlogN) solution 40 | // SC: O(1) 41 | class Solution { 42 | public: 43 | int maxOperations(vector& nums, int k) { 44 | sort(nums.begin(), nums.end()); 45 | int start = 0; 46 | int end = nums.size() - 1; 47 | int count = 0; 48 | 49 | while (start < end) { 50 | int sum = nums[start] + nums[end]; 51 | 52 | if (sum > k) { 53 | end--; 54 | } else if (sum < k) { 55 | start++; 56 | } else { 57 | end--; 58 | start++; 59 | count++; 60 | } 61 | } 62 | return count; 63 | } 64 | }; -------------------------------------------------------------------------------- /day-293.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Longest Palindromic Substring 3 | 4 | Solution 5 | Given a string s, return the longest palindromic substring in s. 6 | 7 | 8 | 9 | Example 1: 10 | 11 | Input: s = "babad" 12 | Output: "bab" 13 | Note: "aba" is also a valid answer. 14 | Example 2: 15 | 16 | Input: s = "cbbd" 17 | Output: "bb" 18 | Example 3: 19 | 20 | Input: s = "a" 21 | Output: "a" 22 | Example 4: 23 | 24 | Input: s = "ac" 25 | Output: "a" 26 | 27 | 28 | Constraints: 29 | 30 | 1 <= s.length <= 1000 31 | s consist of only digits and English letters (lower-case and/or upper-case), 32 | */ 33 | 34 | // Simple solution 35 | class Solution { 36 | public: 37 | string longestPalindrome(string s) { 38 | if (s.size() <= 1) return s; 39 | int start = 0, length = 1; 40 | 41 | for (unsigned i = 1; 42 | i < s.size() * 2 - 1 && (s.size() - 1 - i / 2) >= length / 2; 43 | i++) { 44 | int left = i / 2, right = i % 2 == 0 ? left : left + 1; 45 | 46 | if (s[right] != s[left]) continue; 47 | 48 | do { 49 | right++; 50 | left--; 51 | } while (right <= s.size() - 1 && left >= 0 && s[right] == s[left]); 52 | 53 | if (right - left - 1 > length) { 54 | start = left + 1; 55 | length = right - left - 1; 56 | } 57 | } 58 | 59 | return s.substr(start, length); 60 | } 61 | }; -------------------------------------------------------------------------------- /day-294.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Valid Parentheses 3 | Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', 4 | determine if the input string is valid. 5 | 6 | An input string is valid if: 7 | 8 | Open brackets must be closed by the same type of brackets. 9 | Open brackets must be closed in the correct order. 10 | 11 | 12 | Example 1: 13 | 14 | Input: s = "()" 15 | Output: true 16 | Example 2: 17 | 18 | Input: s = "()[]{}" 19 | Output: true 20 | Example 3: 21 | 22 | Input: s = "(]" 23 | Output: false 24 | Example 4: 25 | 26 | Input: s = "([)]" 27 | Output: false 28 | Example 5: 29 | 30 | Input: s = "{[]}" 31 | Output: true 32 | 33 | 34 | Constraints: 35 | 36 | 1 <= s.length <= 104 37 | s consists of parentheses only '()[]{}'. 38 | */ 39 | 40 | // Simple stack solution 41 | class Solution { 42 | public: 43 | bool isValid(string s) { 44 | std::vector stack; 45 | for (int i = 0; i < s.length(); i++) { 46 | if (s[i] == '{') 47 | stack.push_back('}'); 48 | else if (s[i] == '(') 49 | stack.push_back(')'); 50 | else if (s[i] == '[') 51 | stack.push_back(']'); 52 | else { 53 | if ((stack.empty()) || (s[i] != stack[stack.size() - 1])) 54 | return false; 55 | stack.pop_back(); 56 | } 57 | } 58 | return stack.empty(); 59 | } 60 | }; -------------------------------------------------------------------------------- /day-299.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Merge k Sorted Lists 3 | 4 | Solution 5 | You are given an array of k linked-lists lists, each linked-list is sorted in 6 | ascending order. 7 | 8 | Merge all the linked-lists into one sorted linked-list and return it. 9 | 10 | 11 | 12 | Example 1: 13 | 14 | Input: lists = [[1,4,5],[1,3,4],[2,6]] 15 | Output: [1,1,2,3,4,4,5,6] 16 | Explanation: The linked-lists are: 17 | [ 18 | 1->4->5, 19 | 1->3->4, 20 | 2->6 21 | ] 22 | merging them into one sorted list: 23 | 1->1->2->3->4->4->5->6 24 | Example 2: 25 | 26 | Input: lists = [] 27 | Output: [] 28 | Example 3: 29 | 30 | Input: lists = [[]] 31 | Output: [] 32 | 33 | 34 | Constraints: 35 | 36 | k == lists.length 37 | 0 <= k <= 10^4 38 | 0 <= lists[i].length <= 500 39 | -10^4 <= lists[i][j] <= 10^4 40 | lists[i] is sorted in ascending order. 41 | The sum of lists[i].length won't exceed 10^4. 42 | */ 43 | 44 | // Recursive solution to merge the list 45 | class Solution { 46 | public: 47 | ListNode* merge2Lists(ListNode* l1, ListNode* l2) { 48 | if (!l1) return l2; 49 | if (!l2) return l1; 50 | ListNode* head = l1->val <= l2->val ? l1 : l2; 51 | head->next = l1->val <= l2->val ? merge2Lists(l1->next, l2) 52 | : merge2Lists(l1, l2->next); 53 | return head; 54 | } 55 | 56 | ListNode* mergeKLists(vector& lists) { 57 | if (lists.size() == 0) return NULL; 58 | 59 | ListNode* head = lists[0]; 60 | 61 | for (int i = 1; i < lists.size(); i++) 62 | head = merge2Lists(head, lists[i]); 63 | 64 | return head; 65 | } 66 | }; -------------------------------------------------------------------------------- /day-3.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Question: Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. 3 | */ 4 | 5 | // O(N) & O(1) beat 99.8% cpp solutions 6 | class Solution { 7 | public: 8 | int maxSubArray(vector& nums) { 9 | int sum = 0; 10 | int maxSum = INT_MIN; 11 | for (int i = 0; i < nums.size(); i++) { 12 | sum = max(sum + nums[i], nums[i]); 13 | maxSum = max(sum, maxSum); 14 | } 15 | return maxSum; 16 | } 17 | }; -------------------------------------------------------------------------------- /day-30.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a binary tree where each path going from the root to any leaf form a valid sequence, check if a given string is a valid sequence in such binary tree. 3 | 4 | We get the given string from the concatenation of an array of integers arr and the concatenation of all values of the nodes along a path results in a sequence in the given binary tree. 5 | 6 | Example 1: 7 | Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,1,0,1] 8 | Output: true 9 | Explanation: 10 | The path 0 -> 1 -> 0 -> 1 is a valid sequence (green color in the figure). 11 | Other valid sequences are: 12 | 0 -> 1 -> 1 -> 0 13 | 0 -> 0 -> 0 14 | 15 | Example 2: 16 | Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,0,1] 17 | Output: false 18 | Explanation: The path 0 -> 0 -> 1 does not exist, therefore it is not even a sequence. 19 | 20 | Example 3: 21 | Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,1,1] 22 | Output: false 23 | Explanation: The path 0 -> 1 -> 1 is a sequence, but it is not a valid sequence. 24 | */ 25 | 26 | class Solution { 27 | public: 28 | bool isValidSequence(TreeNode* root, vector& arr) { 29 | if (!root) return arr.size() == 0; 30 | return isValid(root, arr, 0); 31 | } 32 | 33 | bool isValid(TreeNode* root, vector& arr, int idx) { 34 | if (root->val != arr[idx]) return false; 35 | if (idx == arr.size() - 1) return !root->left && !root->right; 36 | return (root->left && isValid(root->left, arr, idx + 1)) || (root->right && isValid(root->right, arr, idx + 1)); 37 | } 38 | }; -------------------------------------------------------------------------------- /day-31.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | First Bad Version 3 | Solution 4 | You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. 5 | 6 | Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. 7 | 8 | You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. 9 | 10 | Example: 11 | 12 | Given n = 5, and version = 4 is the first bad version. 13 | 14 | call isBadVersion(3) -> false 15 | call isBadVersion(5) -> true 16 | call isBadVersion(4) -> true 17 | 18 | Then 4 is the first bad version. 19 | */ 20 | 21 | class Solution { 22 | public: 23 | int firstBadVersion(int n) { 24 | int start = 1; 25 | int end = n; 26 | // [false, false, false, true, true] 27 | while (start <= end) { 28 | int mid = start + (end - start) / 2; 29 | bool status = isBadVersion(mid); 30 | 31 | if (status) { 32 | if (isBadVersion(mid - 1) == false) return mid; 33 | end = mid - 1; 34 | } else { 35 | start = mid + 1; 36 | } 37 | } 38 | 39 | return end; 40 | } 41 | }; -------------------------------------------------------------------------------- /day-32.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | You're given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels. 3 | 4 | The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A". 5 | 6 | Example 1: 7 | 8 | Input: J = "aA", S = "aAAbbbb" 9 | Output: 3 10 | Example 2: 11 | 12 | Input: J = "z", S = "ZZ" 13 | Output: 0 14 | Note: 15 | 16 | S and J will consist of letters and have length at most 50. 17 | The characters in J are distinct. 18 | */ 19 | 20 | // O(N) & O(N) solution using hash map 21 | class Solution { 22 | public: 23 | int numJewelsInStones(string J, string S) { 24 | int result = 0; 25 | 26 | unordered_map hashMap; 27 | 28 | for (char ch : S) { 29 | hashMap[ch] += 1; 30 | } 31 | 32 | for (char ch : J) { 33 | result += hashMap[ch]; 34 | } 35 | 36 | return result; 37 | } 38 | }; -------------------------------------------------------------------------------- /day-33.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Ransom Note 3 | Solution 4 | Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false. 5 | 6 | Each letter in the magazine string can only be used once in your ransom note. 7 | 8 | Note: 9 | You may assume that both strings contain only lowercase letters. 10 | 11 | canConstruct("a", "b") -> false 12 | canConstruct("aa", "ab") -> false 13 | canConstruct("aa", "aab") -> true 14 | */ 15 | 16 | class Solution { 17 | public: 18 | bool canConstruct(string ransomNote, string magazine) { 19 | unordered_map hashMap; 20 | 21 | for (char ch : magazine) { 22 | hashMap[ch] += 1; 23 | } 24 | 25 | for (char ch : ransomNote) { 26 | if (hashMap[ch] == 0) return false; 27 | hashMap[ch] -= 1; 28 | } 29 | 30 | return true; 31 | } 32 | }; -------------------------------------------------------------------------------- /day-34.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Number Complement 3 | Solution 4 | Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation. 5 | 6 | Example 1: 7 | 8 | Input: 5 9 | Output: 2 10 | Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. 11 | 12 | 13 | Example 2: 14 | 15 | Input: 1 16 | Output: 0 17 | Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to outpu 18 | */ 19 | 20 | class Solution { 21 | public: 22 | int findComplement(int num) { 23 | int result = 0; 24 | int power = 1; 25 | while (num > 0) { 26 | result += (num % 2 ^ 1) * power; 27 | power <<= 1; 28 | num >>= 1; 29 | } 30 | 31 | return result; 32 | } 33 | }; -------------------------------------------------------------------------------- /day-35.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | First Unique Character in a String 3 | Solution 4 | Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. 5 | 6 | Examples: 7 | 8 | s = "leetcode" 9 | return 0. 10 | 11 | s = "loveleetcode", 12 | return 2. 13 | Note: You may assume the string contain only lowercase letters. 14 | */ 15 | 16 | class Solution { 17 | public: 18 | int firstUniqChar(string s) { 19 | unordered_map hashMap; 20 | for (char ch : s) { 21 | hashMap[ch] += 1; 22 | } 23 | 24 | for (int i = 0; i < s.length(); i++) { 25 | if (hashMap[s[i]] == 1) return i; 26 | } 27 | 28 | return -1; 29 | } 30 | }; -------------------------------------------------------------------------------- /day-36.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Majority Element 3 | Solution 4 | Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. 5 | 6 | You may assume that the array is non-empty and the majority element always exist in the array. 7 | 8 | Example 1: 9 | 10 | Input: [3,2,3] 11 | Output: 3 12 | Example 2: 13 | 14 | Input: [2,2,1,1,1,2,2] 15 | Output: 2 16 | */ 17 | 18 | // O(N) & O(1) solution -- I came about to know this solution from CTCI book 19 | class Solution { 20 | public: 21 | int majorityElement(vector& nums) { 22 | int counter = 0; 23 | int guessMajorityElt; 24 | for (int i = 0; i < nums.size(); i++) { 25 | if (counter == 0) { 26 | counter += 1; 27 | guessMajorityElt = nums[i]; 28 | } else if (guessMajorityElt == nums[i]) { 29 | counter += 1; 30 | } else { 31 | counter -= 1; 32 | } 33 | } 34 | 35 | return guessMajorityElt; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /day-38.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Check If It Is a Straight Line 3 | 4 | 5 | 6 | You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane. 7 | 8 | Example 1: 9 | 10 | Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]] 11 | Output: true 12 | 13 | Example 2: 14 | 15 | Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]] 16 | Output: false 17 | 18 | 19 | Constraints: 20 | 21 | 2 <= coordinates.length <= 1000 22 | coordinates[i].length == 2 23 | -10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4 24 | coordinates contains no duplicate point. 25 | */ 26 | 27 | class Solution { 28 | public: 29 | bool checkStraightLine(vector>& coordinates) { 30 | if (coordinates.size() == 2) return true; 31 | 32 | double m1 = (double)(coordinates[1][1] - coordinates[0][1]) / (coordinates[1][0] - coordinates[0][0]); 33 | 34 | for (int i = 1; i < coordinates.size() - 1; i++) { 35 | double m2 = (double)(coordinates[i + 1][1] - coordinates[i][1]) / (coordinates[i + 1][0] - coordinates[i][0]); 36 | 37 | if (m1 != m2) return false; 38 | } 39 | return true; 40 | } 41 | }; -------------------------------------------------------------------------------- /day-39.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Valid Perfect Square 3 | Solution 4 | Given a positive integer num, write a function which returns True if num is a perfect square else False. 5 | 6 | Note: Do not use any built-in library function such as sqrt. 7 | 8 | Example 1: 9 | 10 | Input: 16 11 | Output: true 12 | Example 2: 13 | 14 | Input: 14 15 | Output: false 16 | */ 17 | 18 | // O(1) & O(1) beats 100% cpp solutions 19 | class Solution { 20 | public: 21 | bool isPerfectSquare(int num) { 22 | double x = sqrt(num); 23 | if (x == floor(x)) return true; 24 | return false; 25 | } 26 | }; -------------------------------------------------------------------------------- /day-4.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Question: Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. 3 | 4 | Examples: 5 | Input: [0,1,0,3,12] 6 | Output: [1,3,12,0,0] 7 | */ 8 | 9 | // O(N) & O(1) beats 99.88% cpp solution 10 | class Solution { 11 | public: 12 | void moveZeroes(vector& nums) { 13 | int idx = 0; 14 | for (int i = 0; i < nums.size(); i++) { 15 | if (nums[i] != 0) { 16 | nums[idx++] = nums[i]; 17 | } 18 | } 19 | 20 | for (int pending = idx; pending < nums.size(); pending++) nums[pending] = 0; 21 | } 22 | }; -------------------------------------------------------------------------------- /day-40.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Find the Town Judge 3 | 4 | 5 | Solution 6 | In a town, there are N people labelled from 1 to N. There is a rumor that one of these people is secretly the town judge. 7 | 8 | If the town judge exists, then: 9 | 10 | The town judge trusts nobody. 11 | Everybody (except for the town judge) trusts the town judge. 12 | There is exactly one person that satisfies properties 1 and 2. 13 | You are given trust, an array of pairs trust[i] = [a, b] representing that the person labelled a trusts the person labelled b. 14 | 15 | If the town judge exists and can be identified, return the label of the town judge. Otherwise, return -1. 16 | 17 | 18 | 19 | Example 1: 20 | 21 | Input: N = 2, trust = [[1,2]] 22 | Output: 2 23 | Example 2: 24 | 25 | Input: N = 3, trust = [[1,3],[2,3]] 26 | Output: 3 27 | Example 3: 28 | 29 | Input: N = 3, trust = [[1,3],[2,3],[3,1]] 30 | Output: -1 31 | Example 4: 32 | 33 | Input: N = 3, trust = [[1,2],[2,3]] 34 | Output: -1 35 | Example 5: 36 | 37 | Input: N = 4, trust = [[1,3],[1,4],[2,3],[2,4],[4,3]] 38 | Output: 3 39 | */ 40 | 41 | // O(N) & O(N) solution 42 | class Solution { 43 | public: 44 | int findJudge(int N, vector>& trust) { 45 | unordered_map> hashMap; 46 | 47 | for (int i = 0; i < trust.size(); i++) { 48 | hashMap[trust[i][0]].first += 1; 49 | hashMap[trust[i][1]].second += 1; 50 | } 51 | 52 | for (int i = 1; i <= N; i++) { 53 | if (hashMap[i].first == 0 && hashMap[i].second == N - 1) return i; 54 | } 55 | 56 | return -1; 57 | } 58 | }; -------------------------------------------------------------------------------- /day-43.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Remove K Digits 3 | 4 | 5 | Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible. 6 | 7 | Note: 8 | The length of num is less than 10002 and will be ≥ k. 9 | The given num does not contain any leading zero. 10 | Example 1: 11 | 12 | Input: num = "1432219", k = 3 13 | Output: "1219" 14 | Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest. 15 | Example 2: 16 | 17 | Input: num = "10200", k = 1 18 | Output: "200" 19 | Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes. 20 | Example 3: 21 | 22 | Input: num = "10", k = 2 23 | Output: "0" 24 | Explanation: Remove all the digits from the number and it is left with nothing which is 0. 25 | */ 26 | 27 | // Idea: Greedy approach when you find the peek element delete element to its right until you find another peek. 28 | 29 | // Solved in O(N + k) & O(1) 30 | class Solution { 31 | public: 32 | string removeKdigits(string num, int k) { 33 | if (k == num.size()) { 34 | return "0"; 35 | } 36 | 37 | int idx = 0; 38 | while (k > 0) { 39 | if (idx > 0) idx -= 1; 40 | while (idx <= num.length() - 1 && num[idx] <= num[idx + 1]) idx += 1; 41 | num.erase(num.begin() + idx); 42 | k -= 1; 43 | } 44 | 45 | auto non_zero = num.find_first_not_of("0"); 46 | num.erase(0, non_zero); 47 | 48 | if (num.length() == 0) return "0"; 49 | return num; 50 | } 51 | }; -------------------------------------------------------------------------------- /day-46.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Odd Even Linked List 3 | 4 | Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes. 5 | 6 | You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity. 7 | 8 | Example 1: 9 | 10 | Input: 1->2->3->4->5->NULL 11 | Output: 1->3->5->2->4->NULL 12 | Example 2: 13 | 14 | Input: 2->1->3->5->6->4->7->NULL 15 | Output: 2->3->6->7->1->5->4->NULL 16 | Note: 17 | 18 | The relative order inside both the even and odd groups should remain as it was in the input. 19 | The first node is considered odd, the second node even and so on ... 20 | */ 21 | 22 | // O(N) & O(1) solution 23 | class Solution { 24 | public: 25 | ListNode* oddEvenList(ListNode* head) { 26 | if (head == NULL) return head; 27 | ListNode* oddHead = head; 28 | ListNode* even = head->next; 29 | ListNode* evenHead = even; 30 | 31 | while (even != NULL && even->next != NULL) { 32 | oddHead->next = even->next; 33 | oddHead = oddHead->next; 34 | even->next = oddHead->next; 35 | even = even->next; 36 | } 37 | 38 | oddHead->next = evenHead; 39 | 40 | return head; 41 | } 42 | }; 43 | -------------------------------------------------------------------------------- /day-48.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Permutation in String 3 | 4 | 5 | Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string's permutations is the substring of the second string. 6 | 7 | 8 | Example 1: 9 | 10 | Input: s1 = "ab" s2 = "eidbaooo" 11 | Output: True 12 | Explanation: s2 contains one permutation of s1 ("ba"). 13 | Example 2: 14 | 15 | Input:s1= "ab" s2 = "eidboaoo" 16 | Output: False 17 | 18 | 19 | Note: 20 | 21 | The input strings only contain lower case letters. 22 | The length of both given strings is in range [1, 10,000]. 23 | */ 24 | 25 | // O(N) & O(1) beats 76.14 % of cpp submissions. 26 | 27 | class Solution { 28 | public: 29 | bool checkInclusion(string s1, string s2) { 30 | if (s2.length() == 0) return false; 31 | 32 | vector charCount(26, 0); 33 | 34 | for (char ch : s1) { 35 | charCount[ch - 'a'] += 1; 36 | } 37 | 38 | int left = 0; 39 | int right = 0; 40 | int count = s1.length(); 41 | 42 | while (right < s2.length()) { 43 | if (charCount[s2[right] - 'a'] > 0) { 44 | charCount[s2[right] - 'a'] -= 1; 45 | count -= 1; 46 | right += 1; 47 | if (count == 0) return true; 48 | } else if (left == right) { 49 | left += 1; 50 | right += 1; 51 | } else { 52 | charCount[s2[left] - 'a'] += 1; 53 | left += 1; 54 | count += 1; 55 | } 56 | } 57 | 58 | return false; 59 | } 60 | }; -------------------------------------------------------------------------------- /day-5.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Question: Say you have an array for which the ith element is the price of a given stock on day i. 3 | 4 | Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times). 5 | */ 6 | 7 | // O(N) & O(1) beats 97.60% of cpp submissions 8 | class Solution { 9 | public: 10 | int maxProfit(vector& prices) { 11 | int max = 0; 12 | for (int i = 1; i < prices.size(); i++) { 13 | if (prices[i] > prices[i - 1]) { 14 | max = max + prices[i] - prices[i - 1]; 15 | } 16 | } 17 | 18 | return max; 19 | } 20 | }; 21 | 22 | /*Solution for if we had asked only to buy and sell 1 stock*/ 23 | 24 | // class Solution { 25 | // public: 26 | // int maxProfit(vector& prices) { 27 | // int min = INT_MAX; // min value found till now 28 | // int maxProfit = 0; // max profit we made till now 29 | 30 | // for (int i = 0; i < prices.size(); i++) { 31 | // if (prices[i] < min) { 32 | // min = prices[i]; // if pr[i] is lt min update min 33 | // } else { 34 | // maxProfit = max(maxProfit, prices[i] - min); // if pr[i] is gte min then calculate max 35 | // } 36 | // } 37 | 38 | // return maxProfit; 39 | // } 40 | // }; -------------------------------------------------------------------------------- /day-50.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Kth Smallest Element in a BST 4 | 5 | Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. 6 | 7 | Note: 8 | You may assume k is always valid, 1 ≤ k ≤ BST's total elements. 9 | 10 | Example 1: 11 | 12 | Input: root = [3,1,4,null,2], k = 1 13 | 3 14 | / \ 15 | 1 4 16 | \ 17 | 2 18 | Output: 1 19 | Example 2: 20 | 21 | Input: root = [5,3,6,2,4,null,null,1], k = 3 22 | 5 23 | / \ 24 | 3 6 25 | / \ 26 | 2 4 27 | / 28 | 1 29 | Output: 3 30 | 31 | */ 32 | 33 | // O(height(tree)) & O(1) solution 34 | class Solution { 35 | public: 36 | void inorder(TreeNode* root, int k, vector& nums) { 37 | if (root == NULL) return; 38 | inorder(root->left, k, nums); 39 | nums[0] += 1; 40 | if (nums[0] == k) { 41 | nums[1] = root->val; 42 | return; 43 | } 44 | inorder(root->right, k, nums); 45 | } 46 | 47 | int kthSmallest(TreeNode* root, int k) { 48 | vector nums(2, 0); 49 | inorder(root, k, nums); 50 | return nums[1]; 51 | } 52 | }; -------------------------------------------------------------------------------- /day-52.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Sort Characters By Frequency 3 | 4 | 5 | Given a string, sort it in decreasing order based on the frequency of characters. 6 | 7 | Example 1: 8 | 9 | Input: 10 | "tree" 11 | 12 | Output: 13 | "eert" 14 | 15 | Explanation: 16 | 'e' appears twice while 'r' and 't' both appear once. 17 | So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. 18 | Example 2: 19 | 20 | Input: 21 | "cccaaa" 22 | 23 | Output: 24 | "cccaaa" 25 | 26 | Explanation: 27 | Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer. 28 | Note that "cacaca" is incorrect, as the same characters must be together. 29 | Example 3: 30 | 31 | Input: 32 | "Aabb" 33 | 34 | Output: 35 | "bbAa" 36 | 37 | Explanation: 38 | "bbaA" is also a valid answer, but "Aabb" is incorrect. 39 | Note that 'A' and 'a' are treated as two different characters. 40 | 41 | */ 42 | 43 | // O(N) & O(N) solution using hashmap 44 | class Solution { 45 | public: 46 | string frequencySort(string s) { 47 | unordered_map hashMap; 48 | vector charSet; 49 | 50 | for (char c : s) { 51 | hashMap[c] += 1; 52 | if (hashMap[c] == 1) charSet.push_back(c); 53 | } 54 | 55 | vector> vp; 56 | for (char ch : charSet) { 57 | vp.push_back({hashMap[ch], ch}); 58 | } 59 | 60 | sort(vp.begin(), vp.end()); 61 | 62 | string answer = ""; 63 | for (int i = vp.size() - 1; i >= 0; i--) { 64 | int times = vp[i].first; 65 | while (times-- > 0) answer += vp[i].second; 66 | } 67 | 68 | return answer; 69 | } 70 | }; -------------------------------------------------------------------------------- /day-54.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Question: Return the root node of a binary search tree that matches the given preorder traversal. 3 | 4 | (Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val. Also recall that a preorder traversal displays the value of the node first, then traverses node.left, then traverses node.right.) 5 | 6 | 7 | 8 | Example 1: 9 | 10 | Input: [8,5,1,7,10,12] 11 | Output: [8,5,10,1,7,null,12] 12 | 13 | */ 14 | class Solution { 15 | public: 16 | TreeNode* buildTree(vector& preorder, int low, int high) { 17 | if (low > high) return nullptr; 18 | TreeNode* root = new TreeNode(preorder[low]); 19 | if (low == high) return root; 20 | int idx = low + 1; 21 | while (idx <= high && preorder[idx] < preorder[low]) idx += 1; 22 | root->left = buildTree(preorder, low + 1, idx - 1); 23 | root->right = buildTree(preorder, idx, high); 24 | return root; 25 | } 26 | 27 | TreeNode* bstFromPreorder(vector& preorder) { 28 | return buildTree(preorder, 0, preorder.size() - 1); 29 | } 30 | }; -------------------------------------------------------------------------------- /day-56.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Question: Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1. 3 | 4 | Example 1: 5 | Input: [0,1] 6 | Output: 2 7 | Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1. 8 | Example 2: 9 | Input: [0,1,0] 10 | Output: 2 11 | Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1. 12 | Note: The length of the given binary array will not exceed 50,000. 13 | */ 14 | 15 | class Solution { 16 | public: 17 | int findMaxLength(vector& nums) { 18 | unordered_map hashMap; 19 | hashMap[0] = -1; 20 | int ans = 0; 21 | int curr = 0; 22 | for (int i = 0; i < nums.size(); i++) { 23 | if (nums[i] == 0) { 24 | curr -= 1; 25 | } else { 26 | curr += 1; 27 | } 28 | 29 | if (hashMap.find(curr) != hashMap.end()) { 30 | ans = max(ans, i - hashMap[curr]); 31 | } else { 32 | hashMap[curr] = i; 33 | } 34 | } 35 | 36 | return ans; 37 | } 38 | }; -------------------------------------------------------------------------------- /day-58.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array. 3 | 4 | Example 1: 5 | 6 | Input: 2 7 | Output: [0,1,1] 8 | Example 2: 9 | 10 | Input: 5 11 | Output: [0,1,1,2,1,2] 12 | Follow up: 13 | */ 14 | 15 | // Idea is for a number N, operation: {N & (N-1)} => removes the least significant 1. 16 | 17 | class Solution { 18 | public: 19 | vector countBits(int num) { 20 | vector answer(num + 1, 0); 21 | for (int i = 1; i < num + 1; i++) { 22 | answer[i] = answer[i & (i - 1)] + 1; 23 | } 24 | 25 | return answer; 26 | } 27 | }; -------------------------------------------------------------------------------- /day-6.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Question: Given an array of strings, group anagrams together. 3 | Input: ["eat", "tea", "tan", "ate", "nat", "bat"], 4 | Output: 5 | [ 6 | ["ate","eat","tea"], 7 | ["nat","tan"], 8 | ["bat"] 9 | ] 10 | */ 11 | 12 | class Solution { 13 | public: 14 | vector> groupAnagrams(vector& strs) { 15 | vector> answer; 16 | unordered_map> hashMap; 17 | for (int i = 0; i < strs.size(); i++) { 18 | string strCopy = strs[i]; 19 | sort(strs[i].begin(), strs[i].end()); 20 | hashMap[strs[i]].push_back(strCopy); 21 | } 22 | 23 | for (auto& itr : hashMap) { 24 | answer.push_back(itr.second); 25 | } 26 | return answer; 27 | } 28 | }; -------------------------------------------------------------------------------- /day-60.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | K Closest Points to Origin 3 | 4 | We have a list of points on the plane. Find the K closest points to the origin (0, 0). 5 | 6 | (Here, the distance between two points on a plane is the Euclidean distance.) 7 | 8 | You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in.) 9 | 10 | 11 | 12 | Example 1: 13 | 14 | Input: points = [[1,3],[-2,2]], K = 1 15 | Output: [[-2,2]] 16 | Explanation: 17 | The distance between (1, 3) and the origin is sqrt(10). 18 | The distance between (-2, 2) and the origin is sqrt(8). 19 | Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. 20 | We only want the closest K = 1 points from the origin, so the answer is just [[-2,2]]. 21 | Example 2: 22 | 23 | Input: points = [[3,3],[5,-1],[-2,4]], K = 2 24 | Output: [[3,3],[-2,4]] 25 | (The answer [[-2,4],[3,3]] would also be accepted.) 26 | 27 | */ 28 | 29 | // Easy problem: learnt this short and fast way to solve this problem 30 | class Solution { 31 | struct Comp { 32 | bool operator()(vector& a, vector& b) { 33 | return a[1] * a[1] + a[0] * a[0] < b[1] * b[1] + b[0] * b[0]; 34 | } 35 | }; 36 | 37 | public: 38 | vector> kClosest(vector>& points, int K) { 39 | if (K == points.size()) return points; 40 | sort(points.begin(), points.end(), Comp()); 41 | return vector>(points.begin(), points.begin() + K); 42 | } 43 | }; -------------------------------------------------------------------------------- /day-62.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Invert Binary Tree 3 | */ 4 | 5 | // Recursive solution 6 | class Solution { 7 | public: 8 | TreeNode* invertTree(TreeNode* root) { 9 | if (root == NULL) { 10 | return root; 11 | } 12 | 13 | TreeNode* tempNode; 14 | invertTree(root->left); 15 | invertTree(root->right); 16 | 17 | tempNode = root->left; 18 | root->left = root->right; 19 | root->right = tempNode; 20 | return root; 21 | } 22 | }; -------------------------------------------------------------------------------- /day-63.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Delete Node in a Linked List 3 | 4 | 5 | Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. 6 | 7 | Given linked list -- head = [4,5,1,9], which looks like following: 8 | 9 | Example 1: 10 | 11 | Input: head = [4,5,1,9], node = 5 12 | Output: [4,1,9] 13 | Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function. 14 | Example 2: 15 | 16 | Input: head = [4,5,1,9], node = 1 17 | Output: [4,5,9] 18 | Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your 19 | */ 20 | 21 | class Solution { 22 | public: 23 | void deleteNode(ListNode* node) { 24 | node->val = node->next->val; 25 | node->next = node->next->next; 26 | } 27 | }; -------------------------------------------------------------------------------- /day-64.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Two City Scheduling 3 | 4 | There are 2N people a company is planning to interview. The cost of flying the i-th person to city A is costs[i][0], and the cost of flying the i-th person to city B is costs[i][1]. 5 | 6 | Return the minimum cost to fly every person to a city such that exactly N people arrive in each city. 7 | 8 | 9 | 10 | Example 1: 11 | 12 | Input: [[10,20],[30,200],[400,50],[30,20]] 13 | Output: 110 14 | Explanation: 15 | The first person goes to city A for a cost of 10. 16 | The second person goes to city A for a cost of 30. 17 | The third person goes to city B for a cost of 50. 18 | The fourth person goes to city B for a cost of 20. 19 | 20 | The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city. 21 | 22 | */ 23 | 24 | // O(N) & O(1) solution 25 | class Solution { 26 | struct Comp { 27 | bool operator()(vector& a, vector& b) { 28 | return (a[0] - a[1]) < (b[0] - b[1]); 29 | } 30 | }; 31 | 32 | public: 33 | int twoCitySchedCost(vector>& costs) { 34 | int answer = 0; 35 | sort(costs.begin(), costs.end(), Comp()); 36 | 37 | for (int i = 0; i < costs.size() / 2; i++) { 38 | answer += costs[i][0]; 39 | } 40 | 41 | for (int i = costs.size() / 2; i < costs.size(); i++) { 42 | answer += costs[i][1]; 43 | } 44 | 45 | return answer; 46 | } 47 | }; -------------------------------------------------------------------------------- /day-65.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Reverse String 3 | 4 | Write a function that reverses a string. The input string is given as an array of characters char[]. 5 | 6 | Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. 7 | 8 | You may assume all the characters consist of printable ascii characters. 9 | 10 | 11 | 12 | Example 1: 13 | 14 | Input: ["h","e","l","l","o"] 15 | Output: ["o","l","l","e","h"] 16 | Example 2: 17 | 18 | Input: ["H","a","n","n","a","h"] 19 | Output: ["h","a","n","n","a","H"] 20 | 21 | */ 22 | 23 | // O(len(str)) & O(1) beats 82% of cpp solutions 24 | class Solution { 25 | public: 26 | void reverseString(vector& s) { 27 | int len = s.size(); 28 | for (int i = 0; i < len / 2; i++) { 29 | char ch = s[i]; 30 | s[i] = s[len - i - 1]; 31 | s[len - i - 1] = ch; 32 | } 33 | } 34 | }; -------------------------------------------------------------------------------- /day-67.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Queue Reconstruction by Height 3 | 4 | 5 | Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the queue. 6 | 7 | Note: 8 | The number of people is less than 1,100. 9 | 10 | 11 | Example 12 | 13 | Input: 14 | [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]] 15 | 16 | Output: 17 | [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]] 18 | */ 19 | 20 | class Solution { 21 | struct Comp { 22 | bool operator()(const vector& a, const vector& b) { 23 | return (a[0] > b[0] || (a[0] == b[0] && a[1] < b[1])); 24 | } 25 | }; 26 | 27 | public: 28 | vector> reconstructQueue(vector>& people) { 29 | sort(people.begin(), people.end(), Comp()); 30 | vector> answers; 31 | 32 | for (int i = 0; i < people.size(); i++) { 33 | answers.insert(answers.begin() + people[i][1], people[i]); 34 | } 35 | return answers; 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /day-68.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Coin Change 2 3 | 4 | 5 | You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that amount. You may assume that you have infinite number of each kind of coin. 6 | 7 | 8 | 9 | Example 1: 10 | 11 | Input: amount = 5, coins = [1, 2, 5] 12 | Output: 4 13 | Explanation: there are four ways to make up the amount: 14 | 5=5 15 | 5=2+2+1 16 | 5=2+1+1+1 17 | 5=1+1+1+1+1 18 | Example 2: 19 | 20 | Input: amount = 3, coins = [2] 21 | Output: 0 22 | Explanation: the amount of 3 cannot be made up just with coins of 2. 23 | Example 3: 24 | 25 | Input: amount = 10, coins = [10] 26 | Output: 1 27 | */ 28 | 29 | // Popular DP problem 30 | class Solution { 31 | public: 32 | int change(int amount, vector& coins) { 33 | vector> dp(coins.size() + 1, vector(amount + 1, 0)); 34 | 35 | for (int i = 0; i <= coins.size(); i++) { 36 | for (int j = 0; j <= amount; j++) { 37 | if (j == 0) 38 | dp[i][j] = 1; 39 | else if (i == 0) 40 | dp[i][j] = 0; 41 | else if (coins[i - 1] <= j) 42 | dp[i][j] = dp[i - 1][j] + dp[i][j - coins[i - 1]]; 43 | else 44 | dp[i][j] = dp[i - 1][j]; 45 | } 46 | } 47 | 48 | return dp[coins.size()][amount]; 49 | } 50 | }; -------------------------------------------------------------------------------- /day-69.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Power of Two 3 | 4 | Given an integer, write a function to determine if it is a power of two. 5 | 6 | Example 1: 7 | 8 | Input: 1 9 | Output: true 10 | Explanation: 20 = 1 11 | Example 2: 12 | 13 | Input: 16 14 | Output: true 15 | Explanation: 24 = 16 16 | Example 3: 17 | 18 | Input: 218 19 | Output: false 20 | 21 | */ 22 | 23 | // Simple log approach 24 | class Solution { 25 | public: 26 | bool isPowerOfTwo(int n) { 27 | if (n == 0) return false; 28 | double x = log2(n); 29 | if (floor(x) == ceil(x)) return true; 30 | return false; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /day-7.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Question: Given an integer array arr, count element x such that x + 1 is also in arr. 3 | If there're duplicates in arr, count them seperately. 4 | 5 | EXAMPLE: 6 | Input: arr = [1,2,3] 7 | Output: 2 8 | Explanation: 1 and 2 are counted cause 2 and 3 are in arr. 9 | 10 | Input: arr = [1,1,2,2] 11 | Output: 2 12 | Explanation: Two 1s are counted cause 2 is in arr. 13 | */ 14 | 15 | class Solution { 16 | public: 17 | int countElements(vector& arr) { 18 | map hashMap; 19 | for (int i = 0; i < arr.size(); i++) { 20 | hashMap[arr[i]] += 1; 21 | } 22 | 23 | int cnt = 0; 24 | for (int i = 0; i < arr.size(); i++) { 25 | if (hashMap[arr[i] + 1] > 0) { 26 | cnt++; 27 | } 28 | } 29 | 30 | return cnt; 31 | } 32 | }; -------------------------------------------------------------------------------- /day-71.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Search Insert Position 4 | 5 | Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. 6 | 7 | You may assume no duplicates in the array. 8 | 9 | Example 1: 10 | 11 | Input: [1,3,5,6], 5 12 | Output: 2 13 | Example 2: 14 | 15 | Input: [1,3,5,6], 2 16 | Output: 1 17 | Example 3: 18 | 19 | Input: [1,3,5,6], 7 20 | Output: 4 21 | Example 4: 22 | 23 | Input: [1,3,5,6], 0 24 | Output: 0 25 | 26 | */ 27 | 28 | // Simple binary search solution 29 | class Solution { 30 | public: 31 | int searchInsert(vector& nums, int target) { 32 | int low = 0; 33 | int high = nums.size() - 1; 34 | 35 | while (low <= high) { 36 | int mid = low + (high - low) / 2; 37 | if (target == nums[mid]) { 38 | return mid; 39 | } 40 | 41 | if (nums[mid] > target) { 42 | high = mid - 1; 43 | } else { 44 | low = mid + 1; 45 | } 46 | } 47 | 48 | return low; 49 | } 50 | }; 51 | -------------------------------------------------------------------------------- /day-76.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Search in a Binary Search Tree 3 | 4 | Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the node's value equals the given value. Return the subtree rooted with that node. If such node doesn't exist, you should return NULL. 5 | 6 | In the example above, if we want to search the value 5, since there is no node with value 5, we should return NULL. 7 | 8 | Note that an empty tree is represented by NULL, therefore you would see the expected output (serialized tree format) as [], not null. 9 | */ 10 | 11 | // Simple recursive solution based on properties of BST 12 | class Solution { 13 | public: 14 | TreeNode* performSearch(TreeNode* root, int val) { 15 | if (root == NULL) return root; 16 | 17 | if (root->val == val) return root; 18 | TreeNode* answer; 19 | if (val < root->val) 20 | answer = performSearch(root->left, val); 21 | else 22 | answer = performSearch(root->right, val); 23 | 24 | return answer; 25 | } 26 | 27 | TreeNode* searchBST(TreeNode* root, int val) { 28 | return performSearch(root, val); 29 | } 30 | }; -------------------------------------------------------------------------------- /day-79.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | H-Index II 3 | 4 | 5 | Given an array of citations sorted in ascending order (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index. 6 | 7 | According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each." 8 | 9 | Example: 10 | 11 | Input: citations = [0,1,3,5,6] 12 | Output: 3 13 | Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had 14 | received 0, 1, 3, 5, 6 citations respectively. 15 | Since the researcher has 3 papers with at least 3 citations each and the remaining 16 | two with no more than 3 citations each, her h-index is 3. 17 | 18 | */ 19 | 20 | // Used binary search O(log N) approach 21 | class Solution { 22 | public: 23 | int hIndex(vector& citations) { 24 | int N = citations.size(); 25 | int start = 0; 26 | int end = citations.size() - 1; 27 | 28 | while (start <= end) { 29 | int mid = start + (end - start) / 2; 30 | 31 | if (citations[mid] < (N - mid)) { 32 | start = mid + 1; 33 | } else { 34 | end = mid - 1; 35 | } 36 | } 37 | 38 | return N - start; 39 | } 40 | }; -------------------------------------------------------------------------------- /day-8.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Question: Given a non-empty, singly linked list with head node head, return a middle node of linked list. 3 | 4 | If there are two middle nodes, return the second middle node. 5 | */ 6 | class Solution { 7 | public: 8 | ListNode* middleNode(ListNode* head) { 9 | int len = 0; 10 | ListNode* temp = head; 11 | while (temp != NULL) { 12 | len = len + 1; 13 | temp = temp->next; 14 | } 15 | int mid = len / 2; 16 | temp = head; 17 | while (mid-- > 0) { 18 | temp = temp->next; 19 | } 20 | return temp; 21 | } 22 | }; -------------------------------------------------------------------------------- /day-83.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Single Number II 3 | 4 | 5 | Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one. 6 | 7 | Note: 8 | 9 | Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 10 | 11 | Example 1: 12 | 13 | Input: [2,2,3,2] 14 | Output: 3 15 | Example 2: 16 | 17 | Input: [0,1,0,1,0,1,99] 18 | Output: 99 19 | */ 20 | 21 | // O(N) & O(1) solution beats 93.19 % of cpp submissions. 22 | 23 | class Solution { 24 | public: 25 | int singleNumber(vector& nums) { 26 | int len = nums.size(); 27 | int ones = 0; 28 | int twos = 0; 29 | int not_threes; 30 | 31 | for (int i = 0; i < len; i++) { 32 | int curr = nums[i]; 33 | 34 | twos |= ones & curr; 35 | ones ^= curr; 36 | not_threes = ~(ones & twos); 37 | ones &= not_threes; 38 | twos &= not_threes; 39 | } 40 | 41 | return ones; 42 | } 43 | }; -------------------------------------------------------------------------------- /day-84.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Count Complete Tree Nodes 3 | 4 | 5 | Given a complete binary tree, count the number of nodes. 6 | 7 | Note: 8 | 9 | Definition of a complete binary tree from Wikipedia: 10 | In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. 11 | 12 | Example: 13 | 14 | Input: 15 | 1 16 | / \ 17 | 2 3 18 | / \ / 19 | 4 5 6 20 | 21 | Output: 6 22 | */ 23 | 24 | //Simple recursive based solution to count nodes 25 | class Solution { 26 | public: 27 | void computeNodes(TreeNode* root, int& count) { 28 | if (root == NULL) return; 29 | 30 | count += 1; 31 | computeNodes(root->left, count); 32 | computeNodes(root->right, count); 33 | } 34 | 35 | int countNodes(TreeNode* root) { 36 | int count = 0; 37 | computeNodes(root, count); 38 | return count; 39 | } 40 | }; -------------------------------------------------------------------------------- /day-85.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Unique Binary Search Trees 3 | 4 | 5 | Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n? 6 | 7 | Example: 8 | 9 | Input: 3 10 | Output: 5 11 | Explanation: 12 | Given n = 3, there are a total of 5 unique BST's: 13 | 14 | 1 3 3 2 1 15 | \ / / / \ \ 16 | 3 2 1 1 3 2 17 | / / \ \ 18 | 2 1 2 3 19 | */ 20 | 21 | //Simple DP solutions to calculate number of BST 22 | class Solution { 23 | public: 24 | int numTrees(int n) { 25 | if (n < 2) return 1; 26 | vector ans(n + 1); 27 | ans[0] = 1; 28 | ans[1] = 1; 29 | 30 | for (int i = 2; i <= n; i++) { 31 | for (int j = 0; j < i; j++) { 32 | ans[i] += ans[j] * ans[i - j - 1]; 33 | } 34 | } 35 | 36 | return ans[n]; 37 | } 38 | }; -------------------------------------------------------------------------------- /day-86.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Find the Duplicate Number 3 | 4 | Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one. 5 | 6 | Example 1: 7 | 8 | Input: [1,3,4,2,2] 9 | Output: 2 10 | Example 2: 11 | 12 | Input: [3,1,3,4,2] 13 | Output: 3 14 | Note: 15 | 16 | You must not modify the array (assume the array is read only). 17 | You must use only constant, O(1) extra space. 18 | Your runtime complexity should be less than O(n2). 19 | There is only one duplicate number in the array, but it could be repeated more than once. 20 | */ 21 | 22 | // O(N) solution based on idea of using index as elements 23 | // Example: [1,3,4,2,2] 24 | // treat array elements as index of array 25 | // when you first time visit the element make it negative 26 | // And the second time that -ve element will be converted to +ve 27 | // Fact is only duplicate element will be turned +ve others all will be -ve 28 | 29 | class Solution { 30 | public: 31 | int findDuplicate(vector& nums) { 32 | for (int i = 0; i < nums.size(); i++) { 33 | int idx = nums[i]; 34 | if (nums[abs(idx)] < 0) return abs(idx); 35 | nums[abs(idx)] *= -1; 36 | } 37 | 38 | return -1; 39 | } 40 | }; -------------------------------------------------------------------------------- /day-87.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Sum Root to Leaf Numbers 3 | 4 | 5 | Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. 6 | 7 | An example is the root-to-leaf path 1->2->3 which represents the number 123. 8 | 9 | Find the total sum of all root-to-leaf numbers. 10 | 11 | Note: A leaf is a node with no children. 12 | 13 | Example: 14 | 15 | Input: [1,2,3] 16 | 1 17 | / \ 18 | 2 3 19 | Output: 25 20 | Explanation: 21 | The root-to-leaf path 1->2 represents the number 12. 22 | The root-to-leaf path 1->3 represents the number 13. 23 | Therefore, sum = 12 + 13 = 25. 24 | Example 2: 25 | 26 | Input: [4,9,0,5,1] 27 | 4 28 | / \ 29 | 9 0 30 | / \ 31 | 5 1 32 | Output: 1026 33 | Explanation: 34 | The root-to-leaf path 4->9->5 represents the number 495. 35 | The root-to-leaf path 4->9->1 represents the number 491. 36 | The root-to-leaf path 4->0 represents the number 40. 37 | Therefore, sum = 495 + 491 + 40 = 1026. 38 | */ 39 | 40 | // Simple recursive based solution it takes O(1) memory 41 | class Solution { 42 | int ans; 43 | 44 | public: 45 | void makeNumbers(TreeNode* root, int num, int& ans) { 46 | if (root == NULL) return; 47 | num = num * 10 + root->val; 48 | 49 | if (root->left == NULL && root->right == NULL) ans += num; 50 | 51 | makeNumbers(root->left, num, ans); 52 | makeNumbers(root->right, num, ans); 53 | } 54 | int sumNumbers(TreeNode* root) { 55 | ans = 0; 56 | makeNumbers(root, 0, ans); 57 | return ans; 58 | } 59 | }; -------------------------------------------------------------------------------- /day-88.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Perfect Squares 3 | 4 | 5 | Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. 6 | 7 | Example 1: 8 | 9 | Input: n = 12 10 | Output: 3 11 | Explanation: 12 = 4 + 4 + 4. 12 | Example 2: 13 | 14 | Input: n = 13 15 | Output: 2 16 | Explanation: 13 = 4 + 9. 17 | */ 18 | 19 | // Simple DP solution 20 | class Solution { 21 | public: 22 | int numSquares(int n) { 23 | vector dp(n + 1, 0); 24 | 25 | for (int num = 1; num <= n; num++) { 26 | int minVal = num; 27 | 28 | int y = 1; 29 | int sq = 1; 30 | 31 | while (sq <= num) { 32 | minVal = min(minVal, 1 + dp[num - sq]); 33 | y += 1; 34 | sq = y * y; 35 | } 36 | 37 | dp[num] = minVal; 38 | } 39 | 40 | return dp[n]; 41 | } 42 | }; -------------------------------------------------------------------------------- /day-9.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Question: Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character. 3 | 4 | Examples: 5 | Input: S = "ab#c", T = "ad#c" 6 | Output: true 7 | Explanation: Both S and T become "ac". 8 | 9 | Input: S = "ab##", T = "c#d#" 10 | Output: true 11 | Explanation: Both S and T become "". 12 | 13 | Input: S = "a##c", T = "#a#c" 14 | Output: true 15 | Explanation: Both S and T become "c". 16 | 17 | Input: S = "a#c", T = "b" 18 | Output: false 19 | Explanation: S becomes "c" while T becomes "b". 20 | */ 21 | 22 | class Solution { 23 | public: 24 | string computeString(string str) { 25 | int len = str.length(); 26 | int idx = 0; 27 | for (int i = 0; i < len; i++) { 28 | if (str[i] == '#' && idx == 0) continue; 29 | if (str[i] == '#') 30 | idx -= 1; 31 | else 32 | str[idx++] = str[i]; 33 | } 34 | str = str.substr(0, idx); 35 | return str; 36 | } 37 | bool backspaceCompare(string S, string T) { 38 | S = computeString(S); 39 | T = computeString(T); 40 | if (S == T) return true; 41 | return false; 42 | } 43 | }; -------------------------------------------------------------------------------- /day-90.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Unique Paths 3 | 4 | 5 | A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). 6 | 7 | The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). 8 | 9 | How many possible unique paths are there? 10 | Example 1: 11 | 12 | Input: m = 3, n = 2 13 | Output: 3 14 | Explanation: 15 | From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 16 | 1. Right -> Right -> Down 17 | 2. Right -> Down -> Right 18 | 3. Down -> Right -> Right 19 | Example 2: 20 | 21 | Input: m = 7, n = 3 22 | Output: 28 23 | 24 | */ 25 | 26 | // Bottom up simple DP solutions 27 | // O(row * cols) both time & space complexity 28 | class Solution { 29 | public: 30 | int uniquePaths(int m, int n) { 31 | vector> dp(m, vector(n)); 32 | 33 | for (int i = 0; i < n; i++) { 34 | dp[m - 1][i] = 1; 35 | } 36 | 37 | for (int i = 0; i < m; i++) { 38 | dp[i][n - 1] = 1; 39 | } 40 | 41 | for (int i = m - 2; i >= 0; i--) { 42 | for (int j = n - 2; j >= 0; j--) { 43 | dp[i][j] = dp[i + 1][j] + dp[i][j + 1]; 44 | } 45 | } 46 | 47 | return dp[0][0]; 48 | } 49 | }; -------------------------------------------------------------------------------- /day-92.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Arranging Coins 3 | 4 | You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins. 5 | 6 | Given n, find the total number of full staircase rows that can be formed. 7 | 8 | n is a non-negative integer and fits within the range of a 32-bit signed integer. 9 | 10 | Example 1: 11 | 12 | n = 5 13 | 14 | The coins can form the following rows: 15 | ¤ 16 | ¤ ¤ 17 | ¤ ¤ 18 | 19 | Because the 3rd row is incomplete, we return 2. 20 | Example 2: 21 | 22 | n = 8 23 | 24 | The coins can form the following rows: 25 | ¤ 26 | ¤ ¤ 27 | ¤ ¤ ¤ 28 | ¤ ¤ 29 | 30 | Because the 4th row is incomplete, we return 3. 31 | */ 32 | 33 | // Simple binary search solution 34 | class Solution { 35 | public: 36 | int arrangeCoins(int n) { 37 | int low = 1; 38 | int high = n; 39 | 40 | while (low <= high) { 41 | long mid = low + (high - low) / 2; 42 | 43 | long sumMid = mid * (mid + 1) / 2; 44 | 45 | if (sumMid <= n) { 46 | low = mid + 1; 47 | } else { 48 | high = mid - 1; 49 | } 50 | } 51 | 52 | return low - 1; 53 | } 54 | }; 55 | -------------------------------------------------------------------------------- /day-95.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Ugly Number II 3 | 4 | 5 | Write a program to find the n-th ugly number. 6 | 7 | Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. 8 | 9 | Example: 10 | 11 | Input: n = 10 12 | Output: 12 13 | Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers. 14 | Note: 15 | 16 | 1 is typically treated as an ugly number. 17 | n does not exceed 1690. 18 | */ 19 | 20 | // DP solution to generate Ugly Number 21 | class Solution { 22 | public: 23 | int nthUglyNumber(int n) { 24 | if (n == 0) return 1; 25 | 26 | vector nums; 27 | 28 | nums.push_back(1); 29 | 30 | int i = 0; 31 | int j = 0; 32 | int k = 0; 33 | 34 | while (nums.size() <= n) { 35 | int numTwo = nums[i] * 2; 36 | 37 | int numThree = nums[j] * 3; 38 | 39 | int numFive = nums[k] * 5; 40 | 41 | int minNum = min({numTwo, numThree, numFive}); 42 | 43 | nums.push_back(minNum); 44 | 45 | if (minNum == numTwo) i += 1; 46 | if (minNum == numThree) j += 1; 47 | if (minNum == numFive) k += 1; 48 | } 49 | 50 | return nums[n - 1]; 51 | } 52 | }; -------------------------------------------------------------------------------- /day-96.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Hamming Distance 3 | 4 | 5 | The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 6 | 7 | Given two integers x and y, calculate the Hamming distance. 8 | 9 | Note: 10 | 0 ≤ x, y < 231. 11 | 12 | Example: 13 | 14 | Input: x = 1, y = 4 15 | 16 | Output: 2 17 | 18 | Explanation: 19 | 1 (0 0 0 1) 20 | 4 (0 1 0 0) 21 | ↑ ↑ 22 | 23 | The above arrows point to positions where the corresponding bits are different. 24 | */ 25 | 26 | // Easy problem using XOR operator 27 | class Solution { 28 | public: 29 | int hammingDistance(int x, int y) { 30 | int answer = 0; 31 | 32 | // Using XOR operator 33 | // If two bits are same it returns 0 34 | // If two bits are different it returns 1 35 | while (x > 0 || y > 0) { 36 | answer += (x % 2) ^ (y % 2); 37 | x = x / 2; 38 | y = y / 2; 39 | } 40 | 41 | return answer; 42 | } 43 | }; -------------------------------------------------------------------------------- /day-97.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Plus One 3 | 4 | 5 | Given a non-empty array of digits representing a non-negative integer, plus one to the integer. 6 | 7 | The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit. 8 | 9 | You may assume the integer does not contain any leading zero, except the number 0 itself. 10 | 11 | Example 1: 12 | 13 | Input: [1,2,3] 14 | Output: [1,2,4] 15 | Explanation: The array represents the integer 123. 16 | Example 2: 17 | 18 | Input: [4,3,2,1] 19 | Output: [4,3,2,2] 20 | Explanation: The array represents the integer 4321. 21 | 22 | */ 23 | 24 | // Simple logic building question 25 | class Solution { 26 | public: 27 | vector plusOne(vector& digits) { 28 | int N = digits.size() - 1; 29 | 30 | if (digits[N] != 9) { 31 | digits[N] += 1; 32 | return digits; 33 | } 34 | 35 | list sumList; 36 | int prevCarry = 0; 37 | 38 | for (int i = N; i >= 0; i--) { 39 | int currCarry = 0; 40 | int currSum = digits[i] + prevCarry; 41 | if (i == N) currSum += 1; 42 | prevCarry = 0; 43 | if (currSum > 9) { 44 | currSum = 0; 45 | currCarry = 1; 46 | } 47 | 48 | prevCarry = currCarry; 49 | sumList.push_front(currSum); 50 | } 51 | 52 | if (prevCarry == 1) sumList.push_front(1); 53 | 54 | vector answer(sumList.begin(), sumList.end()); 55 | 56 | return answer; 57 | } 58 | }; --------------------------------------------------------------------------------