├── 0001. Two Sum ├── 0002. Add Two Numbers ├── 0003. Longest Substring Without Repeating Characters ├── 0004. Median of Two Sorted Arrays ├── 0007. Reverse Integer ├── 0009. Palindrome Number ├── 0014. Longest Common Prefix ├── 0015. 3Sum ├── 0016. 3Sum Closest ├── 0018. 4Sum ├── 0019. Remove Nth Node From End of List ├── 0020. Valid Parentheses ├── 0021. Merge Two Sorted Lists ├── 0023. Merge k Sorted Lists ├── 0024. Swap Nodes in Pairs ├── 0025. Reverse Nodes in k-Group ├── 0026. Remove Duplicates from Sorted Array ├── 0027. Remove Element ├── 0028. Find the Index of the First Occurrence in a String ├── 0031. Next Permutation ├── 0033. Search in Rotated Sorted Array ├── 0034. Find First and Last Position of Element in Sorted Array ├── 0035. Search Insert Position ├── 0039. Combination Sum ├── 0040. Combination Sum II ├── 0041. First Missing Positive ├── 0042. Trapping Rain Water ├── 0048. Rotate Image ├── 0050. Pow(x, n) ├── 0053. Maximum Subarray ├── 0056. Merge Intervals ├── 0058. Length of Last Word ├── 0061. Rotate List ├── 0066. Plus One ├── 0069. Sqrt(x) ├── 0070. Climbing Stairs ├── 0073. Set Matrix Zeroes ├── 0074. Search a 2D Matrix ├── 0075. Sort Colors ├── 0078. Subsets ├── 0083. Remove Duplicates from Sorted List ├── 0088. Merge Sorted Array ├── 0090. Subsets II ├── 0094. Binary Tree Inorder Traversal ├── 0098. Validate Binary Search Tree ├── 0100. Same Tree ├── 0102. Binary Tree Level Order Traversal ├── 0103. Binary Tree Zigzag Level Order Traversal ├── 0104. Maximum Depth of Binary Tree ├── 0113. Path Sum II ├── 0114. Flatten Binary Tree to Linked List ├── 0118. Pascal's Triangle ├── 0119. Pascal's Triangle II ├── 0121. Best Time to Buy and Sell Stock ├── 0122. Best Time to Buy and Sell Stock II ├── 0128. Longest Consecutive Sequence ├── 0133. Clone Graph ├── 0136. Single Number ├── 0138. Copy List with Random Pointer ├── 0141. Linked List Cycle ├── 0142. Linked List Cycle II ├── 0144. Binary Tree Preorder Traversal ├── 0145. Binary Tree Postorder Traversal ├── 0151. Reverse Words in a String ├── 0153. Find Minimum in Rotated Sorted Array ├── 0155. Min Stack ├── 0160. Intersection of Two Linked Lists ├── 0167. Two Sum II - Input Array Is Sorted ├── 0169. Majority Element ├── 0171. Excel Sheet Column Number ├── 0172. Factorial Trailing Zeroes ├── 0189. Rotate Array ├── 0199. Binary Tree Right Side View ├── 0201. Bitwise AND of Numbers Range ├── 0206. Reverse Linked List ├── 0209. Minimum Size Subarray Sum ├── 0215. Kth Largest Element in an Array ├── 0217. Contains Duplicate ├── 0222. Count Complete Tree Nodes ├── 0225. Implement Stack using Queues ├── 0226. Invert Binary Tree ├── 0229. Majority Element II ├── 0231. Power of Two ├── 0232. Implement Queue using Stacks ├── 0234. Palindrome Linked List ├── 0237. Delete Node in a Linked List ├── 0242. Valid Anagram ├── 0258. Add Digits ├── 0260. Single Number III ├── 0268. Missing Number ├── 0287. Find the Duplicate Number ├── 0295. Find Median from Data Stream ├── 0326. Power of Three ├── 0344. Reverse String ├── 0347. Top K Frequent Elements ├── 0350. Intersection of Two Arrays II ├── 0387. First Unique Character in a String ├── 0409. Longest Palindrome ├── 0430. Flatten a Multilevel Doubly Linked List ├── 0436. Find Right Interval ├── 0455. Assign Cookies ├── 0485. Max Consecutive Ones ├── 0496. Next Greater Element I ├── 0543. Diameter of Binary Tree ├── 0605. Can Place Flowers ├── 0633. Sum of Square Numbers ├── 0645. Set Mismatch ├── 0703. Kth Largest Element in a Stream ├── 0704. Binary Search ├── 0713. Subarray Product Less Than K ├── 0744. Find Smallest Letter Greater Than Target ├── 0763. Partition Labels ├── 0826. Most Profit Assigning Work ├── 0846. Hand of Straights ├── 0876. Middle of the Linked List ├── 0918. Maximum Sum Circular Subarray ├── 0945. Minimum Increment to Make Array Unique ├── 0981. Time Based Key-Value Store ├── 1002. Find Common Characters ├── 1028. Recover a Tree From Preorder Traversal ├── 1128. Number of Equivalent Domino Pairs ├── 1295. Find Numbers with Even Number of Digits ├── 1304. Find N Unique Integers Sum up to Zero ├── 1305. All Elements in Two Binary Search Trees ├── 1317. Convert Integer to the Sum of Two No-Zero Integers ├── 1351. Count Negative Numbers in a Sorted Matrix ├── 1352. Product of the Last K Numbers ├── 1358. Number of Substrings Containing All Three Characters ├── 1402. Reducing Dishes ├── 1480. Running Sum of 1d Array ├── 1493. Longest Subarray of 1's After Deleting One Element ├── 1509. Minimum Difference Between Largest and Smallest Value in Three Moves ├── 1512. Number of Good Pairs ├── 1518. Water Bottles ├── 1550. Three Consecutive Odds ├── 1614. Maximum Nesting Depth of the Parentheses ├── 1689. Partitioning Into Minimum Number Of Deci-Binary Numbers ├── 1749. Maximum Absolute Sum of Any Subarray ├── 1769. Minimum Number of Operations to Move All Balls to Each Box ├── 1780. Check if Number is a Sum of Powers of Three ├── 1790. Check if One String Swap Can Make Strings Equal ├── 1791. Find Center of Star Graph ├── 1833. Maximum Ice Cream Bars ├── 1848. Minimum Distance to the Target Element ├── 1909. Remove One Element to Make the Array Strictly Increasing ├── 1910. Remove All Occurrences of a Substring ├── 1920. Build Array from Permutation ├── 1929. Concatenation of Array ├── 2017. Grid Game ├── 2037. Minimum Number of Moves to Seat Everyone ├── 2144. Minimum Cost of Buying Candies With Discount ├── 2161. Partition Array According to Given Pivot ├── 2181. Merge Nodes in Between Zeros ├── 2221. Find Triangular Sum of an Array ├── 2226. Maximum Candies Allocated to K Children ├── 2239. Find Closest Number to Zero ├── 2259. Remove Digit From Number to Maximize Result ├── 2342. Max Sum of a Pair With Equal Sum of Digits ├── 2364. Count Number of Bad Pairs ├── 2379. Minimum Recolors to Get K Consecutive Black Blocks ├── 2391. Minimum Amount of Time to Collect Garbage ├── 2441. Largest Positive Integer That Exists With Its Negative ├── 2460. Apply Operations to an Array ├── 2486. Append Characters to String to Make Subsequence ├── 2523. Closest Prime Numbers in Range ├── 2529. Maximum Count of Positive Integer and Negative Integer ├── 2540. Minimum Common Value ├── 2545. Sort the Students by Their Kth Score ├── 2570. Merge Two 2D Arrays by Summing Values ├── 2579. Count Total Number of Colored Cells ├── 2582. Pass the Pillow ├── 2591. Distribute Money to Maximum Children ├── 2661. First Completely Painted Row or Column ├── 2698. Find the Punishment Number of an Integer ├── 2703. Return Length of Arguments Passed ├── 2769. Find the Maximum Achievable Number ├── 2807. Insert Greatest Common Divisors in Linked List ├── 2810. Faulty Keyboard ├── 2816. Double a Number Represented as a Linked List ├── 2824. Count Pairs Whose Sum is Less than Target ├── 2856. Minimum Array Length After Pair Removals ├── 2894. Divisible and Non-divisible Sums Difference ├── 2895. Minimum Processing Time ├── 2900. Longest Unequal Adjacent Groups Subsequence I ├── 2965. Find Missing and Repeated Values ├── 3042. Count Prefix and Suffix Pairs I ├── 3066. Minimum Operations to Exceed Threshold Value II ├── 3105. Longest Strictly Increasing or Strictly Decreasing Subarray ├── 3110. Score of a String ├── 3151. Special Array I ├── 3174. Clear Digits ├── 3190. Find Minimum Operations to Make All Elements Divisible by Three ├── 3191. Minimum Operations to Make Binary Array Elements Equal to One I ├── 3206. Alternating Groups I ├── 3208. Alternating Groups II ├── 3210. Find the Encrypted String ├── 3306. Count of Substrings Containing Every Vowel and K Consonants II ├── 3356. Zero Array Transformation II ├── 3392. Count Subarrays of Length Three With a Condition ├── 3396. Minimum Number of Operations to Make Elements in Array Distinct ├── 3487. Maximum Unique Subarray Sum After Deletion └── README.md /0001. Two Sum: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector twoSum(vector& nums, int target) { 4 | unordered_map numIndices; 5 | for (int i = 0; i < nums.size(); ++i) { 6 | if (numIndices.find(target - nums[i]) != numIndices.end()) 7 | return {numIndices[target - nums[i]], i}; 8 | numIndices[nums[i]] = i; 9 | } 10 | return {}; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /0002. Add Two Numbers: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 4 | ListNode* dummy = new ListNode(0); 5 | ListNode* current = dummy; 6 | int carry = 0; 7 | 8 | while (l1 || l2 || carry) { 9 | int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + carry; 10 | carry = sum / 10; 11 | current->next = new ListNode(sum % 10); 12 | current = current->next; 13 | l1 = l1 ? l1->next : nullptr; 14 | l2 = l2 ? l2->next : nullptr; 15 | } 16 | 17 | return dummy->next; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /0003. Longest Substring Without Repeating Characters: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLongestSubstring(string s) { 4 | 5 | unordered_map mp; 6 | int maxl = 0 ; 7 | int l = 0; 8 | 9 | for ( int r = 0 ; r < s.length() ; r++) { 10 | if( mp.find(s[r]) != mp.end()) { 11 | l = max(l, mp[s[r]] + 1); 12 | } 13 | mp[s[r]] = r; 14 | maxl = max( maxl, r - l + 1); 15 | } 16 | 17 | return maxl; 18 | } 19 | }; 20 | 21 | -------------------------------------------------------------------------------- /0004. Median of Two Sorted Arrays: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double findMedianSortedArrays(vector& nums1, vector& nums2) { 4 | priority_queuemaxh; 5 | priority_queue, greater>minh; 6 | 7 | for( auto i : nums1) { 8 | maxh.push(i); 9 | minh.push(maxh.top()); 10 | maxh.pop(); 11 | 12 | if( minh.size() > maxh.size()) { 13 | maxh.push(minh.top()); 14 | minh.pop(); 15 | } 16 | } 17 | for( auto i : nums2) { 18 | maxh.push(i); 19 | minh.push(maxh.top()); 20 | maxh.pop(); 21 | 22 | if( minh.size() > maxh.size()) { 23 | maxh.push(minh.top()); 24 | minh.pop(); 25 | } 26 | } 27 | if( maxh.size() == minh.size()) return (minh.top() + maxh.top()) / 2.0; 28 | else { 29 | return maxh.top(); 30 | } 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /0007. Reverse Integer: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int reverse(int x) { 4 | int r = 0; 5 | 6 | while (x) { 7 | int digit = x % 10; 8 | x /= 10; 9 | if (r > (INT_MAX / 10) || (r == (INT_MAX / 10) && digit > 7)) return 0; 10 | if (r < (INT_MIN / 10) || (r == (INT_MIN / 10) && digit < -8)) return 0; 11 | r = r * 10 + digit; 12 | } 13 | return r; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /0009. Palindrome Number: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPalindrome(int x) { 4 | if (x < 0 || (x % 10 == 0 && x != 0)) return false; 5 | 6 | int reversed = 0; 7 | while (x > reversed) { 8 | reversed = reversed * 10 + x % 10; 9 | x /= 10; 10 | } 11 | 12 | return x == reversed || x == reversed / 10; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /0014. Longest Common Prefix: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string longestCommonPrefix(vector& strs) { 4 | 5 | if (strs.empty()) return ""; 6 | 7 | sort(strs.begin(), strs.end()); 8 | 9 | string f = strs[0]; 10 | string l = strs[strs.size() - 1]; 11 | int i = 0; 12 | 13 | while ( i < f.length() && f[i] == l[i]) i++; 14 | 15 | return f.substr(0,i); 16 | 17 | 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /0015. 3Sum: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> threeSum(vector& nums) { 4 | vector> res; 5 | sort(nums.begin(), nums.end()); 6 | int n = nums.size(); 7 | for (int i = 0; i < n; i++) { 8 | if (i > 0 && nums[i] == nums[i - 1]) 9 | continue; 10 | 11 | int j = i + 1; 12 | int k = n - 1; 13 | while (j < k) { 14 | int total = nums[i] + nums[j] + nums[k]; 15 | 16 | if (total > 0) 17 | k--; 18 | 19 | else if (total < 0) 20 | j++; 21 | else { 22 | res.push_back({nums[i], nums[j], nums[k]}); 23 | j++; 24 | 25 | while (nums[j] == nums[j - 1] && j < k) 26 | j++; 27 | } 28 | } 29 | } 30 | return res; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /0016. 3Sum Closest: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int threeSumClosest(vector& nums, int target) { 4 | int ans = 0 ; 5 | int diff = INT_MAX ; 6 | 7 | sort(nums.begin(), nums.end()); 8 | 9 | for ( int i = 0 ; i < nums.size() ; i++) { 10 | int j = i + 1; 11 | int k = nums.size() - 1; 12 | 13 | while ( j < k ) { 14 | int sum = nums[i] + nums[j] + nums[k]; 15 | 16 | if( sum == target) return sum; 17 | 18 | else if ( abs(target - sum) < diff) { 19 | diff = abs(target - sum); 20 | ans = sum; 21 | } 22 | if (sum > target) k--; 23 | else j++; 24 | } 25 | } 26 | return ans; 27 | 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /0018. 4Sum: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> fourSum(vector& nums, int target) { 4 | int n = nums.size(); 5 | vector> ans; 6 | 7 | sort(nums.begin(), nums.end()); 8 | 9 | for (int i = 0; i < n; i++) { 10 | if (i > 0 && nums[i] == nums[i - 1]) 11 | continue; 12 | for (int j = i + 1; j < n; j++) { 13 | if (j > i + 1 && nums[j] == nums[j - 1]) 14 | continue; 15 | 16 | int k = j + 1; 17 | int l = n - 1; 18 | while (k < l) { 19 | long long sum = nums[i]; 20 | sum += nums[j]; 21 | sum += nums[k]; 22 | sum += nums[l]; 23 | if (sum == target) { 24 | vector temp = {nums[i], nums[j], nums[k], nums[l]}; 25 | ans.push_back(temp); 26 | k++; 27 | l--; 28 | 29 | while (k < l && nums[k] == nums[k - 1]) 30 | k++; 31 | while (k < l && nums[l] == nums[l + 1]) 32 | l--; 33 | } else if (sum < target) 34 | k++; 35 | else 36 | l--; 37 | } 38 | } 39 | } 40 | 41 | return ans; 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /0019. Remove Nth Node From End of List: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* removeNthFromEnd(ListNode* head, int n) { 4 | if( head->next == nullptr) 5 | return nullptr; 6 | ListNode* f = head; 7 | ListNode* d = head; 8 | for (int i = 0; i < n; i++) { 9 | f = f->next; 10 | } 11 | if ( f == nullptr) { 12 | d = d->next; 13 | delete head; 14 | return d; 15 | } 16 | while (f->next != nullptr) { 17 | f = f->next; 18 | d = d->next; 19 | } 20 | f = d->next->next; 21 | delete d->next; 22 | d->next = f; 23 | return head; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /0020. Valid Parentheses: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isValid(string s) { 4 | stack st; 5 | 6 | for (char c : s) { 7 | if (c == '(' || c == '{' || c == '[') { 8 | st.push(c); 9 | } else { 10 | if (st.empty()) { 11 | return false; 12 | } 13 | 14 | char top = st.top(); 15 | if ((c == ')' && top == '(') || 16 | (c == '}' && top == '{') || 17 | (c == ']' && top == '[')) { 18 | st.pop(); 19 | } else { 20 | return false; 21 | } 22 | } 23 | } 24 | 25 | return st.empty(); 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /0021. Merge Two Sorted Lists: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { 14 | 15 | ListNode *dummy = new ListNode(-1); 16 | ListNode *temp = dummy; 17 | ListNode *l1 = list1; 18 | ListNode *l2 = list2; 19 | while(l1 != nullptr && l2 != nullptr) { 20 | if( l1->val <= l2->val) { 21 | dummy->next = l1; 22 | l1 = l1->next; 23 | } 24 | else { 25 | dummy->next = l2; 26 | l2 = l2->next; 27 | } 28 | dummy = dummy->next; 29 | } 30 | 31 | if( l1 != nullptr) { 32 | dummy->next = l1; 33 | } 34 | else { 35 | dummy->next = l2; 36 | } 37 | return temp->next; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /0023. Merge k Sorted Lists: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public: 4 | struct compare { 5 | bool operator()(ListNode* a, ListNode* b) { 6 | return a->val > b->val; 7 | } 8 | }; 9 | 10 | ListNode* mergeKLists(vector& lists) { 11 | priority_queue, compare> minHeap; 12 | 13 | for (auto l : lists) { 14 | if (l) minHeap.push(l); 15 | } 16 | 17 | ListNode* dummy = new ListNode(); 18 | ListNode* tail = dummy; 19 | 20 | while (!minHeap.empty()) { 21 | ListNode* node = minHeap.top(); 22 | minHeap.pop(); 23 | 24 | tail->next = node; 25 | tail = tail->next; 26 | 27 | if (node->next) { 28 | minHeap.push(node->next); 29 | } 30 | } 31 | 32 | return dummy->next; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /0024. Swap Nodes in Pairs: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* swapPairs(ListNode* head) { 14 | ListNode* cur = head; 15 | while (cur && cur->next) { 16 | int temp = cur->val; 17 | cur->val = cur->next->val; 18 | cur->next->val = temp; 19 | cur = cur->next->next; 20 | } 21 | return head; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /0025. Reverse Nodes in k-Group: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | private: 13 | ListNode* getKthNode(ListNode* temp, int k) { 14 | k -= 1; 15 | while (temp != nullptr && k > 0) { 16 | k--; 17 | temp = temp->next; 18 | } 19 | return temp; 20 | } 21 | ListNode* reverseList(ListNode* head) { 22 | ListNode* curr = head; 23 | ListNode* prev = nullptr; 24 | while (curr != nullptr) { 25 | ListNode* next = curr->next; 26 | curr->next = prev; 27 | prev = curr; 28 | curr = next; 29 | } 30 | return prev; 31 | } 32 | 33 | public: 34 | ListNode* reverseKGroup(ListNode* head, int k) { 35 | ListNode* temp = head; 36 | ListNode* prev = nullptr; 37 | 38 | while (temp != nullptr) { 39 | ListNode* kthNode = getKthNode(temp, k); 40 | 41 | if (kthNode == nullptr) { 42 | if (prev) { 43 | prev->next = temp; 44 | } 45 | break; 46 | } 47 | 48 | ListNode* nextNode = kthNode->next; 49 | kthNode->next = nullptr; 50 | reverseList(temp); 51 | 52 | if (temp == head) { 53 | head = kthNode; 54 | } else { 55 | prev->next = kthNode; 56 | } 57 | prev = temp; 58 | temp = nextNode; 59 | } 60 | return head; 61 | } 62 | }; 63 | -------------------------------------------------------------------------------- /0026. Remove Duplicates from Sorted Array: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeDuplicates(vector& nums) { 4 | int count = 1; 5 | int temp = nums[0]; 6 | vector ans; 7 | ans.push_back(temp); 8 | for ( int i = 0 ; i < nums.size() ;i++){ 9 | if(temp != nums[i]){ 10 | count++; 11 | temp = nums[i]; 12 | ans.push_back(temp); 13 | } 14 | 15 | } 16 | nums = ans; 17 | return count; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /0027. Remove Element: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeElement(vector& nums, int val) { 4 | int count = 0; 5 | vector ans; 6 | for ( int i = 0 ; i < nums.size() ;i++){ 7 | if(val != nums[i]){ 8 | count++; 9 | ans.push_back(nums[i]); 10 | } 11 | } 12 | nums = ans; 13 | return count; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /0028. Find the Index of the First Occurrence in a String: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int strStr(string haystack, string needle) { 4 | int n = haystack.length(), m = needle.length(); 5 | 6 | for (int i = 0; i <= n - m; i++) { 7 | int j = 0; 8 | while (j < m && haystack[i + j] == needle[j]) { 9 | j++; 10 | } 11 | if (j == m) return i; // Found match 12 | } 13 | 14 | return -1; // Not found 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /0031. Next Permutation: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void nextPermutation(vector& nums) { 4 | int n = nums.size(), i = n - 2; 5 | while (i >= 0 && nums[i] >= nums[i + 1]) { 6 | i--; 7 | } 8 | if (i >= 0) { 9 | int j = n - 1; 10 | while (nums[j] <= nums[i]) { 11 | j--; 12 | } 13 | swap(nums[i], nums[j]); 14 | } 15 | reverse(nums.begin() + i + 1, nums.end()); 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /0033. Search in Rotated Sorted Array: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int search(vector& nums, int target) { 4 | int left = 0, right = nums.size() - 1; 5 | 6 | while (left <= right) { 7 | int mid = (left + right) / 2; 8 | 9 | if (nums[mid] == target) 10 | return mid; 11 | 12 | if (nums[left] <= nums[mid]) { 13 | if (nums[left] <= target && target < nums[mid]) 14 | right = mid - 1; 15 | else 16 | left = mid + 1; 17 | } else { 18 | if (nums[mid] < target && target <= nums[right]) 19 | left = mid + 1; 20 | else 21 | right = mid - 1; 22 | } 23 | } 24 | return -1; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /0034. Find First and Last Position of Element in Sorted Array: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector searchRange(vector& nums, int target) { 4 | vector ans = {-1, -1}; 5 | if( !nums.size()) return ans; 6 | int l = 0, r = nums.size() -1, mid = 0; 7 | 8 | while ( l <= r) { 9 | mid = (l + r) / 2; 10 | if( nums[mid] >= target) r = mid - 1; 11 | else l= mid + 1; 12 | } 13 | if( l < nums.size() && nums[l] == target) ans[0] = l; 14 | 15 | l = 0; r = nums.size() - 1; 16 | while ( l <= r ) { 17 | mid = (l + r)/ 2; 18 | if ( nums[mid] <= target) l = mid + 1; 19 | else r = mid - 1; 20 | } 21 | 22 | if ( r >= 0 && nums[r] == target) ans[1] = r; 23 | return ans; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /0035. Search Insert Position: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int searchInsert(vector& nums, int target) { 4 | int first = 0; 5 | int last = nums.size() - 1; 6 | 7 | while (first <= last) { 8 | int mid = first + (last - first) / 2; 9 | if (nums[mid] == target) { 10 | return mid; 11 | } 12 | if (nums[mid] < target) { 13 | first = mid + 1; 14 | } else { 15 | last = mid - 1; 16 | } 17 | } 18 | 19 | return first; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /0039. Combination Sum: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private : 3 | void cSum( vector&c , int t , int index, vector&curr, vector>& ans){ 4 | if (t == 0) { 5 | ans.push_back(curr); 6 | return; 7 | } 8 | for ( int i = index ; i < c.size() ; i++) { 9 | if(c[i] > t) break; 10 | curr.push_back(c[i]); 11 | cSum(c, t - c[i], i, curr, ans); 12 | curr.pop_back(); 13 | } 14 | } 15 | public: 16 | vector> combinationSum(vector& c, int t) { 17 | sort(c.begin() ,c.end()); 18 | vector> ans; 19 | vector curr; 20 | cSum(c, t, 0, curr, ans); 21 | return ans; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /0040. Combination Sum II: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private : 3 | void cSum( vector&c , int t , int index, vector&curr, vector>& ans){ 4 | if (t == 0) { 5 | ans.push_back(curr); 6 | return; 7 | } 8 | for ( int i = index ; i < c.size() ; i++) { 9 | if( i > index && c[i] == c[i-1]) continue; 10 | if(c[i] > t) break; 11 | curr.push_back(c[i]); 12 | cSum(c, t - c[i], i+1, curr, ans); 13 | curr.pop_back(); 14 | } 15 | } 16 | public: 17 | vector> combinationSum2(vector& c, int t) { 18 | sort(c.begin() ,c.end()); 19 | vector> ans; 20 | vector curr; 21 | cSum(c, t, 0, curr, ans); 22 | return ans; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /0041. First Missing Positive: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int firstMissingPositive(vector& nums) { 4 | int n = nums.size(); 5 | for (int i = 0; i < n; i++) { 6 | while (nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] != nums[i]){ 7 | swap(nums[i], nums[nums[i] - 1]);} 8 | } 9 | for (int i = 0; i < n; i++) { 10 | if (nums[i] != i + 1) 11 | return i + 1; 12 | } 13 | return n + 1; 14 | } 15 | }; 16 | 17 | 18 | -------------------------------------------------------------------------------- /0042. Trapping Rain Water: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int trap(vector& arr) { 4 | int n = arr.size(); 5 | int res = 0; 6 | int l = 0; 7 | int r = n - 1; 8 | int ml = 0; 9 | int mr = 0; 10 | 11 | while (l <= r) { 12 | if (arr[l] <= arr[r]) { 13 | if (arr[l] >= ml) { 14 | ml = arr[l]; 15 | } else { 16 | res += ml - arr[l]; 17 | } 18 | l++; 19 | } else { 20 | if (arr[r] >= mr) { 21 | mr = arr[r]; 22 | } else { 23 | res += mr - arr[r]; 24 | } 25 | r--; 26 | } 27 | } 28 | return res; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /0048. Rotate Image: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void rotate(vector>& matrix) { 4 | int n = matrix.size(); 5 | for (int i = 0; i < n; ++i) { 6 | for (int j = i; j < n; ++j) { 7 | swap(matrix[i][j], matrix[j][i]); 8 | } 9 | } 10 | for (int i = 0; i < n; ++i) { 11 | reverse(matrix[i].begin(), matrix[i].end()); 12 | } 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /0050. Pow(x, n): -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double myPow(double x, int n) { 4 | long long exp = n; 5 | if (exp < 0) { 6 | x = 1 / x; 7 | exp = -exp; 8 | } 9 | 10 | double result = 1.0; 11 | while (exp > 0) { 12 | if (exp % 2 == 1) { 13 | result *= x; 14 | } 15 | x *= x; 16 | exp /= 2; 17 | } 18 | return result; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /0053. Maximum Subarray: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxSubArray(vector& nums) { 4 | long long int maxi = LONG_MIN; 5 | long long int sum = 0; 6 | for ( int i = 0 ; i < nums.size() ; i++) { 7 | sum += nums[i]; 8 | 9 | if( sum > maxi) 10 | maxi = sum; 11 | 12 | if( sum < 0) sum =0; 13 | } 14 | return maxi; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /0056. Merge Intervals: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> merge(vector>& intervals) { 4 | if (intervals.empty()) return {}; 5 | sort(intervals.begin(), intervals.end()); 6 | 7 | vector> ans; 8 | ans.push_back(intervals[0]); 9 | 10 | for (int i = 1; i < intervals.size(); i++) { 11 | vector& last = ans.back(); 12 | 13 | if (last[1] >= intervals[i][0]) { 14 | last[1] = max(last[1], intervals[i][1]); 15 | } else { 16 | ans.push_back(intervals[i]); 17 | } 18 | } 19 | 20 | return ans; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /0058. Length of Last Word: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLastWord(string s) { 4 | int count =0; 5 | int mcount = 0; 6 | for( char c : s){ 7 | if(c == ' '){ 8 | count = 0; 9 | } 10 | else{ 11 | count++; 12 | mcount = count; 13 | } 14 | } 15 | return mcount; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /0061. Rotate List: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* rotateRight(ListNode* head, int k) { 4 | if (!head || k == 0) return head; 5 | ListNode* temp = head; 6 | int length = 1; 7 | while (temp->next) { 8 | temp = temp->next; 9 | length++; 10 | } 11 | k = k % length; 12 | if (k == 0) return head; 13 | temp->next = head; 14 | int stepsToNewTail = length - k; 15 | temp = head; 16 | for (int i = 1; i < stepsToNewTail; i++) { 17 | temp = temp->next; 18 | } 19 | ListNode* newHead = temp->next; 20 | temp->next = nullptr; 21 | return newHead; 22 | } 23 | }; 24 | 25 | -------------------------------------------------------------------------------- /0066. Plus One: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector plusOne(vector& digits) { 4 | int n = digits.size(); 5 | for (int i = n - 1; i >= 0; --i) { 6 | if (digits[i] < 9) { 7 | digits[i]++; 8 | return digits; 9 | } 10 | digits[i] = 0; 11 | } 12 | digits.insert(digits.begin(), 1); 13 | return digits; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /0069. Sqrt(x): -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int mySqrt(int x) { 4 | 5 | 6 | if( x == 0 || x == 1) return x; 7 | 8 | long long int s = 1; 9 | long long int m = -1; 10 | long long int e = x; 11 | 12 | while ( s <= e) { 13 | m = (s + e) / 2; 14 | 15 | if( m * m > x) 16 | e = m - 1; 17 | else if( m * m == x) return m; 18 | else 19 | s= m + 1; 20 | } 21 | 22 | return round(e); 23 | 24 | 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /0070. Climbing Stairs: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int climbStairs(int n) { 4 | if (n <= 2) return n; 5 | int prev1 = 1, prev2 = 2; 6 | for (int i = 3; i <= n; i++) { 7 | int curr = prev1 + prev2; 8 | prev1 = prev2; 9 | prev2 = curr; 10 | } 11 | return prev2; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /0073. Set Matrix Zeroes: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void setZeroes(vector>& matrix){ 4 | int m = matrix.size(); 5 | int n = matrix[0].size(); 6 | int col0 = 1; 7 | 8 | for (int i = 0 ; i < m ; i++){ 9 | for (int j = 0 ; j < n ;j++){ 10 | if(matrix[i][j] == 0){ 11 | matrix[i][0] = 0; 12 | 13 | if(j == 0) { 14 | col0 = 0; 15 | } 16 | else { 17 | matrix[0][j] = 0; 18 | } 19 | } 20 | } 21 | } 22 | 23 | for (int i = 1 ; i < m ; i++){ 24 | for (int j = 1 ; j < n ;j++){ 25 | if (matrix[i][0] == 0 || matrix[0][j] == 0) { 26 | matrix[i][j] = 0; 27 | } 28 | 29 | } 30 | } 31 | 32 | if (matrix[0][0] == 0) { 33 | for (int j = 0; j < n; j++) { 34 | matrix[0][j] = 0; 35 | } 36 | } 37 | if (col0 == 0) { 38 | for (int i = 0; i < m; i++) { 39 | matrix[i][0] = 0; 40 | } 41 | } 42 | } 43 | }; 44 | -------------------------------------------------------------------------------- /0074. Search a 2D Matrix: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool searchMatrix(vector>& matrix, int target) { 4 | int n = matrix.size(); 5 | int m = matrix[0].size(); 6 | 7 | int low = 0, high = n * m - 1; 8 | while (low <= high) { 9 | int mid = (low + high) / 2; 10 | int row = mid / m, col = mid % m; 11 | if (matrix[row][col] == target) 12 | return true; 13 | else if (matrix[row][col] < target) 14 | low = mid + 1; 15 | else 16 | high = mid - 1; 17 | } 18 | return false; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /0075. Sort Colors: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void sortColors(vector& nums) { 4 | int l = 0, m = 0, r = nums.size() - 1; 5 | 6 | while (m <= r) { 7 | if (nums[m] == 0) { 8 | swap(nums[l], nums[m]); 9 | l++; 10 | m++; 11 | } 12 | else if (nums[m] == 2) { 13 | swap(nums[m], nums[r]); 14 | r--; 15 | } 16 | else { 17 | m++; 18 | } 19 | } 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /0078. Subsets: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> subsets(vector& nums) { 4 | vector> ans; 5 | ans.push_back(vector()); 6 | 7 | for ( int i = 0 ; i < nums.size() ; i++){ 8 | int n = ans.size(); 9 | for ( int j = 0 ; j < n ; j++){ 10 | vector ele = ans[j]; 11 | ele.push_back(nums[i]); 12 | ans.push_back(ele); 13 | } 14 | } 15 | return ans; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /0083. Remove Duplicates from Sorted List: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* deleteDuplicates(ListNode* head) { 14 | ListNode* temp = head; 15 | while (temp && temp->next) { 16 | if (temp->val == temp->next->val) 17 | temp->next = temp->next->next; 18 | else 19 | temp = temp->next; 20 | } 21 | return head; 22 | 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /0088. Merge Sorted Array: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void merge(vector& nums1, int m, vector& nums2, int n) { 4 | int i = m - 1, j = n - 1, k = m + n - 1; 5 | 6 | while (i >= 0 && j >= 0) { 7 | if (nums1[i] > nums2[j]) { 8 | nums1[k--] = nums1[i--]; 9 | } else { 10 | nums1[k--] = nums2[j--]; 11 | } 12 | } 13 | while (j >= 0) { 14 | nums1[k--] = nums2[j--]; 15 | } 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /0090. Subsets II: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | private: 4 | void totalSubset(vector nums, int index, vector arr, 5 | vector>& ans) { 6 | 7 | ans.push_back(arr); 8 | 9 | for (int i = index; i < nums.size(); i++) { 10 | 11 | if (i > index && nums[i] == nums[i - 1]) 12 | continue; 13 | 14 | arr.push_back(nums[i]); 15 | totalSubset(nums, i + 1, arr, ans); 16 | 17 | arr.pop_back(); 18 | } 19 | } 20 | 21 | public: 22 | vector> subsetsWithDup(vector& nums) { 23 | sort(nums.begin(), nums.end()); 24 | 25 | vector> ans; 26 | vector arr; 27 | 28 | totalSubset(nums, 0, arr, ans); 29 | return ans; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /0094. Binary Tree Inorder Traversal: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | 14 | private: 15 | void helper(TreeNode* root, vector&res) { 16 | if( root != nullptr) { 17 | helper(root->left, res); 18 | res.push_back(root->val); 19 | helper(root->right, res); 20 | } 21 | } 22 | public: 23 | vector inorderTraversal(TreeNode* root) { 24 | vector res; 25 | helper(root, res); 26 | return res; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /0098. Validate Binary Search Tree: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isValidBST(TreeNode* root, long minVal = LONG_MIN, long maxVal = LONG_MAX) { 4 | if (!root) return true; 5 | 6 | if (root->val <= minVal || root->val >= maxVal) return false; 7 | return isValidBST(root->left, minVal, root->val) && 8 | isValidBST(root->right, root->val, maxVal); 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /0100. Same Tree: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isSameTree(TreeNode* p, TreeNode* q) { 4 | if (!p && !q) { 5 | return true; 6 | } 7 | 8 | if (p && q && p->val == q->val) { 9 | return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); 10 | } 11 | 12 | return false; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /0102. Binary Tree Level Order Traversal: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | vector> levelOrder(TreeNode* root) { 15 | 16 | vector> ans; 17 | 18 | 19 | if( !root) return ans; 20 | 21 | queueq; 22 | q.push(root); 23 | 24 | while( !q.empty()) { 25 | vector res; 26 | int s = q.size(); 27 | 28 | while( s--) { 29 | 30 | TreeNode* temp = q.front(); 31 | res.push_back(temp->val); 32 | q.pop(); 33 | 34 | if( temp->left) q.push(temp->left); 35 | if( temp->right) q.push(temp->right); 36 | 37 | } 38 | ans.push_back(res); 39 | 40 | } 41 | return ans; 42 | 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /0103. Binary Tree Zigzag Level Order Traversal: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | vector> zigzagLevelOrder(TreeNode* root) { 15 | bool d = 1; 16 | vector> ans; 17 | 18 | if(!root) return ans; 19 | 20 | queue q; 21 | q.push(root); 22 | 23 | while ( !q.empty()) { 24 | int n = q.size(); 25 | vector res(n); 26 | for ( int i = 0 ; i < n ;i++) { 27 | 28 | TreeNode* temp = q.front(); 29 | q.pop(); 30 | int index = d ? i : n-i-1; 31 | res[index] = temp->val; 32 | if( temp->left) q.push(temp->left); 33 | if( temp->right) q.push(temp->right); 34 | } 35 | ans.push_back(res); 36 | d = !d; 37 | 38 | } 39 | return ans; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /0104. Maximum Depth of Binary Tree: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int maxDepth(TreeNode* root) { 15 | int ans = 0 ; 16 | if ( !root) return ans; 17 | 18 | queuest; 19 | st.push(root); 20 | 21 | while (!st.empty()) { 22 | ans++; 23 | int s = st.size(); 24 | 25 | while ( s--) { 26 | TreeNode* temp = st.front(); 27 | st.pop(); 28 | if(temp->left) st.push(temp->left); 29 | if(temp->right) st.push(temp->right); 30 | } 31 | } 32 | return ans; 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /0113. Path Sum II: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | private: 14 | void calPathSum( TreeNode* root, int t, int &csum, vector&res, vector>&ans ) { 15 | if(!root) return; 16 | 17 | csum += root->val; 18 | res.push_back(root->val); 19 | 20 | if(!root->left && !root->right && csum == t ) ans.push_back(res); 21 | calPathSum(root->right, t, csum, res, ans); 22 | calPathSum(root->left, t , csum, res, ans); 23 | csum -= root->val; 24 | res.pop_back(); 25 | } 26 | public: 27 | vector> pathSum(TreeNode* root, int targetSum) { 28 | TreeNode *curr= root; 29 | vector> ans; 30 | vectorres; 31 | int csum = 0; 32 | calPathSum(curr, targetSum, csum, res, ans); 33 | return ans; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /0114. Flatten Binary Tree to Linked List: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | void flatten(TreeNode* root) { 15 | TreeNode *curr = root; 16 | 17 | while (curr) { 18 | if (curr->left) { 19 | TreeNode *pred = curr->left; 20 | while( pred->right) { 21 | pred = pred->right; 22 | } 23 | pred->right = curr->right; 24 | curr->right = curr->left; 25 | curr->left = nullptr; 26 | } 27 | curr = curr->right; 28 | } 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /0118. Pascal's Triangle: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> generate(int numRows) { 4 | vector> ans; 5 | 6 | for (int i = 0; i < numRows; i++) { 7 | vector curr(i + 1, 1); 8 | 9 | for (int j = 1; j < i; j++) { 10 | curr[j] = ans[i - 1][j - 1] + ans[i - 1][j]; 11 | } 12 | ans.push_back(curr); 13 | } 14 | 15 | return ans; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /0119. Pascal's Triangle II: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector getRow(int rowIndex) { 4 | vector row(rowIndex + 1, 1); // Initialize all elements to 1 5 | 6 | for (int i = 1; i < rowIndex; ++i) { 7 | row[i] = (long long)row[i - 1] * (rowIndex - i + 1) / i; 8 | } 9 | 10 | return row; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /0121. Best Time to Buy and Sell Stock: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& s) { 4 | 5 | int mn = s[0]; 6 | int mp = 0; 7 | for ( int i = 1 ; i < s.size() ; i++) { 8 | mn = min( mn, s[i]); 9 | mp = max( mp, s[i] - mn); 10 | } 11 | return mp; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /0122. Best Time to Buy and Sell Stock II: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices) { 4 | int ans = 0; 5 | for ( int i = 1 ; i < prices.size() ; i++){ 6 | if( prices[i] > prices[i-1]){ 7 | ans += prices[i] - prices[i-1]; 8 | } 9 | } 10 | return ans; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /0128. Longest Consecutive Sequence: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestConsecutive(vector& nums) { 4 | if(!nums.size()) return 0; 5 | int count = 1; 6 | int max = 1; 7 | sort(nums.begin(), nums.end()); 8 | for (int i = 1; i < nums.size(); i++) { 9 | if (nums[i - 1] + 1 == nums[i]) { 10 | count++; 11 | if (count > max) 12 | max = count; 13 | 14 | } 15 | else if( nums[i-1] == nums[i]) continue; 16 | else { 17 | count = 1; 18 | } 19 | } 20 | return max; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /0133. Clone Graph: -------------------------------------------------------------------------------- 1 | /* 2 | // Definition for a Node. 3 | class Node { 4 | public: 5 | int val; 6 | vector neighbors; 7 | Node() { 8 | val = 0; 9 | neighbors = vector(); 10 | } 11 | Node(int _val) { 12 | val = _val; 13 | neighbors = vector(); 14 | } 15 | Node(int _val, vector _neighbors) { 16 | val = _val; 17 | neighbors = _neighbors; 18 | } 19 | }; 20 | */ 21 | 22 | class Solution { 23 | public: 24 | unordered_mapcloned; 25 | Node* cloneGraph(Node* node) { 26 | if (!node) return nullptr; 27 | if(cloned.find(node) != cloned.end()) return cloned[node]; 28 | 29 | Node* nN = new Node(node->val); 30 | cloned[node] = nN; 31 | 32 | for ( auto neigh : node->neighbors) 33 | nN->neighbors.push_back(cloneGraph(neigh)); 34 | return nN; 35 | 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /0136. Single Number: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int singleNumber(vector& nums) { 4 | int s = 0; 5 | for (int num : nums) { 6 | s ^= num; 7 | } 8 | return s; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /0138. Copy List with Random Pointer: -------------------------------------------------------------------------------- 1 | /* 2 | // Definition for a Node. 3 | class Node { 4 | public: 5 | int val; 6 | Node* next; 7 | Node* random; 8 | 9 | Node(int _val) { 10 | val = _val; 11 | next = NULL; 12 | random = NULL; 13 | } 14 | }; 15 | */ 16 | 17 | class Solution { 18 | public: 19 | Node* copyRandomList(Node* head) { 20 | 21 | if (!head) 22 | return nullptr; 23 | 24 | Node* curr = head; 25 | while (curr) { 26 | Node* copy = new Node(curr->val); 27 | copy->next = curr->next; 28 | curr->next = copy; 29 | curr = copy->next; 30 | } 31 | 32 | curr = head; 33 | while (curr) { 34 | if (curr->random) { 35 | curr->next->random = curr->random->next; 36 | } 37 | curr = curr->next->next; 38 | } 39 | 40 | curr = head; 41 | Node* dummy = new Node(0); 42 | Node* res = dummy; 43 | while (curr) { 44 | dummy->next = curr->next; 45 | curr->next = curr->next->next; 46 | 47 | curr = curr->next; 48 | dummy = dummy->next; 49 | } 50 | 51 | return res->next; 52 | } 53 | }; 54 | -------------------------------------------------------------------------------- /0141. Linked List Cycle: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | bool hasCycle(ListNode *head) { 12 | 13 | map llc; 14 | 15 | ListNode* temp = head; 16 | 17 | while(temp != nullptr) { 18 | if( llc.find(temp) != llc.end()) { 19 | return true; 20 | } 21 | 22 | llc[temp] = 1; 23 | temp = temp->next; 24 | } 25 | return false; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /0142. Linked List Cycle II: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | 10 | class Solution { 11 | public: 12 | ListNode *detectCycle(ListNode *head) { 13 | if (!head || !head->next) return nullptr; 14 | 15 | ListNode *slow = head; 16 | ListNode *fast = head; 17 | while (fast && fast->next) { 18 | slow = slow->next; 19 | fast = fast->next->next; 20 | if (slow == fast) { 21 | ListNode *entry = head; 22 | while (entry != slow) { 23 | entry = entry->next; 24 | slow = slow->next; 25 | } 26 | return entry; 27 | } 28 | } 29 | return nullptr; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /0144. Binary Tree Preorder Traversal: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | 14 | private: 15 | void helperTree(TreeNode* root, vector& res) { 16 | if( root) { 17 | res.push_back(root->val); 18 | helperTree(root->left, res); 19 | helperTree(root->right, res); 20 | } 21 | } 22 | public: 23 | vector preorderTraversal(TreeNode* root) { 24 | vector res; 25 | helperTree(root, res); 26 | return res; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /0145. Binary Tree Postorder Traversal: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void helper(TreeNode* root, vector& ans) { 4 | if (root == nullptr) return; 5 | helper(root->left, ans); 6 | helper(root->right, ans); 7 | ans.push_back(root->val); 8 | } 9 | vector postorderTraversal(TreeNode* root) { 10 | vector ans; 11 | helper(root, ans); 12 | return ans; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /0151. Reverse Words in a String: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void trimSpaces(string& s) { 4 | int left = 0, right = s.size() - 1; 5 | 6 | while (left <= right && s[left] == ' ') left++; 7 | 8 | while (right >= left && s[right] == ' ') right--; 9 | 10 | int i = 0; 11 | while (left <= right) { 12 | if (s[left] != ' ' || (i > 0 && s[i - 1] != ' ')) { 13 | s[i++] = s[left]; 14 | } 15 | left++; 16 | } 17 | 18 | s.resize(i); 19 | } 20 | 21 | void reverse(string& s, int left, int right) { 22 | while (left < right) { 23 | swap(s[left++], s[right--]); 24 | } 25 | } 26 | 27 | void reverseEachWord(string& s) { 28 | int n = s.size(); 29 | int start = 0, end = 0; 30 | 31 | while (start < n) { 32 | while (end < n && s[end] != ' ') end++; 33 | reverse(s, start, end - 1); 34 | start = end + 1; 35 | end++; 36 | } 37 | } 38 | 39 | string reverseWords(string s) { 40 | trimSpaces(s); 41 | reverse(s, 0, s.size() - 1); 42 | reverseEachWord(s); 43 | 44 | return s; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /0153. Find Minimum in Rotated Sorted Array: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMin(vector& nums) { 4 | int n = nums.size(); 5 | int ans = nums[0]; 6 | for ( int i = 0 ; i < n ; i++){ 7 | if( nums[0] > nums[nums.size() - 1]){ 8 | ans = nums[nums.size() - 1]; 9 | nums.pop_back(); 10 | } 11 | 12 | } 13 | return ans; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /0155. Min Stack: -------------------------------------------------------------------------------- 1 | class MinStack { 2 | 3 | stack s; 4 | stack m; 5 | 6 | public: 7 | MinStack() {} 8 | 9 | void push(int val) { 10 | s.push(val); 11 | if (m.empty() || val < m.top()) { 12 | m.push(val); 13 | } else { 14 | 15 | m.push(m.top()); 16 | } 17 | } 18 | 19 | void pop() { 20 | s.pop(); 21 | m.pop(); 22 | } 23 | 24 | int top() { return s.top(); } 25 | 26 | int getMin() { return m.top(); } 27 | }; 28 | 29 | /** 30 | * Your MinStack object will be instantiated and called as such: 31 | * MinStack* obj = new MinStack(); 32 | * obj->push(val); 33 | * obj->pop(); 34 | * int param_3 = obj->top(); 35 | * int param_4 = obj->getMin(); 36 | */ 37 | -------------------------------------------------------------------------------- /0160. Intersection of Two Linked Lists: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) { 12 | ListNode* d1 = headA; 13 | ListNode* d2 = headB; 14 | 15 | while (d1 != d2) { 16 | d1 = d1 == NULL ? headB : d1->next; 17 | d2 = d2 == NULL ? headA : d2->next; 18 | } 19 | 20 | return d1; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /0167. Two Sum II - Input Array Is Sorted: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector twoSum(vector& nums, int target) { 4 | int l = 0, r = nums.size()-1; 5 | while ( l < r) { 6 | if((nums[l] + nums[r]) == target) return {l+1,r+1}; 7 | else if ((nums[l] + nums[r]) < target) l++; 8 | else r--; 9 | } 10 | return {-1,-1}; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /0169. Majority Element: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int majorityElement(vector& nums) { 4 | 5 | int candidate = 0, count = 0; 6 | 7 | for (int num : nums) { 8 | if (count == 0) { 9 | candidate = num; 10 | } 11 | count += (num == candidate) ? 1 : -1; 12 | } 13 | 14 | return candidate; 15 | 16 | 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /0171. Excel Sheet Column Number: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int titleToNumber(string columnTitle) { 4 | int result = 0; 5 | for (char c : columnTitle) { 6 | result = result * 26 + (c - 'A' + 1); 7 | } 8 | return result; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /0172. Factorial Trailing Zeroes: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int trailingZeroes(int n) { 4 | int count = 0; 5 | while (n >= 5) { 6 | n /= 5; 7 | count += n; 8 | } 9 | return count; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /0189. Rotate Array: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void rotate(vector& nums, int k) { 4 | k = k% nums.size(); 5 | vector ans(nums.size(), 0); 6 | for( int i = 0 ; i < nums.size() ; i++){ 7 | ans[i] = nums[ (nums.size() - k + i)%(nums.size())]; 8 | } 9 | nums = ans; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /0199. Binary Tree Right Side View: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | vector rightSideView(TreeNode* root) { 15 | vector ans; 16 | if( !root ) return ans; 17 | 18 | queueq; 19 | q.push(root); 20 | 21 | while(!q.empty()) { 22 | 23 | int s = q.size(); 24 | TreeNode* temp = NULL; 25 | 26 | while( s--) { 27 | TreeNode* n = q.front(); 28 | q.pop(); 29 | temp = n; 30 | if( n->left) q.push(n->left); 31 | if( n->right) q.push(n->right); 32 | } 33 | ans.push_back(temp->val); 34 | 35 | } 36 | return ans; 37 | } 38 | }; 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /0201. Bitwise AND of Numbers Range: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int rangeBitwiseAnd(int left, int right) { 4 | while (left < right) { 5 | right = right & (right - 1); 6 | } 7 | return right; 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /0206. Reverse Linked List: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* reverseList(ListNode* head) { 14 | ListNode* prev = nullptr; 15 | ListNode* curr = head; 16 | while (curr != nullptr) { 17 | ListNode* next = curr->next; 18 | curr->next = prev; 19 | prev = curr; 20 | curr = next; 21 | } 22 | return prev; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /0209. Minimum Size Subarray Sum: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minSubArrayLen(int target, vector& nums) { 4 | int sum = 0; 5 | int mcount = nums.size() + 1; 6 | int i = 0; 7 | int j = 0; 8 | while (j < nums.size()) { 9 | sum += nums[j]; 10 | while (sum >= target) { 11 | mcount = min(mcount, j - i + 1); 12 | sum -= nums[i]; 13 | i++; 14 | } 15 | j++; 16 | } 17 | return (mcount == nums.size() + 1) ? 0 : mcount; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /0215. Kth Largest Element in an Array: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findKthLargest(vector& nums, int k) { 4 | priority_queue, greater> pq; 5 | 6 | for ( auto i : nums) { 7 | pq.push(i); 8 | if(pq.size() > k) { 9 | pq.pop(); 10 | } 11 | } 12 | return pq.top(); 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /0217. Contains Duplicate: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool containsDuplicate(vector& nums) { 4 | sort(nums.begin(), nums.end()); 5 | for (int i = 1; i < nums.size(); i++) { 6 | if (nums[i - 1] != nums[i]) 7 | continue; 8 | else 9 | return 1; 10 | } 11 | return 0; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /0222. Count Complete Tree Nodes: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int countNodes(TreeNode* root) { 15 | if(!root) return 0; 16 | return (countNodes(root->left) + countNodes(root->right)) + 1; 17 | 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /0225. Implement Stack using Queues: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class MyStack { 6 | public: 7 | queue q; 8 | 9 | MyStack() { 10 | 11 | } 12 | 13 | void push(int x) { 14 | int n = q.size(); 15 | q.push(x); 16 | for (int i = 0; i < n; i++) { 17 | q.push(q.front()); 18 | q.pop(); 19 | } 20 | } 21 | 22 | int pop() { 23 | int topElement = q.front(); 24 | q.pop(); 25 | return topElement; 26 | } 27 | 28 | int top() { 29 | return q.front(); 30 | } 31 | 32 | bool empty() { 33 | return q.empty(); 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /0226. Invert Binary Tree: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), 10 | * right(right) {} 11 | * }; 12 | */ 13 | class Solution { 14 | public: 15 | TreeNode* invertTree(TreeNode* root) { 16 | if (root == nullptr) 17 | return nullptr; 18 | TreeNode* temp = root->left; 19 | root->left = root->right; 20 | root->right = temp; 21 | invertTree(root->left); 22 | invertTree(root->right); 23 | return root; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /0229. Majority Element II: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector majorityElement(vector& nums) { 4 | int num1 = -1, num2 = -1, count1 = 0, count2 = 0; 5 | int n = nums.size(); 6 | for (int num : nums) { 7 | if (num == num1) count1++; 8 | else if (num == num2) count2++; 9 | else if (count1 == 0) num1 = num, count1 = 1; 10 | else if (count2 == 0) num2 = num, count2 = 1; 11 | else count1--, count2--; 12 | } 13 | count1 = count2 = 0; 14 | for (int num : nums) { 15 | if (num == num1) count1++; 16 | else if (num == num2) count2++; 17 | } 18 | vector result; 19 | if (count1 > n / 3) result.push_back(num1); 20 | if (count2 > n / 3) result.push_back(num2); 21 | 22 | 23 | return result; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /0231. Power of Two: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPowerOfTwo(int n) { 4 | if (n <= 0) { 5 | return false; 6 | } 7 | return (n & (n - 1)) == 0; 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /0232. Implement Queue using Stacks: -------------------------------------------------------------------------------- 1 | class MyQueue { 2 | private: 3 | stack inputStack, outputStack; 4 | 5 | public: 6 | MyQueue() {} 7 | 8 | void push(int x) { 9 | inputStack.push(x); 10 | } 11 | 12 | int pop() { 13 | if (outputStack.empty()) { 14 | while (!inputStack.empty()) { 15 | outputStack.push(inputStack.top()); 16 | inputStack.pop(); 17 | } 18 | } 19 | int frontElement = outputStack.top(); 20 | outputStack.pop(); 21 | return frontElement; 22 | } 23 | 24 | int peek() { 25 | if (outputStack.empty()) { 26 | while (!inputStack.empty()) { 27 | outputStack.push(inputStack.top()); 28 | inputStack.pop(); 29 | } 30 | } 31 | return outputStack.top(); 32 | } 33 | 34 | bool empty() { 35 | return inputStack.empty() && outputStack.empty(); 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /0234. Palindrome Linked List: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | bool isPalindrome(ListNode* head) { 14 | 15 | if (head == NULL || head->next == NULL) return true; 16 | 17 | ListNode* mid = head; 18 | ListNode* full = head; 19 | while ( full->next && full->next->next){ 20 | mid = mid->next; 21 | full = full->next->next; 22 | } 23 | 24 | ListNode* first = head; 25 | ListNode* second = reverseList(mid->next); 26 | 27 | while(second) { 28 | if(first->val != second->val){ 29 | return false; 30 | } 31 | first = first->next; 32 | second = second->next; 33 | } 34 | return 1; 35 | } 36 | private: 37 | ListNode* reverseList(ListNode* head){ 38 | ListNode* prev = NULL; 39 | while(head){ 40 | ListNode* nextNode = head->next; 41 | head->next = prev; 42 | prev = head; 43 | head = nextNode; 44 | } 45 | return prev; 46 | } 47 | }; 48 | -------------------------------------------------------------------------------- /0237. Delete Node in a Linked List: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | void deleteNode(ListNode* node) { 12 | ListNode* nextNode = node->next; 13 | node->val = nextNode->val; 14 | node->next = nextNode->next; 15 | delete nextNode; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /0242. Valid Anagram: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isAnagram(string s, string t) { 4 | if (s.length() != t.length()) { 5 | return false; 6 | } 7 | int count[26] = {0}; 8 | for (int i = 0; i < s.length(); ++i) { 9 | count[s[i] - 'a']++; 10 | count[t[i] - 'a']--; 11 | } 12 | 13 | for (int i = 0; i < 26; ++i) { 14 | if (count[i] != 0) { 15 | return false; 16 | } 17 | } 18 | 19 | return true; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /0258. Add Digits: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int addDigits(int num) { 4 | return (num - 1) % 9 + 1; 5 | } 6 | }; 7 | -------------------------------------------------------------------------------- /0260. Single Number III: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | vector singleNumber(vector& nums) { 9 | unordered_map mymap; 10 | vector ans; 11 | for (int num : nums) { 12 | mymap[num]++; 13 | } 14 | for (auto& pair : mymap) { 15 | if (pair.second == 1) { 16 | ans.push_back(pair.first); 17 | } 18 | } 19 | 20 | return ans; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /0268. Missing Number: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int missingNumber(vector& nums) { 4 | return (((nums.size()*(nums.size()+1))/2) - accumulate(nums.begin(), nums.end(), 0)); 5 | } 6 | }; 7 | -------------------------------------------------------------------------------- /0287. Find the Duplicate Number: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findDuplicate(vector& nums) { 4 | int slow = nums[0], fast = nums[0]; 5 | do { 6 | slow = nums[slow]; 7 | fast = nums[nums[fast]]; 8 | } while (slow != fast); 9 | slow = nums[0]; 10 | while (slow != fast) { 11 | slow = nums[slow]; 12 | fast = nums[fast]; 13 | } 14 | return slow; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /0295. Find Median from Data Stream: -------------------------------------------------------------------------------- 1 | class MedianFinder { 2 | public: 3 | 4 | priority_queue maxh; 5 | priority_queue, greater> minh; 6 | MedianFinder() { 7 | 8 | } 9 | 10 | void addNum(int num) { 11 | 12 | maxh.push(num); 13 | minh.push(maxh.top()); 14 | maxh.pop(); 15 | 16 | if( minh.size() > maxh.size()) { 17 | maxh.push(minh.top()); 18 | minh.pop(); 19 | } 20 | 21 | } 22 | 23 | double findMedian() { 24 | 25 | if( maxh.size() > minh.size()) return maxh.top(); 26 | return (maxh.top() + minh.top()) / 2.0; 27 | 28 | } 29 | }; 30 | 31 | /** 32 | * Your MedianFinder object will be instantiated and called as such: 33 | * MedianFinder* obj = new MedianFinder(); 34 | * obj->addNum(num); 35 | * double param_2 = obj->findMedian(); 36 | */ 37 | -------------------------------------------------------------------------------- /0326. Power of Three: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPowerOfThree(int n) { 4 | return n > 0 && (1162261467 % n == 0); 5 | } 6 | }; 7 | -------------------------------------------------------------------------------- /0344. Reverse String: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public: 4 | void reverseString(vector& s) { 5 | int left = 0; 6 | int right = s.size() - 1; 7 | 8 | while (left < right) { 9 | char temp = s[left]; 10 | s[left] = s[right]; 11 | s[right] = temp; 12 | left++; 13 | right--; 14 | } 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /0347. Top K Frequent Elements: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector topKFrequent(vector& nums, int k) { 4 | unordered_map freq; 5 | for (int num : nums) { 6 | freq[num]++; 7 | } 8 | 9 | int n = nums.size(); 10 | vector> bucket(n + 1); 11 | 12 | for (auto& [num, count] : freq) { 13 | bucket[count].push_back(num); 14 | } 15 | 16 | vector result; 17 | for (int i = n; i >= 0 && result.size() < k; i--) { 18 | for (int num : bucket[i]) { 19 | result.push_back(num); 20 | if (result.size() == k) return result; 21 | } 22 | } 23 | return result; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /0350. Intersection of Two Arrays II: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector intersect(vector& nums1, vector& nums2) { 4 | vector ans; 5 | sort(nums1.begin(), nums1.end()); 6 | sort(nums2.begin(), nums2.end()); 7 | int n = 0; 8 | int m = 0; 9 | int i = 0; 10 | int j = 0; 11 | n = nums1.size(); 12 | m = nums2.size(); 13 | while (i < n && j < m) { 14 | if (nums1[i] == nums2[j]) { 15 | ans.push_back(nums1[i]); 16 | i++; 17 | j++; 18 | } else if (nums1[i] < nums2[j]) 19 | i++; 20 | else 21 | j++; 22 | } 23 | return ans; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /0387. First Unique Character in a String: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int firstUniqChar(string s) { 4 | vector count(26, 0); 5 | for(char c : s) count[c - 'a']++; 6 | for(int i = 0; i < s.size(); i++) 7 | if(count[s[i] - 'a'] == 1) 8 | return i; 9 | return -1; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /0409. Longest Palindrome: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestPalindrome(string s) { 4 | unordered_map charCount; 5 | for (char c : s) 6 | charCount[c]++; 7 | 8 | int length = 0; 9 | bool oddCountFound = false; 10 | for (const auto& entry : charCount) { 11 | length += entry.second / 2 * 2; 12 | if (entry.second % 2 == 1) 13 | oddCountFound = true; 14 | } 15 | if (oddCountFound) 16 | length++; 17 | return length; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /0430. Flatten a Multilevel Doubly Linked List: -------------------------------------------------------------------------------- 1 | /* 2 | // Definition for a Node. 3 | class Node { 4 | public: 5 | int val; 6 | Node* prev; 7 | Node* next; 8 | Node* child; 9 | }; 10 | */ 11 | 12 | class Solution { 13 | public: 14 | Node* flatten(Node* head) { 15 | Node* temp = head; 16 | while (temp != nullptr) { 17 | if (temp->child) { 18 | Node* next = temp->next; 19 | Node* childH = flatten(temp->child); 20 | temp->next = childH; 21 | childH->prev = temp; 22 | temp->child = nullptr; 23 | 24 | Node* childT = childH; 25 | 26 | while (childT->next != nullptr) { 27 | childT = childT->next; 28 | } 29 | childT->next = next; 30 | 31 | if (next != nullptr) { 32 | next->prev = childT; 33 | } 34 | } 35 | 36 | temp = temp->next; 37 | } 38 | return head; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /0436. Find Right Interval: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findRightInterval(vector>& in) { 4 | int n = in.size(); 5 | vector> v; 6 | 7 | for ( int i = 0 ; i < n ; i++) { 8 | v.push_back({in[i][0], i}); 9 | } 10 | 11 | sort(v.begin(), v.end()); 12 | 13 | vectorans(n, -1); 14 | for ( int i = 0 ; i < n ;i++) { 15 | int e = in[i][1]; 16 | 17 | int l = 0 ; 18 | int r = n - 1; 19 | int index = -1; 20 | 21 | while ( l <= r) { 22 | int mid = (l + r) / 2; 23 | 24 | if( v[mid].first >= e) { 25 | index = v[mid].second; 26 | r = mid - 1; 27 | }else l = mid + 1; 28 | } ans[i] = index; 29 | } 30 | return ans; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /0455. Assign Cookies: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findContentChildren(vector& g, vector& s) { 4 | 5 | sort(g.begin(), g.end()); 6 | sort(s.begin(), s.end()); 7 | 8 | int ans = 0; 9 | int i = 0, j = 0; 10 | 11 | while ( i < g.size() && j < s.size()) { 12 | if( s[j] >= g[i]) { 13 | ans++; 14 | i++; 15 | } 16 | j++; 17 | } 18 | 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /0485. Max Consecutive Ones: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMaxConsecutiveOnes(vector& nums) { 4 | int ans = 0; 5 | int l = 0; 6 | for ( int i = 0 ; i < nums.size(); i++ ) { 7 | if ( nums[i] == 1) { 8 | l++; 9 | } 10 | else { 11 | l = 0; 12 | } 13 | ans = max(l, ans); 14 | } 15 | return ans; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /0496. Next Greater Element I: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector nextGreaterElement(vector& nums1, vector& nums2) { 4 | unordered_map mpp; 5 | stack st; 6 | 7 | for(int i = nums2.size()-1 ; i>=0; i--){ 8 | while(!st.empty() && st.top() <= nums2[i]){ 9 | st.pop(); 10 | } 11 | if(!st.empty()) mpp[nums2[i]] = st.top(); 12 | else mpp[nums2[i]] = -1; 13 | st.push(nums2[i]); 14 | } 15 | vector ans; 16 | for(int num:nums1){ 17 | ans.push_back(mpp[num]); 18 | } 19 | return ans; 20 | } 21 | 22 | }; 23 | -------------------------------------------------------------------------------- /0543. Diameter of Binary Tree: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | private: 14 | int height(TreeNode* root, int &res) { 15 | 16 | if( !root) return 0; 17 | 18 | int l = height(root->left, res); 19 | int r = height(root->right, res); 20 | 21 | res = max(res, l + r); 22 | 23 | return 1 + max(l,r); 24 | 25 | } 26 | public: 27 | int diameterOfBinaryTree(TreeNode* root) { 28 | int res = 0; 29 | height(root, res); 30 | return res; 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /0605. Can Place Flowers: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canPlaceFlowers(vector& flowerbed, int n) { 4 | // If no flowers need to be planted, return true immediately 5 | if (n == 0) return true; 6 | 7 | int count = 0; 8 | int size = flowerbed.size(); 9 | 10 | // Special case for flowerbed size 1 11 | if (size == 1) { 12 | return flowerbed[0] == 0 && n <= 1; 13 | } 14 | 15 | for (int i = 0; i < size; ++i) { 16 | if (flowerbed[i] == 0 && 17 | (i == 0 || flowerbed[i - 1] == 0) && 18 | (i == size - 1 || flowerbed[i + 1] == 0)) { 19 | flowerbed[i] = 1; 20 | count++; 21 | i++; // Skip the next plot as we can't plant adjacent flowers 22 | if (count >= n) return true; 23 | } 24 | } 25 | 26 | return count >= n; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /0633. Sum of Square Numbers: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool judgeSquareSum(int c) { 4 | long left = 0; 5 | long right = static_cast(sqrt(c)); 6 | 7 | while (left <= right) { 8 | long sum = left * left + right * right; 9 | if (sum == c) { 10 | return true; 11 | } else if (sum < c) { 12 | left++; 13 | } else { 14 | right--; 15 | } 16 | } 17 | return false; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /0645. Set Mismatch: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findErrorNums(vector& nums) { 4 | int n = nums.size(); 5 | vector frequency(n + 1, 0); 6 | for (int num : nums) { 7 | frequency[num]++; 8 | } 9 | int duplicate = -1, missing = -1; 10 | for (int i = 1; i <= n; ++i) { 11 | if (frequency[i] == 2) { 12 | duplicate = i; 13 | } else if (frequency[i] == 0) { 14 | missing = i; 15 | } 16 | } 17 | return {duplicate, missing}; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /0703. Kth Largest Element in a Stream: -------------------------------------------------------------------------------- 1 | class KthLargest { 2 | private: 3 | int K; 4 | priority_queue, greater> minHeap; 5 | 6 | public: 7 | KthLargest(int k, vector& nums) { 8 | K = k; 9 | for (int num : nums) { 10 | add(num); 11 | } 12 | } 13 | 14 | int add(int val) { 15 | minHeap.push(val); 16 | if (minHeap.size() > K) { 17 | minHeap.pop(); 18 | } 19 | return minHeap.top(); 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /0704. Binary Search: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int search(vector& nums, int target) { 4 | int first = 0; 5 | int last = nums.size() - 1; 6 | while (first <= last) { 7 | int mid = first + (last - first) / 2; 8 | if (nums[mid] == target) { 9 | return mid; 10 | } 11 | if (nums[mid] < target) { 12 | first = mid + 1; 13 | } else { 14 | last = mid - 1; 15 | } 16 | } 17 | return -1; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /0713. Subarray Product Less Than K: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numSubarrayProductLessThanK(vector& nums, int k) { 4 | if (k <= 1) return 0; 5 | int f = 0, m = 0, count = 0; 6 | int pro = 1; 7 | while (m < nums.size()) { 8 | pro *= nums[m]; 9 | while (pro >= k && f <= m) { 10 | pro /= nums[f++]; 11 | } 12 | count += (m - f + 1); 13 | m++; 14 | } 15 | return count; 16 | } 17 | }; 18 | 19 | -------------------------------------------------------------------------------- /0744. Find Smallest Letter Greater Than Target: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | char nextGreatestLetter(vector& letter, char t) { 4 | int l = 0; 5 | int r = letter.size() - 1; 6 | 7 | while ( l <= r ) { 8 | 9 | int mid = l + ( r - l ) / 2; 10 | 11 | if( letter[mid] <= t) l = mid + 1; 12 | else r = mid - 1; 13 | 14 | } 15 | return letter[l % letter.size()]; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /0763. Partition Labels: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector partitionLabels(string s) { 4 | vector lastI(26, 0); 5 | vector ans; 6 | 7 | for( int i = 0 ; i < s.length(); i++) { 8 | lastI[s[i] - 'a'] = i; 9 | } 10 | 11 | int start = 0; 12 | int end = 0; 13 | for ( int i = 0 ; i < s.length() ; i++) { 14 | end = max(end, lastI[s[i] - 'a']); 15 | if ( i == end) { 16 | ans.push_back(end - start + 1); 17 | start = i + 1; 18 | } 19 | } 20 | return ans; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /0826. Most Profit Assigning Work: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfitAssignment(vector& difficulty, vector& profit, vector& worker) { 4 | vector> jobs; 5 | for (int i = 0; i < difficulty.size(); ++i) { 6 | jobs.emplace_back(difficulty[i], profit[i]); 7 | } 8 | sort(jobs.begin(), jobs.end()); 9 | sort(worker.begin(), worker.end()); 10 | int maxProfit = 0; 11 | int totalProfit = 0; 12 | int j = 0; 13 | for (int i = 0; i < worker.size(); ++i) { 14 | while (j < jobs.size() && worker[i] >= jobs[j].first) { 15 | maxProfit = max(maxProfit, jobs[j].second); 16 | ++j; 17 | } 18 | totalProfit += maxProfit; 19 | } 20 | return totalProfit; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /0846. Hand of Straights: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isNStraightHand(vector& hand, int groupSize) { 4 | if (hand.size() % groupSize != 0) return false; 5 | map count; 6 | for (int card : hand) count[card]++; 7 | 8 | for (auto it = count.begin(); it != count.end(); ++it) { 9 | if (it->second > 0) { 10 | int start = it->first; 11 | int freq = it->second; 12 | for (int i = 0; i < groupSize; ++i) { 13 | if (count[start + i] < freq) return false; 14 | count[start + i] -= freq; 15 | } 16 | } 17 | } 18 | return true; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /0876. Middle of the Linked List: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* middleNode(ListNode* head) { 14 | ListNode* s = head; 15 | ListNode* f = head; 16 | 17 | while( f != nullptr && f->next != nullptr) { 18 | s = s->next; 19 | f = f->next->next; 20 | } 21 | return s; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /0918. Maximum Sum Circular Subarray: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxSubarraySumCircular(vector& nums) { 4 | int tsum = 0; 5 | int tmax = INT_MIN; 6 | int tmin = INT_MAX; 7 | int cmax = 0; 8 | int cmin = 0; 9 | 10 | for ( auto i : nums) { 11 | 12 | tsum += i; 13 | 14 | cmax = max(i, cmax + i); 15 | tmax = max(tmax, cmax); 16 | 17 | cmin = min(i, cmin + i); 18 | tmin = min( cmin, tmin); 19 | cout << tsum << cmax << tmax << cmin << tmin<< endl; 20 | } 21 | return (tmax > 0) ? max(tmax, tsum - tmin) : tmax; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /0945. Minimum Increment to Make Array Unique: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minIncrementForUnique(vector& nums) { 4 | int count = 0; 5 | sort(nums.begin(), nums.end()); 6 | for ( int i = 1 ; i < nums.size() ; i++) 7 | { 8 | if ( nums[i] <= nums[i-1]) { 9 | count += ((nums[i-1]+1) - nums[i]); 10 | nums[i] = nums[i-1] + 1; 11 | } 12 | } 13 | return count; 14 | } 15 | 16 | }; 17 | -------------------------------------------------------------------------------- /0981. Time Based Key-Value Store: -------------------------------------------------------------------------------- 1 | class TimeMap { 2 | public: 3 | unordered_map>> mp; 4 | 5 | TimeMap() {} 6 | 7 | void set(string key, string value, int timestamp) { 8 | mp[key].push_back({timestamp, value}); 9 | } 10 | 11 | string get(string key, int timestamp) { 12 | if (mp.find(key) == mp.end()) 13 | return ""; 14 | 15 | auto& v = mp[key]; 16 | int low = 0, high = v.size() - 1; 17 | string ans = ""; 18 | 19 | while (low <= high) { 20 | int mid = (low + high) / 2; 21 | if (v[mid].first <= timestamp) { 22 | ans = v[mid].second; 23 | low = mid + 1; 24 | } else { 25 | high = mid - 1; 26 | } 27 | } 28 | 29 | return ans; 30 | } 31 | }; 32 | 33 | /** 34 | * Your TimeMap object will be instantiated and called as such: 35 | * TimeMap* obj = new TimeMap(); 36 | * obj->set(key,value,timestamp); 37 | * string param_2 = obj->get(key,timestamp); 38 | */ 39 | -------------------------------------------------------------------------------- /1002. Find Common Characters: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector commonChars(vector& words) { 4 | vector reference_count(26, INT_MAX); 5 | 6 | for (const auto& word : words) { 7 | vector current_count(26, 0); 8 | for (char c : word) { 9 | current_count[c - 'a']++; 10 | } 11 | for (int j = 0; j < 26; j++) { 12 | reference_count[j] = min(reference_count[j], current_count[j]); 13 | } 14 | } 15 | 16 | vector result; 17 | for (int i = 0; i < 26; i++) { 18 | while (reference_count[i]-- > 0) { 19 | result.push_back(string(1, i + 'a')); 20 | } 21 | } 22 | 23 | return result; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /1028. Recover a Tree From Preorder Traversal: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), 10 | * right(right) {} 11 | * }; 12 | */ 13 | class Solution { 14 | public: 15 | TreeNode* recoverFromPreorder(string t) { 16 | 17 | stack s; 18 | int i = 0; 19 | 20 | while (i < t.length()) { 21 | 22 | int d = 0; 23 | while (i < t.length() && t[i] == '-') { 24 | i++; 25 | d++; 26 | } 27 | 28 | int v = 0; 29 | 30 | while (i < t.length() && isdigit(t[i])) { 31 | v = v * 10 + (t[i] - '0'); 32 | i++; 33 | } 34 | 35 | TreeNode* temp = new TreeNode(v); 36 | 37 | while (s.size() > d) { 38 | s.pop(); 39 | } 40 | 41 | if (!s.empty()) { 42 | if (s.top()->left == nullptr) 43 | s.top()->left = temp; 44 | else 45 | s.top()->right = temp; 46 | } 47 | 48 | s.push(temp); 49 | } 50 | 51 | while (s.size() > 1) 52 | s.pop(); 53 | 54 | return s.top(); 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /1128. Number of Equivalent Domino Pairs: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numEquivDominoPairs(vector>& dominoes) { 4 | map, int> mpp; 5 | 6 | int c = 0 ; 7 | 8 | for ( auto &d : dominoes) { 9 | if( d[0] > d[1]) swap(d[0], d[1]); 10 | c += mpp[make_pair(d[0], d[1])]++; 11 | } 12 | 13 | return c; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /1295. Find Numbers with Even Number of Digits: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findNumbers(vector& nums) { 4 | int ans = 0; 5 | int c = 0; 6 | for ( auto i : nums) { 7 | c = 0; 8 | while(i){ 9 | i/=10; 10 | c++; 11 | } 12 | if(c%2 ==0) { 13 | ans++; 14 | } 15 | } 16 | return ans; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /1304. Find N Unique Integers Sum up to Zero: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector sumZero(int n) { 4 | vector ans; 5 | for( int i = -n/2 ; i <= n/2 ; i++){ 6 | if( n% 2 == 0 && i == 0) { 7 | continue; 8 | } 9 | else { 10 | ans.push_back(i); 11 | } 12 | }return ans; 13 | } 14 | 15 | }; 16 | -------------------------------------------------------------------------------- /1305. All Elements in Two Binary Search Trees: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), 10 | * right(right) {} 11 | * }; 12 | */ 13 | class Solution { 14 | public: 15 | void inOrderTraversal(TreeNode* root, vector& result) { 16 | if (root == nullptr) 17 | return; 18 | inOrderTraversal(root->left, result); 19 | result.push_back(root->val); 20 | inOrderTraversal(root->right, result); 21 | } 22 | vector getAllElements(TreeNode* root1, TreeNode* root2) { 23 | vector list1; 24 | inOrderTraversal(root1, list1); 25 | inOrderTraversal(root2, list1); 26 | sort(list1.begin(), list1.end()); 27 | return list1; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /1317. Convert Integer to the Sum of Two No-Zero Integers: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | std::vector getNoZeroIntegers(int n) { 4 | for(int i = 1; i <= n - 1; i++) { 5 | int j = n - i; 6 | if(nozero(i) && nozero(j)) { 7 | return {i, j}; 8 | } 9 | } 10 | return {}; 11 | } 12 | 13 | private: 14 | bool nozero(int a) { 15 | while(a) { 16 | if(a % 10 == 0) 17 | return false; 18 | a /= 10; 19 | } 20 | return true; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /1351. Count Negative Numbers in a Sorted Matrix: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countNegatives(vector>& grid) { 4 | int m = grid.size(); 5 | int c = 0; 6 | for ( int i = 0 ; i < m ; i++) { 7 | 8 | int l = 0; 9 | int r = grid[i].size() - 1; 10 | 11 | while ( l <= r ) { 12 | int mid = l + ( r - l) / 2; 13 | 14 | if( grid[i][mid] < 0) r = mid - 1; 15 | else l = mid + 1; 16 | } 17 | c += (grid[i].size() - r - 1); 18 | 19 | } 20 | return c; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /1352. Product of the Last K Numbers: -------------------------------------------------------------------------------- 1 | class ProductOfNumbers { 2 | 3 | vector v; 4 | int n = 0; 5 | 6 | public: 7 | ProductOfNumbers() { 8 | v.push_back(1); 9 | n = 0; 10 | } 11 | 12 | void add(int num) { 13 | if (num == 0) { 14 | v = {1}; 15 | n = 0; 16 | } else { 17 | v.push_back(v[n] * num); 18 | n++; 19 | } 20 | } 21 | 22 | int getProduct(int k) { 23 | if (k > n) 24 | return 0; 25 | return v[n]/v[n - k]; 26 | } 27 | }; 28 | 29 | /** 30 | * Your ProductOfNumbers object will be instantiated and called as such: 31 | * ProductOfNumbers* obj = new ProductOfNumbers(); 32 | * obj->add(num); 33 | * int param_2 = obj->getProduct(k); 34 | */ 35 | -------------------------------------------------------------------------------- /1358. Number of Substrings Containing All Three Characters: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numberOfSubstrings(string s) { 4 | int len = s.length(); 5 | // Track last position of a, b, c 6 | vector lastPos = {-1, -1, -1}; 7 | int total = 0; 8 | 9 | for (int pos = 0; pos < len; pos++) { 10 | // Update last position of current character 11 | lastPos[s[pos] - 'a'] = pos; 12 | 13 | // Add count of valid substrings ending at current position 14 | // If any character is missing, min will be -1 15 | // Else min gives leftmost required character position 16 | total += 1 + min({lastPos[0], lastPos[1], lastPos[2]}); 17 | } 18 | 19 | return total; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /1402. Reducing Dishes: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxSatisfaction(vector& satisfaction) { 4 | sort(satisfaction.begin(), satisfaction.end(), greater()); 5 | int total = 0, current_sum = 0; 6 | for (int s : satisfaction) { 7 | current_sum += s; 8 | if (current_sum > 0) { 9 | total += current_sum; 10 | } else { 11 | break; 12 | } 13 | } 14 | return total; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /1480. Running Sum of 1d Array: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector runningSum(vector& nums) { 4 | if( nums.size() == 1) return nums; 5 | for ( int i = 1 ; i < nums.size() ; i++){ 6 | nums[i] += nums[i-1]; 7 | } 8 | return nums; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /1493. Longest Subarray of 1's After Deleting One Element: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestSubarray(vector& nums) { 4 | int max_length = 0; 5 | int current_length = 0; 6 | int zero_count = 0; 7 | for (int i = 0, j = 0; j < nums.size(); ++j) { 8 | if (nums[j] == 0) { 9 | ++zero_count; 10 | } 11 | while (zero_count > 1) { 12 | if (nums[i] == 0) { 13 | --zero_count; 14 | } 15 | ++i; 16 | } 17 | max_length = max(max_length, j - i); 18 | } 19 | return max_length; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /1509. Minimum Difference Between Largest and Smallest Value in Three Moves: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minDifference(vector& nums) { 4 | if (nums.size() <= 4) return 0; 5 | sort(nums.begin(), nums.end()); 6 | return min({ 7 | nums[nums.size()-1] - nums[3], 8 | nums[nums.size()-2] - nums[2], 9 | nums[nums.size()-3] - nums[1], 10 | nums[nums.size()-4] - nums[0] 11 | }); 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /1512. Number of Good Pairs: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numIdenticalPairs(vector& nums) { 4 | int l = 0; 5 | int m = 1; 6 | int ans = 0; 7 | while (l < nums.size() && m < nums.size()) { 8 | if (nums[l] == nums[m]) { 9 | ans++; 10 | cout << l << m << endl; 11 | } 12 | 13 | if (m == nums.size() - 1) { 14 | l++; 15 | m = l; 16 | } 17 | m++; 18 | } 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /1518. Water Bottles: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numWaterBottles(int numBottles, int numExchange) { 4 | int ans = numBottles; 5 | int a = 0; 6 | int b = 0; 7 | while(numBottles >= numExchange){ 8 | a = numBottles / numExchange; 9 | b = numBottles % numExchange; 10 | ans += a; 11 | numBottles = a+b; 12 | } 13 | return ans; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /1550. Three Consecutive Odds: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool threeConsecutiveOdds(vector& arr) { 4 | int i = 0, count = 0; 5 | while (i < arr.size()) { 6 | if (arr[i] % 2 != 0) { 7 | count++; 8 | } else { 9 | count = 0; 10 | } 11 | if (count == 3) { 12 | return true; 13 | } 14 | i++; 15 | } 16 | return false; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /1614. Maximum Nesting Depth of the Parentheses: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxDepth(string s) { 4 | int current_depth = 0; 5 | int max_depth = 0; 6 | for (char c : s) { 7 | if (c == '(') { 8 | current_depth++; 9 | if (current_depth > max_depth) { 10 | max_depth = current_depth; 11 | } 12 | } else if (c == ')') { 13 | current_depth--; 14 | } 15 | } 16 | return max_depth; 17 | } 18 | }; 19 | 20 | -------------------------------------------------------------------------------- /1689. Partitioning Into Minimum Number Of Deci-Binary Numbers: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minPartitions(string n) { 4 | char ans = '0'; 5 | for(char c : n){ 6 | if(c > ans){ 7 | ans = c; 8 | } 9 | } 10 | return ans -'0'; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /1749. Maximum Absolute Sum of Any Subarray: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxAbsoluteSum(vector& nums) { 4 | int maxSum = 0, minSum = 0; 5 | int currentMax = 0, currentMin = 0; 6 | 7 | for (int num : nums) { 8 | currentMax = max(num, currentMax + num); 9 | maxSum = max(maxSum, currentMax); 10 | 11 | currentMin = min(num, currentMin + num); 12 | minSum = min(minSum, currentMin); 13 | } 14 | 15 | return max(maxSum, abs(minSum)); 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /1769. Minimum Number of Operations to Move All Balls to Each Box: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector minOperations(string boxes) { 4 | int n = boxes.size(); 5 | vector answer(n, 0); 6 | int count = 0, operations = 0; 7 | for (int i = 0; i < n; ++i) { 8 | answer[i] = operations; 9 | if (boxes[i] == '1') { 10 | ++count; 11 | } 12 | operations += count; 13 | } 14 | count = 0, operations = 0; 15 | for (int i = n - 1; i >= 0; --i) { 16 | answer[i] += operations; 17 | if (boxes[i] == '1') { 18 | ++count; 19 | } 20 | operations += count; 21 | } 22 | 23 | return answer; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /1780. Check if Number is a Sum of Powers of Three: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkPowersOfThree(int n) 4 | { 5 | return checkPowersOfThreeHelper(0, n); 6 | } 7 | 8 | private: 9 | bool checkPowersOfThreeHelper(int power, int n) { 10 | if (n == 0) 11 | return true; 12 | 13 | if (pow(3, power) > n) 14 | return false; 15 | 16 | bool addPower = checkPowersOfThreeHelper(power + 1, n - pow(3, power)); 17 | 18 | bool skipPower = checkPowersOfThreeHelper(power + 1, n); 19 | 20 | return addPower || skipPower; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /1790. Check if One String Swap Can Make Strings Equal: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool areAlmostEqual(string s1, string s2) { 4 | 5 | int x =-1; 6 | 7 | for ( int i = 0 ; i < s1.length() ; i++) { 8 | 9 | if( s1[i] != s2[i]) { 10 | if( x ==-1) { 11 | x = i; 12 | } 13 | else { 14 | swap( s1[i], s1[x]); 15 | return s1 == s2; 16 | } 17 | } 18 | 19 | } 20 | return s1 == s2; 21 | 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /1791. Find Center of Star Graph: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findCenter(vector>& edges) { 4 | int a = edges[0][0]; 5 | int b = edges[0][1]; 6 | if (a == edges[1][0] || a == edges[1][1]) { 7 | return a; 8 | } else { 9 | return b; 10 | } 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /1833. Maximum Ice Cream Bars: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxIceCream(vector& costs, int coins) { 4 | int n = 0 ; 5 | int p = 0 ; 6 | sort( costs.begin() , costs.end()); 7 | for ( int i = 0 ; i < costs.size() ; i++){ 8 | if(p + costs[i] <= coins){ 9 | p += costs[i]; 10 | n++; 11 | } 12 | else break; 13 | } 14 | return n; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /1848. Minimum Distance to the Target Element: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int getMinDistance(vector& nums, int target, int start) { 4 | int min = nums.size(); 5 | for (int i = 0; i < nums.size(); i++) { 6 | if (nums[i] == target) { 7 | int d = abs(i - start); 8 | if (d < min) { 9 | min = d; 10 | } 11 | } 12 | } 13 | return min; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /1909. Remove One Element to Make the Array Strictly Increasing: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canBeIncreasing(vector& nums) { 4 | int count = 0; 5 | 6 | for (int i = 1; i < nums.size(); ++i) { 7 | if (nums[i] <= nums[i - 1]) { 8 | count++; 9 | if (count > 1) return false; 10 | 11 | if (i > 1 && nums[i] <= nums[i - 2]) nums[i] = nums[i - 1]; 12 | } 13 | } 14 | 15 | return true; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /1910. Remove All Occurrences of a Substring: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string removeOccurrences(string s, string part) { 4 | string ans = ""; 5 | int n = part.length(); 6 | int t = part.back(); 7 | for ( auto i : s) { 8 | ans.push_back(i); 9 | if(i == t && ans.length() >= n) { 10 | if( ans.substr(ans.length() - n) == part) { 11 | ans.erase(ans.length() - n); 12 | } 13 | } 14 | 15 | } 16 | return ans; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /1920. Build Array from Permutation: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector buildArray(vector& nums) { 4 | vector ans; 5 | for ( int i = 0 ; i < nums.size() ; i++){ 6 | ans.push_back(nums[nums[i]]); 7 | } 8 | return ans; 9 | } 10 | 11 | }; 12 | -------------------------------------------------------------------------------- /1929. Concatenation of Array: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector getConcatenation(vector& nums) { 4 | int n = nums.size(); 5 | for ( int i = 0 ; i < n ; i++){ 6 | int ele = nums[i]; 7 | nums.push_back(ele); 8 | } 9 | return nums; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /2017. Grid Game: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long gridGame(vector>& grid) { 4 | 5 | int n = grid[0].size(); 6 | 7 | long long totalTop = 0, totalBottom = 0; 8 | 9 | for (int i = 0; i < n; i++) { 10 | totalTop += grid[0][i]; 11 | } 12 | 13 | long long result = LLONG_MAX; 14 | 15 | for (int i = 0; i < n; i++) { 16 | 17 | totalTop -= grid[0][i]; 18 | result = min(result, max(totalTop, totalBottom)); 19 | totalBottom += grid[1][i]; 20 | } 21 | 22 | return result; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /2037. Minimum Number of Moves to Seat Everyone: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minMovesToSeat(vector& seats, vector& students) { 4 | sort(seats.begin(), seats.end()); 5 | sort(students.begin(), students.end()); 6 | int moves = 0; 7 | for (int i = 0 ; i < seats.size(); i++) 8 | { 9 | moves = moves + abs(seats[i] - students[i]); 10 | } 11 | return moves; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /2144. Minimum Cost of Buying Candies With Discount: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimumCost(vector& cost) { 4 | int ans = 0; 5 | int c = 0; 6 | int i = 0; 7 | sort(cost.begin(), cost.end(), greater()); 8 | for (i = 0 ; i < cost.size() ;i++) { 9 | if(c == 0 || c == 1) { 10 | c++; 11 | ans += cost[i]; 12 | } 13 | else { 14 | c=0; 15 | } 16 | } 17 | return ans; 18 | 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /2161. Partition Array According to Given Pivot: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector pivotArray(vector& nums, int pivot) { 4 | vector less, greater; 5 | int c = 0; 6 | for (int num : nums) { 7 | if (num < pivot) less.push_back(num); 8 | else if (num == pivot) c++; 9 | else greater.push_back(num); 10 | } 11 | while(c){ 12 | less.push_back(pivot); 13 | c--; 14 | } 15 | less.insert(less.end(), greater.begin(), greater.end()); 16 | 17 | return less; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /2181. Merge Nodes in Between Zeros: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* mergeNodes(ListNode* head) { 14 | ListNode* dummy = new ListNode(0); 15 | ListNode* pos = dummy; 16 | ListNode* temp = head->next; 17 | int sum = 0; 18 | 19 | while (temp) { 20 | if (temp->val == 0) { 21 | pos->next = new ListNode(sum); 22 | pos = pos->next; 23 | sum = 0; 24 | } else { 25 | sum += temp->val; 26 | } 27 | temp = temp->next; 28 | } 29 | return dummy->next; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /2221. Find Triangular Sum of an Array: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int triangularSum(vector& nums) { 4 | while (nums.size() > 1) { 5 | for (size_t i = 0; i < nums.size() - 1; ++i) { 6 | nums[i] = (nums[i] + nums[i + 1]) % 10; 7 | } 8 | nums.pop_back(); 9 | } 10 | return nums[0]; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /2226. Maximum Candies Allocated to K Children: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canAllocate(vector& candies, long long k, int mid) { 4 | if (mid == 0) return false; // Avoid division by zero 5 | 6 | long long count = 0; 7 | for (int c : candies) { 8 | count += c / mid; // Count how many children can get `mid` candies 9 | if (count >= k) return true; 10 | } 11 | return false; 12 | } 13 | 14 | int maximumCandies(vector& candies, long long k) { 15 | long long total = accumulate(candies.begin(), candies.end(), 0LL); 16 | if (total < k) return 0; // Not enough candies for k children 17 | 18 | int left = 1, right = *max_element(candies.begin(), candies.end()), ans = 0; 19 | 20 | while (left <= right) { 21 | int mid = left + (right - left) / 2; 22 | if (canAllocate(candies, k, mid)) { 23 | ans = mid; // Try to maximize `mid` 24 | left = mid + 1; 25 | } else { 26 | right = mid - 1; 27 | } 28 | } 29 | return ans; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /2239. Find Closest Number to Zero: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findClosestNumber(vector& nums) { 4 | int diff = INT_MAX; 5 | int ans = 0; 6 | 7 | for ( int i = 0 ; i < nums.size() ;i++) { 8 | if( abs(nums[i] - 0) < diff) { 9 | diff = abs(nums[i] - 0); 10 | ans = nums[i]; 11 | } 12 | else if( abs(nums[i] - 0) == diff) { 13 | ans = max(ans, nums[i]); 14 | } 15 | } 16 | return ans; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /2259. Remove Digit From Number to Maximize Result: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string removeDigit(string number, char digit) { 4 | string max = ""; 5 | for (int i = 0; i < number.size(); ++i) { 6 | if (number[i] == digit) { 7 | string newnum = number.substr(0, i) + number.substr(i + 1); 8 | if (newnum > max) { 9 | max = newnum; 10 | } 11 | } 12 | } 13 | return max; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /2342. Max Sum of a Pair With Equal Sum of Digits: -------------------------------------------------------------------------------- 1 | class Solution { 2 | 3 | private: 4 | int csum(int n) { 5 | int sum = 0; 6 | while ( n > 0) { 7 | sum += n % 10; 8 | n /= 10; 9 | } 10 | return sum; 11 | } 12 | public: 13 | int maximumSum(vector& nums) { 14 | 15 | vector> dsump; 16 | 17 | for ( int n : nums) { 18 | int dsum = csum(n); 19 | dsump.push_back({dsum, n}); 20 | } 21 | 22 | sort(dsump.begin(), dsump.end()); 23 | 24 | int maxp = -1; 25 | 26 | for ( int i = 1 ; i < dsump.size() ; i++) { 27 | int currsum = dsump[i].first; 28 | int presum = dsump[i-1].first; 29 | 30 | if ( currsum == presum) { 31 | int tsum = dsump[i].second + dsump[i-1].second; 32 | maxp = max(maxp, tsum); 33 | } 34 | } 35 | 36 | return maxp; 37 | 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /2364. Count Number of Bad Pairs: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long countBadPairs(vector& nums) { 4 | 5 | long long n = nums.size(); 6 | long long tp = (n * (n - 1)) / 2; 7 | long long gp = 0; 8 | unordered_mapc; 9 | 10 | for ( int i = 0 ; i < n ; i++) { 11 | int diff = nums[i] - i; 12 | gp += c[diff]; 13 | c[diff]++; 14 | } 15 | 16 | return tp - gp; 17 | 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /2379. Minimum Recolors to Get K Consecutive Black Blocks: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public: 4 | int minimumRecolors(string b, int k) { 5 | int l = 0, minw = 0, ans = INT_MAX; 6 | for (int r = 0; r < b.size(); r++) { 7 | if (b[r] == 'W') 8 | minw++; 9 | if (r - l + 1 == k) { 10 | ans = min(ans, minw); 11 | if (b[l] == 'W') 12 | minw--; 13 | l++; 14 | } 15 | } 16 | return ans; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /2391. Minimum Amount of Time to Collect Garbage: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int garbageCollection(vector& garbage, vector& travel) { 4 | int ans = 0; 5 | int lastM = 0, lastP = 0, lastG = 0; 6 | 7 | for (int i = 0; i < garbage.size(); i++) { 8 | for (char c : garbage[i]) { 9 | ans++; 10 | if (c == 'M') lastM = i; 11 | if (c == 'P') lastP = i; 12 | if (c == 'G') lastG = i; 13 | } 14 | } 15 | 16 | for (int i = 1; i < garbage.size(); i++) { 17 | if (i <= lastM) ans += travel[i - 1]; 18 | if (i <= lastP) ans += travel[i - 1]; 19 | if (i <= lastG) ans += travel[i - 1]; 20 | } 21 | 22 | return ans; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /2441. Largest Positive Integer That Exists With Its Negative: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMaxK(vector& nums) { 4 | sort(nums.begin(), nums.end()); 5 | int l = 0; 6 | int r = nums.size() - 1; 7 | while (l < r) { 8 | if (nums[l] == nums[r]*(-1)) { 9 | return nums[r]; 10 | } 11 | if (abs(nums[l]) > nums[r]) { 12 | l++; 13 | } else { 14 | r--; 15 | } 16 | } 17 | return -1; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /2460. Apply Operations to an Array: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector applyOperations(vector& nums) { 4 | int index = 0; 5 | 6 | for ( int i = 0 ; i < nums.size() ; i++) { 7 | 8 | if(i < nums.size() - 1 && nums[i] == nums[i+1]) { 9 | nums[i] *= 2; 10 | nums[i+1] = 0; 11 | } 12 | 13 | if(nums[i] != 0){ 14 | swap(nums[i], nums[index]); 15 | index++; 16 | } 17 | 18 | } 19 | return nums; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /2486. Append Characters to String to Make Subsequence: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int appendCharacters(string s, string t) { 4 | int i = 0; 5 | int j = 0; 6 | while (i < s.length() && j < t.length()) { 7 | if (s[i] == t[j]) { 8 | j++; 9 | } 10 | i++; 11 | } 12 | return t.length() - j; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /2523. Closest Prime Numbers in Range: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector closestPrimes(int l, int r) { 4 | vector isP(r + 1, 1); 5 | isP[0] = isP[1] = 0; 6 | 7 | for (int i = 2; i * i <= r; i++) { 8 | if (isP[i]) { 9 | for (int j = i * i; j <= r; j += i) { 10 | isP[j] = 0; 11 | } 12 | } 13 | } 14 | 15 | vector P; 16 | for (int i = l; i <= r; i++) { 17 | if (isP[i]) P.push_back(i); 18 | } 19 | 20 | vector ans(2, -1); 21 | int mind = INT_MAX; 22 | for (int i = 1; i < P.size(); i++) { 23 | int d = P[i] - P[i - 1]; 24 | if (d < mind) { 25 | mind = d; 26 | ans = {P[i - 1], P[i]}; 27 | } 28 | } 29 | return ans; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /2529. Maximum Count of Positive Integer and Negative Integer: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maximumCount(vector& nums) { 4 | int n = 0; 5 | int p = 0; 6 | for ( auto i : nums) { 7 | if( i > 0) p++; 8 | else if( i < 0) n++; 9 | 10 | } 11 | return max(n, p); 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /2540. Minimum Common Value: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int getCommon(vector& nums1, vector& nums2) { 4 | int i = 0, j = 0; 5 | while (i < nums1.size() && j < nums2.size()) { 6 | if (nums1[i] == nums2[j]) { 7 | return nums1[i]; 8 | } else if (nums1[i] < nums2[j]) { 9 | i++; 10 | } else { 11 | j++; 12 | } 13 | } 14 | return -1; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /2545. Sort the Students by Their Kth Score: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> sortTheStudents(vector>& score, int k) { 4 | sort(score.begin(), score.end(), 5 | [k](const vector& a, const vector& b) { 6 | return a[k] > b[k]; 7 | }); 8 | return score; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /2570. Merge Two 2D Arrays by Summing Values: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> mergeArrays(vector>& nums1, vector>& nums2) { 4 | 5 | int i = 0 ; 6 | int j = 0 ; 7 | int n = nums1.size(); 8 | int m = nums2.size(); 9 | vector> ans; 10 | 11 | while ( i < n && j < m) { 12 | 13 | if( nums1[i][0] == nums2[j][0] ) { 14 | int p = nums1[i][1] + nums2[j][1]; 15 | ans.push_back({nums1[i][0],p}); 16 | i++; 17 | j++; 18 | } 19 | else if( nums1[i][0] < nums2[j][0]){ 20 | ans.push_back({nums1[i]}); 21 | i++; 22 | } 23 | 24 | else { 25 | ans.push_back({nums2[j]}); 26 | j++; 27 | } 28 | 29 | 30 | } 31 | 32 | while ( i < n) { 33 | ans.push_back({nums1[i]}); 34 | i++; 35 | } 36 | while ( j < m) { 37 | ans.push_back({nums2[j]}); 38 | j++; 39 | } 40 | 41 | 42 | return ans; 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /2579. Count Total Number of Colored Cells: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long coloredCells(int n) { 4 | return 1 + (long long)n * (n - 1) * 2; 5 | 6 | } 7 | }; 8 | -------------------------------------------------------------------------------- /2582. Pass the Pillow: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int passThePillow(int n, int time) { 4 | int ans = time / (n - 1); 5 | return ans % 2 == 0 ? (time % (n - 1) + 1) : (n - time % (n - 1)); 6 | } 7 | }; 8 | -------------------------------------------------------------------------------- /2591. Distribute Money to Maximum Children: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int distMoney(int m, int c) { 4 | m -= c; 5 | if(m < 0) return -1; 6 | if( m / 7 == c && m % 7 == 0) return c; 7 | if (m / 7 == c - 1 && m % 7 == 3 ) return c - 2; 8 | return min( m/7 , c - 1); 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /2661. First Completely Painted Row or Column: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int firstCompleteIndex(vector& arr, vector>& mat) { 4 | int m = mat.size(); 5 | int n = mat[0].size(); 6 | unordered_map rowSum; 7 | unordered_map colSum; 8 | unordered_map> valueToCoords; 9 | for (int i = 0; i < m; ++i) { 10 | for (int j = 0; j < n; ++j) { 11 | valueToCoords[mat[i][j]] = {i, j}; 12 | } 13 | } 14 | for (int k = 0; k < arr.size(); ++k) { 15 | auto [row, col] = valueToCoords[arr[k]]; 16 | rowSum[row]++; 17 | colSum[col]++; 18 | if (rowSum[row] == n || colSum[col] == m) { 19 | return k; 20 | } 21 | } 22 | 23 | return -1; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /2698. Find the Punishment Number of an Integer: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool findPartitions(int startIndex, int sum, string stringNum, int target, 4 | vector>& memo) { 5 | 6 | if (startIndex == stringNum.size()) { 7 | return sum == target; 8 | } 9 | 10 | if (sum > target) return false; 11 | 12 | if (memo[startIndex][sum] != -1) return memo[startIndex][sum]; 13 | 14 | bool partitionFound = false; 15 | 16 | for (int currentIndex = startIndex; currentIndex < stringNum.size(); 17 | currentIndex++) { 18 | string currentString = 19 | stringNum.substr(startIndex, currentIndex - startIndex + 1); 20 | int addend = stoi(currentString); 21 | 22 | partitionFound = 23 | partitionFound || findPartitions(currentIndex + 1, sum + addend, 24 | stringNum, target, memo); 25 | if (partitionFound == true) return true; 26 | } 27 | 28 | return memo[startIndex][sum] = partitionFound; 29 | } 30 | 31 | int punishmentNumber(int n) { 32 | int punishmentNum = 0; 33 | 34 | for (int currentNum = 1; currentNum <= n; currentNum++) { 35 | int squareNum = currentNum * currentNum; 36 | string stringNum = to_string(squareNum); 37 | 38 | vector> memoArray(stringNum.size(), 39 | vector(currentNum + 1, -1)); 40 | 41 | if (findPartitions(0, 0, stringNum, currentNum, memoArray)) { 42 | punishmentNum += squareNum; 43 | } 44 | } 45 | return punishmentNum; 46 | } 47 | }; 48 | -------------------------------------------------------------------------------- /2703. Return Length of Arguments Passed: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {...(null|boolean|number|string|Array|Object)} args 3 | * @return {number} 4 | */ 5 | var argumentsLength = function(...args) { 6 | return args.length; 7 | }; 8 | 9 | /** 10 | * argumentsLength(1, 2, 3); // 3 11 | */ 12 | -------------------------------------------------------------------------------- /2769. Find the Maximum Achievable Number: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int theMaximumAchievableX(int num, int t) { 4 | return num + (t*2); 5 | } 6 | }; 7 | -------------------------------------------------------------------------------- /2807. Insert Greatest Common Divisors in Linked List: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* insertGreatestCommonDivisors(ListNode* head) { 14 | ListNode* temp = head; 15 | while (temp->next) { 16 | int one = temp->val; 17 | int two = temp->next->val; 18 | ListNode* curr = new ListNode(gcd(one, two)); 19 | curr->next = temp->next; 20 | temp->next = curr; 21 | temp = temp->next->next; 22 | } 23 | return head; 24 | } 25 | 26 | private: 27 | int gcd(int a, int b) { 28 | while (b != 0) { 29 | int temp = b; 30 | b = a % b; 31 | a = temp; 32 | } 33 | return a; 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /2810. Faulty Keyboard: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string finalString(string s) { 4 | string curr; 5 | for (char c : s) { 6 | if (c == 'i') { 7 | curr = reverseString(curr); 8 | } else { 9 | curr += c; 10 | } 11 | } 12 | return curr; 13 | } 14 | 15 | private: 16 | string reverseString(string temp) { 17 | string rev; 18 | for (int i = temp.size() - 1; i >= 0; --i) { 19 | rev += temp[i]; 20 | } 21 | return rev; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /2816. Double a Number Represented as a Linked List: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* reverse(ListNode* head) { 14 | ListNode* curr = head; 15 | ListNode* prev = NULL; 16 | ListNode* next; 17 | while (curr != NULL) { 18 | next = curr->next; 19 | curr->next = prev; 20 | prev = curr; 21 | curr = next; 22 | } 23 | return prev; 24 | } 25 | ListNode* doubleIt(ListNode* head) { 26 | ListNode* head1 = reverse(head); 27 | int carry = 0; 28 | ListNode* curr = head1; 29 | ListNode* dummy = new ListNode(-1); 30 | ListNode* tail = dummy; 31 | while (curr != NULL) { 32 | int val = 2 * (curr->val) + carry; 33 | int digit = (val) % 10; 34 | carry = val / 10; 35 | ListNode* temp = new ListNode(digit); 36 | tail->next = temp; 37 | tail = tail->next; 38 | curr = curr->next; 39 | } 40 | if (carry > 0) { 41 | tail->next = new ListNode(carry); 42 | tail = tail->next; 43 | } 44 | dummy = dummy->next; 45 | ListNode* ans_head = reverse(dummy); 46 | return ans_head; 47 | } 48 | }; 49 | -------------------------------------------------------------------------------- /2824. Count Pairs Whose Sum is Less than Target: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countPairs(vector& nums, int target) { 4 | int temp = 0; 5 | int i = temp + 1; 6 | int count = 0; 7 | while (temp < nums.size() && i < nums.size()) { 8 | if (nums[temp] + nums[i] < target) { 9 | count++; 10 | } 11 | i++; 12 | if( i == nums.size()) { 13 | temp++; 14 | i = temp+1; 15 | } 16 | } 17 | return count; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /2856. Minimum Array Length After Pair Removals: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minLengthAfterRemovals(vector& nums) { 4 | int n = nums.size(); 5 | int ans = nums.size(); 6 | int l = 0; 7 | int r = (n + 1)/2; 8 | while ( l < n/2 && r < n) { 9 | if ( nums[l] < nums[r]) 10 | ans -= 2; 11 | l++; 12 | r++; 13 | } 14 | return ans; 15 | } 16 | 17 | }; 18 | -------------------------------------------------------------------------------- /2894. Divisible and Non-divisible Sums Difference: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int differenceOfSums(int n, int m) { 4 | int num1 = 0; 5 | int num2 = 0; 6 | for (int i = 1; i <= n; i++) { 7 | if (i % m == 0) { 8 | num2 += i; 9 | } 10 | else num1 += i; 11 | } 12 | return num1 - num2; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /2895. Minimum Processing Time: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minProcessingTime(vector& processorTime, vector& tasks) { 4 | sort(tasks.begin(), tasks.end()); 5 | sort(processorTime.begin(), processorTime.end()); 6 | reverse(processorTime.begin(), processorTime.end()); 7 | int j = 3; 8 | int cmax =0; 9 | int max =0; 10 | for (int i = 0; i < processorTime.size(); i++) { 11 | cmax += (processorTime[i] + tasks[j]); 12 | j+=4; 13 | if(cmax > max) 14 | max = cmax; 15 | cmax = 0; 16 | } 17 | return max; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /2900. Longest Unequal Adjacent Groups Subsequence I: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector getLongestSubsequence(vector& words, vector& groups) { 4 | vector ans; 5 | int n = groups.size(); 6 | if (n == 0) return ans; 7 | ans.push_back(words[0]); 8 | int ls = groups[0]; 9 | for (int i = 1; i < n; ++i) { 10 | if (groups[i] != ls) { 11 | ans.push_back(words[i]); 12 | ls = groups[i]; 13 | } 14 | } 15 | return ans; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /2965. Find Missing and Repeated Values: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findMissingAndRepeatedValues(vector>& g) { 4 | 5 | long long n = g.size(); 6 | long long N = 1ll * n * n; 7 | 8 | long long Sn = (N * (N + 1)) / 2; 9 | long long S2n = (N * (N + 1) * (2 * N + 1) ) / 6; 10 | 11 | long long S = 0; 12 | long long S2 = 0; 13 | 14 | for ( int i = 0; i < n ; i++) { 15 | for ( int j = 0 ; j < n ; j++) { 16 | S += 1LL * g[i][j]; 17 | S2 += 1LL * g[i][j] * g[i][j]; 18 | } 19 | } 20 | 21 | 22 | long long a_minus_b = S - Sn; 23 | long long a_plus_b = (S2 - S2n) / a_minus_b; 24 | 25 | int a = (a_plus_b + a_minus_b) / 2; 26 | int b = (a_plus_b - a_minus_b) / 2; 27 | vectorans = {a,b}; 28 | 29 | return ans; 30 | 31 | 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /3042. Count Prefix and Suffix Pairs I: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countPrefixSuffixPairs(vector& words) { 4 | int n = words.size(); 5 | int count = 0; 6 | 7 | for (int i = 0; i < n; i++) { 8 | for (int j = i + 1; j < n; j++) { 9 | string& str1 = words[i]; 10 | string& str2 = words[j]; 11 | 12 | if (str1.size() > str2.size()) 13 | continue; 14 | 15 | if (str2.substr(0, str1.size()) == str1 && 16 | str2.substr(str2.size() - str1.size()) == str1) { 17 | count++; 18 | } 19 | } 20 | } 21 | return count ; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /3066. Minimum Operations to Exceed Threshold Value II: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minOperations(vector& nums, int k) { 4 | 5 | int c = 0; 6 | priority_queue, greater> h; 7 | 8 | for ( auto i : nums) 9 | h.push(i); 10 | while ( h.top() < k) { 11 | long long int f = h.top(); 12 | h.pop(); 13 | long long int s = h.top(); 14 | h.pop(); 15 | long long int n = (min(f, s) * 2) + max(f, s); 16 | h.push(n); 17 | c++; 18 | } 19 | return c; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /3105. Longest Strictly Increasing or Strictly Decreasing Subarray: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public: 4 | int longestMonotonicSubarray(vector& nums) { 5 | int in = 1, de = 1 , ans = 1; 6 | for ( int i = 1 ; i < nums.size() ; i++) { 7 | if( nums[i-1] < nums[i]) { 8 | de = 1; 9 | in++; 10 | } 11 | else if( nums[i-1] > nums[i]) { 12 | in = 1; 13 | de++; 14 | } 15 | else { 16 | in = de = 1; 17 | } 18 | ans = max({in, de, ans}); 19 | } 20 | return ans; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /3110. Score of a String: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int scoreOfString(string s) { 4 | int sum = 0; 5 | for (int i = 1; i < s.size(); i++) { 6 | sum += abs(s[i - 1] - s[i]); 7 | } 8 | return sum; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /3151. Special Array I: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isArraySpecial(vector& nums) { 4 | if( nums.size() == 1 ) return 1; 5 | 6 | for ( int i = 1 ; i < nums.size() ; i++) { 7 | if( nums[i-1]%2 == nums[i]%2) 8 | return 0; 9 | } 10 | return 1; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /3174. Clear Digits: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string clearDigits(string s) { 4 | string ans; 5 | 6 | for (auto i : s) { 7 | if(!isdigit(i)) 8 | ans.push_back(i); 9 | 10 | else { 11 | if(!ans.empty()) 12 | ans.pop_back(); 13 | } 14 | } 15 | return ans; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /3190. Find Minimum Operations to Make All Elements Divisible by Three: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimumOperations(vector& nums) { 4 | int ans = 0 ; 5 | for( int i : nums){ 6 | if(i % 3 != 0 ) ans++; 7 | } 8 | return ans; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /3191. Minimum Operations to Make Binary Array Elements Equal to One I: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minOperations(vector& nums) { 4 | 5 | 6 | int c = 0; 7 | for ( int i = 0 ; i < nums.size() ; i++) { 8 | 9 | if ( nums[i] == 0) { 10 | if (i + 2 < nums.size()) { 11 | nums[i] = !nums[i]; 12 | nums[i+1] = !nums[i+1]; 13 | nums[i+2] = !nums[i+2]; 14 | c++; 15 | }else return -1; 16 | } 17 | 18 | } 19 | return c; 20 | 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /3206. Alternating Groups I: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numberOfAlternatingGroups(vector& c) { 4 | int n = c.size(); 5 | int count = 0; 6 | int vl = 1; 7 | 8 | for ( int i = 1 ; i < n + 2 ; i++) { 9 | if( c[i%n] != c[(i - 1) % n]) { 10 | vl++; 11 | if(vl>= 3) count++; 12 | }else vl = 1; 13 | } return count; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /3208. Alternating Groups II: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numberOfAlternatingGroups(vector& c, int k) { 4 | 5 | int n = c.size(); 6 | int count = 0; 7 | int vl = 1; 8 | 9 | for ( int i = 1 ; i < n + k -1 ; i++) { 10 | if( c[(i % n)] != c[(i - 1) % n]) { 11 | vl++; 12 | if(vl >= k) count++; 13 | } else vl = 1; 14 | } return count; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /3210. Find the Encrypted String: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string getEncryptedString(string s, int k) { 4 | string ans(s.length(), ' '); 5 | for ( int i = 0 ; i < s.length() ; i++){ 6 | ans[i] = s[(i+k) % (s.length())]; 7 | } 8 | return ans; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /3306. Count of Substrings Containing Every Vowel and K Consonants II: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isVowel(char c) { 4 | return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; 5 | } 6 | 7 | long long atLeastK(string& word, int k) { 8 | int n = word.size(); 9 | long long ans = 0; 10 | int consonants = 0; 11 | int left = 0; 12 | unordered_map vowel_map; 13 | 14 | for (int right = 0; right < n; right++) { 15 | if (isVowel(word[right])) { 16 | vowel_map[word[right]]++; 17 | } else { 18 | consonants++; 19 | } 20 | 21 | while (vowel_map.size() == 5 && consonants >= k) { 22 | ans += n - right; 23 | if (isVowel(word[left])) { 24 | vowel_map[word[left]]--; 25 | if (vowel_map[word[left]] == 0) { 26 | vowel_map.erase(word[left]); 27 | } 28 | } else { 29 | consonants--; 30 | } 31 | left++; 32 | } 33 | } 34 | return ans; 35 | } 36 | 37 | long long countOfSubstrings(string word, int k) { 38 | return atLeastK(word, k) - atLeastK(word, k + 1); 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /3356. Zero Array Transformation II: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minZeroArray(vector& nums, vector>& queries) { 4 | int n = nums.size(), sum = 0, k = 0; 5 | vector differenceArray(n + 1); 6 | for (int index = 0; index < n; index++) { 7 | while (sum + differenceArray[index] < nums[index]) { 8 | k++; 9 | if (k > queries.size()) { 10 | return -1; 11 | } 12 | int left = queries[k - 1][0], right = queries[k - 1][1], 13 | val = queries[k - 1][2]; 14 | 15 | if (right >= index) { 16 | differenceArray[max(left, index)] += val; 17 | differenceArray[right + 1] -= val; 18 | } 19 | } 20 | sum += differenceArray[index]; 21 | } 22 | return k; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /3392. Count Subarrays of Length Three With a Condition: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countSubarrays(vector& nums) { 4 | int n = nums.size(); 5 | int ans = 0; 6 | for (int i = 1; i < n - 1; ++i) { 7 | if (nums[i] == (nums[i - 1] + nums[i + 1]) * 2) { 8 | ++ans; 9 | } 10 | } 11 | return ans; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /3396. Minimum Number of Operations to Make Elements in Array Distinct: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minimumOperations(vector& nums) { 4 | unordered_set seen; 5 | int pos = -1; 6 | for (int i = nums.size() - 1; i >= 0; --i) { 7 | if (seen.count(nums[i])) { 8 | pos = i; 9 | break; 10 | } 11 | seen.insert(nums[i]); 12 | } 13 | if (pos == -1) return 0; 14 | return (pos + 1 + 2) / 3; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /3487. Maximum Unique Subarray Sum After Deletion: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxSum(vector& nums) { 4 | int maxi = INT_MIN; 5 | int sum = 0; 6 | unordered_set st; 7 | for (int i : nums) { 8 | maxi = max(maxi, i); 9 | if (i > 0 && st.find(i) == st.end()) { 10 | sum += i; 11 | st.insert(i); 12 | } 13 | } 14 | return (sum == 0) ? maxi : sum; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LeetCode Submissions 2 | 3 | Welcome to my LeetCode Submissions repository! Here, I upload my daily solutions to various LeetCode problems. Each solution is saved as a separate file in the root directory. 4 | 5 | 6 | ## Usage 7 | 8 | 1. **Find the solution file**: Each file is named following the pattern `_problem_name` or a similar naming convention based on the problem title. 9 | 2. **Understand the solution**: Each solution file includes comments and explanations to help you understand the approach and logic used. 10 | 11 | ## Daily Updates 12 | 13 | I aim to upload at least one solution per day. Keep an eye on this repository for regular updates and new solutions. 14 | 15 | ## Algorithms Repository 16 | 17 | I also maintain a separate repository that contains detailed explanations and implementations of various algorithms used in my LeetCode solutions. You can check it out [here](https://github.com/mridul0703/Algorithms). 18 | 19 | ## Contributing 20 | 21 | I welcome contributions and suggestions! If you have a better solution or an alternative approach to any problem, feel free to create a pull request. 22 | 23 | ## Contact 24 | 25 | If you have any questions or suggestions, feel free to reach out to me via [email@example.com](mailto:mridulmkumar07@gmail.com). 26 | 27 | ## License 28 | 29 | This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. 30 | 31 | 32 | --------------------------------------------------------------------------------